From 031446716f03074b98290cb7224a3dee32cece2e Mon Sep 17 00:00:00 2001 From: David Lafreniere Date: Fri, 20 Nov 2026 05:31:34 -0800 Subject: [PATCH] SQLite 3.54.1; fetch DelegateMQ v2.4.1 instead of a bundled copy - SQLite: update the amalgamation from 3.47.0 to 3.54.1 (SHA3-256 checked against sqlite.org). Remove shell.c, the sqlite3 command-line tool. - DelegateMQ: CMake FetchContent at DMQ_GIT_TAG (v2.4.1), linking the DelegateMQ::DelegateMQ target, replaces the bundled DelegateMQ/ folder. FETCHCONTENT_SOURCE_DIR_DELEGATEMQ builds against a local checkout. - CI: a weekly job (and manual run) builds against DelegateMQ master. - README: dependencies and build options. Co-Authored-By: Claude Opus 5.5 --- .gitattributes | 1 - .github/workflows/dmq_latest.yml | 33 + CMakeLists.txt | 69 +- DelegateMQ/Common.cmake | 40 - DelegateMQ/Defaults.cmake | 127 - DelegateMQ/DelegateMQ.cmake | 99 - DelegateMQ/DelegateMQ.h | 297 - DelegateMQ/DepsDir.cmake | 25 - DelegateMQ/External.cmake | 459 - DelegateMQ/Macros.cmake | 52 - DelegateMQ/Port.cmake | 261 - DelegateMQ/delegate/Delegate.h | 997 - DelegateMQ/delegate/DelegateAsync.h | 1230 - DelegateMQ/delegate/DelegateAsyncWait.h | 1891 - .../delegate/DelegateMQConfig_Default.h | 194 - .../delegate/DelegateMQConfig_Template.h | 151 - DelegateMQ/delegate/DelegateMsg.h | 83 - DelegateMQ/delegate/DelegateOpt.h | 672 - DelegateMQ/delegate/DelegateRemote.h | 1688 - DelegateMQ/delegate/DelegateSelect.h | 182 - DelegateMQ/delegate/IDispatcher.h | 42 - DelegateMQ/delegate/IInvoker.h | 43 - DelegateMQ/delegate/ISerializer.h | 66 - DelegateMQ/delegate/IThread.h | 68 - DelegateMQ/delegate/MulticastDelegate.h | 326 - DelegateMQ/delegate/MulticastDelegateSafe.h | 248 - DelegateMQ/delegate/Semaphore.h | 89 - DelegateMQ/delegate/Signal.h | 395 - DelegateMQ/delegate/UnicastDelegate.h | 155 - DelegateMQ/delegate/UnicastDelegateSafe.h | 169 - DelegateMQ/delegate/make_tuple_heap.h | 244 - DelegateMQ/delegate/src_dup.py | 76 - DelegateMQ/extras/allocator/Allocator.cpp | 185 - DelegateMQ/extras/allocator/Allocator.h | 134 - DelegateMQ/extras/allocator/README.md | 64 - DelegateMQ/extras/allocator/stl_allocator.h | 79 - DelegateMQ/extras/allocator/xallocator.cpp | 493 - DelegateMQ/extras/allocator/xallocator.h | 153 - DelegateMQ/extras/allocator/xlist.h | 23 - DelegateMQ/extras/allocator/xmake_shared.h | 18 - DelegateMQ/extras/allocator/xmap.h | 39 - DelegateMQ/extras/allocator/xnew.h | 58 - DelegateMQ/extras/allocator/xqueue.h | 26 - DelegateMQ/extras/allocator/xset.h | 37 - DelegateMQ/extras/allocator/xsstream.h | 19 - DelegateMQ/extras/allocator/xstring.h | 16 - DelegateMQ/extras/databus/DataBus.h | 903 - DelegateMQ/extras/databus/DataBusQos.h | 28 - .../extras/databus/DeadlineSubscription.h | 149 - DelegateMQ/extras/databus/NetworkNode.h | 527 - DelegateMQ/extras/databus/Participant.h | 421 - DelegateMQ/extras/databus/README.md | 201 - DelegateMQ/extras/databus/SpyPacket.h | 44 - DelegateMQ/extras/dispatcher/Dispatcher.h | 79 - DelegateMQ/extras/dispatcher/README.md | 52 - DelegateMQ/extras/dispatcher/RemoteChannel.h | 391 - DelegateMQ/extras/rpc/README.md | 81 - DelegateMQ/extras/rpc/RemoteDispatcher.cpp | 217 - DelegateMQ/extras/rpc/RemoteDispatcher.h | 488 - DelegateMQ/extras/rpc/RemoteEndpoint.h | 80 - DelegateMQ/extras/util/AsyncInvoke.h | 153 - DelegateMQ/extras/util/ClockHelper.h | 36 - DelegateMQ/extras/util/Fault.h | 60 - DelegateMQ/extras/util/MonotonicGuard.h | 73 - DelegateMQ/extras/util/NetworkConnect.h | 118 - DelegateMQ/extras/util/README.md | 62 - DelegateMQ/extras/util/ReliableTransport.h | 111 - DelegateMQ/extras/util/RetryMonitor.h | 311 - DelegateMQ/extras/util/ThreadMonitor.cpp | 124 - DelegateMQ/extras/util/ThreadMonitor.h | 73 - DelegateMQ/extras/util/ThreadMonitorSer.h | 62 - DelegateMQ/extras/util/Timer.cpp | 252 - DelegateMQ/extras/util/Timer.h | 151 - DelegateMQ/extras/util/TimerDelegate.h | 374 - DelegateMQ/extras/util/TransportMonitor.h | 247 - DelegateMQ/extras/util/crc16.h | 91 - DelegateMQ/port/fault/Fault.cpp | 291 - DelegateMQ/port/os/README.md | 73 - .../port/os/bare-metal/BareMetalClock.h | 62 - .../os/bare-metal/BareMetalCriticalSection.h | 97 - .../port/os/bare-metal/BareMetalThisThread.h | 42 - .../port/os/cmsis-rtos2/CmsisRtos2Clock.h | 70 - .../cmsis-rtos2/CmsisRtos2CriticalSection.h | 86 - .../os/cmsis-rtos2/CmsisRtos2DelegateQueue.h | 168 - .../port/os/cmsis-rtos2/CmsisRtos2Mutex.h | 88 - .../port/os/cmsis-rtos2/CmsisRtos2Semaphore.h | 82 - .../os/cmsis-rtos2/CmsisRtos2ThisThread.h | 49 - .../port/os/cmsis-rtos2/CmsisRtos2Thread.cpp | 671 - .../port/os/cmsis-rtos2/CmsisRtos2Thread.h | 296 - .../port/os/cmsis-rtos2/CmsisRtos2Ticks.h | 70 - .../port/os/common/CurrentThreadStorage.h | 169 - .../port/os/common/PortableScopedLock.h | 61 - DelegateMQ/port/os/common/StartGate.h | 311 - DelegateMQ/port/os/common/ThreadHooks.h | 109 - DelegateMQ/port/os/common/ThreadMsg.h | 83 - DelegateMQ/port/os/freertos/FreeRTOSClock.h | 69 - .../os/freertos/FreeRTOSConditionVariable.h | 136 - .../os/freertos/FreeRTOSCriticalSection.h | 122 - .../port/os/freertos/FreeRTOSDelegateQueue.h | 191 - DelegateMQ/port/os/freertos/FreeRTOSMutex.h | 103 - .../port/os/freertos/FreeRTOSThisThread.h | 54 - .../port/os/freertos/FreeRTOSThread.cpp | 652 - DelegateMQ/port/os/freertos/FreeRTOSThread.h | 329 - DelegateMQ/port/os/nuttx/NuttXClock.h | 35 - .../port/os/nuttx/NuttXCriticalSection.h | 82 - DelegateMQ/port/os/nuttx/NuttXDelegateQueue.h | 186 - DelegateMQ/port/os/nuttx/NuttXMutex.h | 88 - DelegateMQ/port/os/nuttx/NuttXSemaphore.h | 102 - DelegateMQ/port/os/nuttx/NuttXThisThread.h | 54 - DelegateMQ/port/os/nuttx/NuttXThread.cpp | 664 - DelegateMQ/port/os/nuttx/NuttXThread.h | 294 - DelegateMQ/port/os/posix/PosixThread.cpp | 723 - DelegateMQ/port/os/posix/PosixThread.h | 329 - DelegateMQ/port/os/qt/QtThread.cpp | 574 - DelegateMQ/port/os/qt/QtThread.h | 341 - DelegateMQ/port/os/stdlib/StdlibThisThread.h | 29 - DelegateMQ/port/os/stdlib/StdlibThread.cpp | 685 - DelegateMQ/port/os/stdlib/StdlibThread.h | 311 - DelegateMQ/port/os/threadx/ThreadXClock.h | 56 - .../os/threadx/ThreadXConditionVariable.h | 113 - .../port/os/threadx/ThreadXCriticalSection.h | 89 - .../port/os/threadx/ThreadXDelegateQueue.h | 253 - DelegateMQ/port/os/threadx/ThreadXMutex.h | 48 - .../port/os/threadx/ThreadXThisThread.h | 57 - DelegateMQ/port/os/threadx/ThreadXThread.cpp | 761 - DelegateMQ/port/os/threadx/ThreadXThread.h | 328 - DelegateMQ/port/os/win32/Win32Thread.cpp | 652 - DelegateMQ/port/os/win32/Win32Thread.h | 314 - DelegateMQ/port/os/zephyr/ZephyrClock.h | 22 - .../port/os/zephyr/ZephyrCriticalSection.h | 72 - .../port/os/zephyr/ZephyrDelegateQueue.h | 187 - DelegateMQ/port/os/zephyr/ZephyrMutex.h | 43 - DelegateMQ/port/os/zephyr/ZephyrSemaphore.h | 77 - DelegateMQ/port/os/zephyr/ZephyrThisThread.h | 47 - DelegateMQ/port/os/zephyr/ZephyrThread.cpp | 684 - DelegateMQ/port/os/zephyr/ZephyrThread.h | 298 - DelegateMQ/port/serialize/README.md | 42 - .../serialize/bitsery/BitserySerializer.h | 84 - .../port/serialize/cereal/CerealSerializer.h | 53 - .../serialize/msgpack/MsgpackSerializer.h | 92 - .../serialize/rapidjson/RapidJsonSerializer.h | 88 - .../port/serialize/serialize/DmqSerializer.h | 51 - DelegateMQ/port/serialize/serialize/README.md | 121 - .../port/serialize/serialize/msg_serialize.h | 1874 - DelegateMQ/port/transport/README.md | 45 - .../ArmLwipNetconnUdpTransport.h | 278 - .../arm-lwip-udp/ArmLwipUdpTransport.h | 297 - DelegateMQ/port/transport/common/DmqHeader.h | 130 - DelegateMQ/port/transport/common/ITransport.h | 37 - .../port/transport/common/ITransportMonitor.h | 29 - .../transport/linux-tcp/LinuxTcpTransport.h | 386 - .../transport/linux-udp/LinuxUdpTransport.h | 324 - .../transport/linux-udp/MulticastTransport.h | 141 - .../transport/linux-uds/LinuxUdsTransport.h | 350 - .../port/transport/mqtt/MqttTransport.h | 350 - .../transport/netx-udp/NetXUdpTransport.h | 345 - DelegateMQ/port/transport/nng/NngTransport.h | 355 - .../port/transport/serial/SerialTransport.h | 245 - .../transport/stm32-uart/Stm32UartTransport.h | 347 - .../transport/win32-pipe/Win32PipeTransport.h | 225 - .../transport/win32-tcp/Win32TcpTransport.h | 398 - .../transport/win32-udp/MulticastTransport.h | 148 - .../transport/win32-udp/Win32UdpTransport.h | 312 - .../transport/zephyr-udp/ZephyrUdpTransport.h | 338 - .../port/transport/zeromq/ZeroMqTransport.h | 344 - README.md | 16 +- SQLite/CMakeLists.txt | 14 +- SQLite/shell.c | 33359 ---------------- SQLite/sqlite3.c | 32331 ++++++++++----- SQLite/sqlite3.h | 1573 +- SQLite/sqlite3ext.h | 42 +- UnitTest/CMakeLists.txt | 12 +- 172 files changed, 22862 insertions(+), 83221 deletions(-) create mode 100644 .github/workflows/dmq_latest.yml delete mode 100644 DelegateMQ/Common.cmake delete mode 100644 DelegateMQ/Defaults.cmake delete mode 100644 DelegateMQ/DelegateMQ.cmake delete mode 100644 DelegateMQ/DelegateMQ.h delete mode 100644 DelegateMQ/DepsDir.cmake delete mode 100644 DelegateMQ/External.cmake delete mode 100644 DelegateMQ/Macros.cmake delete mode 100644 DelegateMQ/Port.cmake delete mode 100644 DelegateMQ/delegate/Delegate.h delete mode 100644 DelegateMQ/delegate/DelegateAsync.h delete mode 100644 DelegateMQ/delegate/DelegateAsyncWait.h delete mode 100644 DelegateMQ/delegate/DelegateMQConfig_Default.h delete mode 100644 DelegateMQ/delegate/DelegateMQConfig_Template.h delete mode 100644 DelegateMQ/delegate/DelegateMsg.h delete mode 100644 DelegateMQ/delegate/DelegateOpt.h delete mode 100644 DelegateMQ/delegate/DelegateRemote.h delete mode 100644 DelegateMQ/delegate/DelegateSelect.h delete mode 100644 DelegateMQ/delegate/IDispatcher.h delete mode 100644 DelegateMQ/delegate/IInvoker.h delete mode 100644 DelegateMQ/delegate/ISerializer.h delete mode 100644 DelegateMQ/delegate/IThread.h delete mode 100644 DelegateMQ/delegate/MulticastDelegate.h delete mode 100644 DelegateMQ/delegate/MulticastDelegateSafe.h delete mode 100644 DelegateMQ/delegate/Semaphore.h delete mode 100644 DelegateMQ/delegate/Signal.h delete mode 100644 DelegateMQ/delegate/UnicastDelegate.h delete mode 100644 DelegateMQ/delegate/UnicastDelegateSafe.h delete mode 100644 DelegateMQ/delegate/make_tuple_heap.h delete mode 100644 DelegateMQ/delegate/src_dup.py delete mode 100644 DelegateMQ/extras/allocator/Allocator.cpp delete mode 100644 DelegateMQ/extras/allocator/Allocator.h delete mode 100644 DelegateMQ/extras/allocator/README.md delete mode 100644 DelegateMQ/extras/allocator/stl_allocator.h delete mode 100644 DelegateMQ/extras/allocator/xallocator.cpp delete mode 100644 DelegateMQ/extras/allocator/xallocator.h delete mode 100644 DelegateMQ/extras/allocator/xlist.h delete mode 100644 DelegateMQ/extras/allocator/xmake_shared.h delete mode 100644 DelegateMQ/extras/allocator/xmap.h delete mode 100644 DelegateMQ/extras/allocator/xnew.h delete mode 100644 DelegateMQ/extras/allocator/xqueue.h delete mode 100644 DelegateMQ/extras/allocator/xset.h delete mode 100644 DelegateMQ/extras/allocator/xsstream.h delete mode 100644 DelegateMQ/extras/allocator/xstring.h delete mode 100644 DelegateMQ/extras/databus/DataBus.h delete mode 100644 DelegateMQ/extras/databus/DataBusQos.h delete mode 100644 DelegateMQ/extras/databus/DeadlineSubscription.h delete mode 100644 DelegateMQ/extras/databus/NetworkNode.h delete mode 100644 DelegateMQ/extras/databus/Participant.h delete mode 100644 DelegateMQ/extras/databus/README.md delete mode 100644 DelegateMQ/extras/databus/SpyPacket.h delete mode 100644 DelegateMQ/extras/dispatcher/Dispatcher.h delete mode 100644 DelegateMQ/extras/dispatcher/README.md delete mode 100644 DelegateMQ/extras/dispatcher/RemoteChannel.h delete mode 100644 DelegateMQ/extras/rpc/README.md delete mode 100644 DelegateMQ/extras/rpc/RemoteDispatcher.cpp delete mode 100644 DelegateMQ/extras/rpc/RemoteDispatcher.h delete mode 100644 DelegateMQ/extras/rpc/RemoteEndpoint.h delete mode 100644 DelegateMQ/extras/util/AsyncInvoke.h delete mode 100644 DelegateMQ/extras/util/ClockHelper.h delete mode 100644 DelegateMQ/extras/util/Fault.h delete mode 100644 DelegateMQ/extras/util/MonotonicGuard.h delete mode 100644 DelegateMQ/extras/util/NetworkConnect.h delete mode 100644 DelegateMQ/extras/util/README.md delete mode 100644 DelegateMQ/extras/util/ReliableTransport.h delete mode 100644 DelegateMQ/extras/util/RetryMonitor.h delete mode 100644 DelegateMQ/extras/util/ThreadMonitor.cpp delete mode 100644 DelegateMQ/extras/util/ThreadMonitor.h delete mode 100644 DelegateMQ/extras/util/ThreadMonitorSer.h delete mode 100644 DelegateMQ/extras/util/Timer.cpp delete mode 100644 DelegateMQ/extras/util/Timer.h delete mode 100644 DelegateMQ/extras/util/TimerDelegate.h delete mode 100644 DelegateMQ/extras/util/TransportMonitor.h delete mode 100644 DelegateMQ/extras/util/crc16.h delete mode 100644 DelegateMQ/port/fault/Fault.cpp delete mode 100644 DelegateMQ/port/os/README.md delete mode 100644 DelegateMQ/port/os/bare-metal/BareMetalClock.h delete mode 100644 DelegateMQ/port/os/bare-metal/BareMetalCriticalSection.h delete mode 100644 DelegateMQ/port/os/bare-metal/BareMetalThisThread.h delete mode 100644 DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Clock.h delete mode 100644 DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2CriticalSection.h delete mode 100644 DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2DelegateQueue.h delete mode 100644 DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Mutex.h delete mode 100644 DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Semaphore.h delete mode 100644 DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2ThisThread.h delete mode 100644 DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.cpp delete mode 100644 DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.h delete mode 100644 DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Ticks.h delete mode 100644 DelegateMQ/port/os/common/CurrentThreadStorage.h delete mode 100644 DelegateMQ/port/os/common/PortableScopedLock.h delete mode 100644 DelegateMQ/port/os/common/StartGate.h delete mode 100644 DelegateMQ/port/os/common/ThreadHooks.h delete mode 100644 DelegateMQ/port/os/common/ThreadMsg.h delete mode 100644 DelegateMQ/port/os/freertos/FreeRTOSClock.h delete mode 100644 DelegateMQ/port/os/freertos/FreeRTOSConditionVariable.h delete mode 100644 DelegateMQ/port/os/freertos/FreeRTOSCriticalSection.h delete mode 100644 DelegateMQ/port/os/freertos/FreeRTOSDelegateQueue.h delete mode 100644 DelegateMQ/port/os/freertos/FreeRTOSMutex.h delete mode 100644 DelegateMQ/port/os/freertos/FreeRTOSThisThread.h delete mode 100644 DelegateMQ/port/os/freertos/FreeRTOSThread.cpp delete mode 100644 DelegateMQ/port/os/freertos/FreeRTOSThread.h delete mode 100644 DelegateMQ/port/os/nuttx/NuttXClock.h delete mode 100644 DelegateMQ/port/os/nuttx/NuttXCriticalSection.h delete mode 100644 DelegateMQ/port/os/nuttx/NuttXDelegateQueue.h delete mode 100644 DelegateMQ/port/os/nuttx/NuttXMutex.h delete mode 100644 DelegateMQ/port/os/nuttx/NuttXSemaphore.h delete mode 100644 DelegateMQ/port/os/nuttx/NuttXThisThread.h delete mode 100644 DelegateMQ/port/os/nuttx/NuttXThread.cpp delete mode 100644 DelegateMQ/port/os/nuttx/NuttXThread.h delete mode 100644 DelegateMQ/port/os/posix/PosixThread.cpp delete mode 100644 DelegateMQ/port/os/posix/PosixThread.h delete mode 100644 DelegateMQ/port/os/qt/QtThread.cpp delete mode 100644 DelegateMQ/port/os/qt/QtThread.h delete mode 100644 DelegateMQ/port/os/stdlib/StdlibThisThread.h delete mode 100644 DelegateMQ/port/os/stdlib/StdlibThread.cpp delete mode 100644 DelegateMQ/port/os/stdlib/StdlibThread.h delete mode 100644 DelegateMQ/port/os/threadx/ThreadXClock.h delete mode 100644 DelegateMQ/port/os/threadx/ThreadXConditionVariable.h delete mode 100644 DelegateMQ/port/os/threadx/ThreadXCriticalSection.h delete mode 100644 DelegateMQ/port/os/threadx/ThreadXDelegateQueue.h delete mode 100644 DelegateMQ/port/os/threadx/ThreadXMutex.h delete mode 100644 DelegateMQ/port/os/threadx/ThreadXThisThread.h delete mode 100644 DelegateMQ/port/os/threadx/ThreadXThread.cpp delete mode 100644 DelegateMQ/port/os/threadx/ThreadXThread.h delete mode 100644 DelegateMQ/port/os/win32/Win32Thread.cpp delete mode 100644 DelegateMQ/port/os/win32/Win32Thread.h delete mode 100644 DelegateMQ/port/os/zephyr/ZephyrClock.h delete mode 100644 DelegateMQ/port/os/zephyr/ZephyrCriticalSection.h delete mode 100644 DelegateMQ/port/os/zephyr/ZephyrDelegateQueue.h delete mode 100644 DelegateMQ/port/os/zephyr/ZephyrMutex.h delete mode 100644 DelegateMQ/port/os/zephyr/ZephyrSemaphore.h delete mode 100644 DelegateMQ/port/os/zephyr/ZephyrThisThread.h delete mode 100644 DelegateMQ/port/os/zephyr/ZephyrThread.cpp delete mode 100644 DelegateMQ/port/os/zephyr/ZephyrThread.h delete mode 100644 DelegateMQ/port/serialize/README.md delete mode 100644 DelegateMQ/port/serialize/bitsery/BitserySerializer.h delete mode 100644 DelegateMQ/port/serialize/cereal/CerealSerializer.h delete mode 100644 DelegateMQ/port/serialize/msgpack/MsgpackSerializer.h delete mode 100644 DelegateMQ/port/serialize/rapidjson/RapidJsonSerializer.h delete mode 100644 DelegateMQ/port/serialize/serialize/DmqSerializer.h delete mode 100644 DelegateMQ/port/serialize/serialize/README.md delete mode 100644 DelegateMQ/port/serialize/serialize/msg_serialize.h delete mode 100644 DelegateMQ/port/transport/README.md delete mode 100644 DelegateMQ/port/transport/arm-lwip-netconn-udp/ArmLwipNetconnUdpTransport.h delete mode 100644 DelegateMQ/port/transport/arm-lwip-udp/ArmLwipUdpTransport.h delete mode 100644 DelegateMQ/port/transport/common/DmqHeader.h delete mode 100644 DelegateMQ/port/transport/common/ITransport.h delete mode 100644 DelegateMQ/port/transport/common/ITransportMonitor.h delete mode 100644 DelegateMQ/port/transport/linux-tcp/LinuxTcpTransport.h delete mode 100644 DelegateMQ/port/transport/linux-udp/LinuxUdpTransport.h delete mode 100644 DelegateMQ/port/transport/linux-udp/MulticastTransport.h delete mode 100644 DelegateMQ/port/transport/linux-uds/LinuxUdsTransport.h delete mode 100644 DelegateMQ/port/transport/mqtt/MqttTransport.h delete mode 100644 DelegateMQ/port/transport/netx-udp/NetXUdpTransport.h delete mode 100644 DelegateMQ/port/transport/nng/NngTransport.h delete mode 100644 DelegateMQ/port/transport/serial/SerialTransport.h delete mode 100644 DelegateMQ/port/transport/stm32-uart/Stm32UartTransport.h delete mode 100644 DelegateMQ/port/transport/win32-pipe/Win32PipeTransport.h delete mode 100644 DelegateMQ/port/transport/win32-tcp/Win32TcpTransport.h delete mode 100644 DelegateMQ/port/transport/win32-udp/MulticastTransport.h delete mode 100644 DelegateMQ/port/transport/win32-udp/Win32UdpTransport.h delete mode 100644 DelegateMQ/port/transport/zephyr-udp/ZephyrUdpTransport.h delete mode 100644 DelegateMQ/port/transport/zeromq/ZeroMqTransport.h delete mode 100644 SQLite/shell.c diff --git a/.gitattributes b/.gitattributes index 8d35b88..16bcd42 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,4 +2,3 @@ SQLite/sqlite3.c linguist-vendored SQLite/sqlite3.h linguist-vendored SQLite/sqlite3ext.h linguist-vendored -SQLite/shell.c linguist-vendored diff --git a/.github/workflows/dmq_latest.yml b/.github/workflows/dmq_latest.yml new file mode 100644 index 0000000..be5e51e --- /dev/null +++ b/.github/workflows/dmq_latest.yml @@ -0,0 +1,33 @@ +name: DelegateMQ latest + +# Builds and tests against DelegateMQ's latest code instead of the pinned +# release (DMQ_GIT_TAG in CMakeLists.txt), so a DelegateMQ change that would +# break this wrapper shows up before the next DelegateMQ release. It only +# reports: pull requests are checked by the pinned-release workflows. + +on: + schedule: + - cron: '0 6 * * 1' # Mondays, 06:00 UTC + workflow_dispatch: + inputs: + dmq_ref: + description: 'DelegateMQ branch or tag to build against' + required: false + default: 'master' + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v7 + + - name: Configure CMake + run: cmake -S . -B build -DDMQ_GIT_TAG=${{ github.event.inputs.dmq_ref || 'master' }} + + - name: Build + run: cmake --build build + + - name: Run Async-SQLiteApp + run: ./build/Async-SQLiteApp diff --git a/CMakeLists.txt b/CMakeLists.txt index ad31d2b..aa2433a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,55 +1,52 @@ # Example CMake command line to create project build files: # -# cmake -B Build . +# cmake -B build . +# +# DelegateMQ is fetched from GitHub at the release tag DMQ_GIT_TAG when CMake +# configures. To build against a local DelegateMQ checkout instead, add +# -DFETCHCONTENT_SOURCE_DIR_DELEGATEMQ=. To configure again without +# network access, add -DFETCHCONTENT_FULLY_DISCONNECTED=ON. # Specify the minimum CMake version required -cmake_minimum_required(VERSION 3.10) +cmake_minimum_required(VERSION 3.16) # Project name and language (C or C++) -project(Async-SQLite VERSION 1.0 LANGUAGES C CXX) - -# Set build options -set (DMQ_ALLOCATOR "OFF") -set (DMQ_UTIL "ON") -set (DMQ_THREAD "DMQ_THREAD_STDLIB") -set (DMQ_SERIALIZE "DMQ_SERIALIZE_NONE") -set (DMQ_TRANSPORT "DMQ_TRANSPORT_NONE") -include("${CMAKE_SOURCE_DIR}/DelegateMQ/DelegateMQ.cmake") +project(Async-SQLite VERSION 1.1.0 LANGUAGES C CXX) # Set C++ standard set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED True) -# Collect all .cpp and *.h source files in the current directory -file(GLOB SOURCES "*.cpp" "*.h") - -# Collect DelegateMQ predef source files -list(APPEND SOURCES ${DMQ_PORT_SOURCES}) - -# Organize delegate source files within IDE (Visual Studio) -source_group("Delegate Files" FILES ${DMQ_LIB_SOURCES}) -source_group("Port Files" FILES ${DMQ_PORT_ONLY_SOURCES}) -source_group("Extras Files" FILES ${DMQ_EXTRAS_SOURCES}) - -# Add subdirectories to include path -include_directories( - ${DMQ_ROOT_DIR} - SQLite - Port - UnitTest +# DelegateMQ build options, set before DelegateMQ is added +set(DMQ_ALLOCATOR "OFF") +set(DMQ_UTIL "ON") +set(DMQ_THREAD "DMQ_THREAD_STDLIB") +set(DMQ_SERIALIZE "DMQ_SERIALIZE_NONE") +set(DMQ_TRANSPORT "DMQ_TRANSPORT_NONE") + +# DelegateMQ release to build against +set(DMQ_GIT_TAG "v2.4.1" CACHE STRING "DelegateMQ release tag (or branch) to fetch") + +include(FetchContent) +FetchContent_Declare( + delegatemq + GIT_REPOSITORY https://github.com/DelegateMQ/DelegateMQ.git + GIT_TAG ${DMQ_GIT_TAG} + GIT_SHALLOW TRUE ) +FetchContent_MakeAvailable(delegatemq) -# Add an executable target -add_executable(Async-SQLiteApp ${SOURCES} ${DMQ_LIB_SOURCES}) - -# Add subdirectories to build +# SQLite and the async wrapper (SQLiteLib links DelegateMQ::DelegateMQ) add_subdirectory(SQLite) + +# Unit tests add_subdirectory(UnitTest) -target_link_libraries(Async-SQLiteApp PRIVATE +# Example application +file(GLOB SOURCES "*.cpp" "*.h") +add_executable(Async-SQLiteApp ${SOURCES}) + +target_link_libraries(Async-SQLiteApp PRIVATE SQLiteLib UnitTestLib ) - - - diff --git a/DelegateMQ/Common.cmake b/DelegateMQ/Common.cmake deleted file mode 100644 index b66815b..0000000 --- a/DelegateMQ/Common.cmake +++ /dev/null @@ -1,40 +0,0 @@ -# C++17 minimum. A newer standard the including project already chose (e.g. -# set(CMAKE_CXX_STANDARD 20) before including DelegateMQ.cmake) is kept; an -# older one is raised to 17, which DelegateMQ needs. 98 is listed explicitly -# because it compares as greater than 17. -if(NOT DEFINED CMAKE_CXX_STANDARD OR CMAKE_CXX_STANDARD MATCHES "^(98|11|14)$") - set(CMAKE_CXX_STANDARD 17) - set(CMAKE_CXX_STANDARD_REQUIRED True) -endif() - -# Global silence for MSVC deprecation warnings (Standard for latest compilers) -if (MSVC) - # /utf-8 travels with the dmq_add_library() target too (DelegateMQ headers - # are UTF-8); /MP is a build-speed choice left to the including project. - list(APPEND DMQ_COMPILE_OPTIONS "/utf-8") - if(NOT DMQ_NO_GLOBAL_DEFINITIONS) - add_compile_options("/utf-8") - add_compile_options("/MP") - endif() - set(DMQ_STRICT_FLAGS "/W4" "/WX" "/analyze" "/analyze:external-" "/permissive-" "/Zc:__cplusplus" "/Zc:inline") - dmq_compile_definitions(_SILENCE_STDEXT_ARR_ITERS_DEPRECATION_WARNING) - dmq_compile_definitions(_SILENCE_ALL_MS_EXT_DEPRECATION_WARNINGS) - - # Fix for spdlog bundled fmt in C++20 mode. Kept directory-wide only: these - # change iterator checking for everything they reach, so the - # dmq_add_library() target carries them only when DMQ_LOG pulls in spdlog. - if(NOT DMQ_NO_GLOBAL_DEFINITIONS) - add_compile_definitions(FMT_USE_ITERATOR_TRAITS=1) - add_compile_definitions(FMT_MSVC_CRT_ITERATORS=0) - add_compile_definitions(_SECURE_SCL=0) - endif() - if(DMQ_LOG STREQUAL "ON") - list(APPEND DMQ_COMPILE_DEFINITIONS FMT_USE_ITERATOR_TRAITS=1 FMT_MSVC_CRT_ITERATORS=0 _SECURE_SCL=0) - endif() -else() - # Add -rdynamic to ensure function names are available in stack traces on Linux - set(DMQ_STRICT_FLAGS "-Wall" "-Wextra" "-Werror" "-Wpedantic" "-Wconversion" "-Wshadow" "-rdynamic") -endif() - - - diff --git a/DelegateMQ/Defaults.cmake b/DelegateMQ/Defaults.cmake deleted file mode 100644 index 84df6e2..0000000 --- a/DelegateMQ/Defaults.cmake +++ /dev/null @@ -1,127 +0,0 @@ -# DelegateMQ Defaults -# -# This module auto-selects default DelegateMQ build options based on the target platform. -# Options can be overridden by setting the variables before including DelegateMQ.cmake. - -# Forget the defaults an earlier include in this scope (or a parent's) filled -# in, so a second configuration recomputes them from its own options, e.g. -# DMQ_DATABUS from a new DMQ_THREAD. A value the caller set, or changed since, -# is kept. -foreach(_dmq_var IN LISTS _DMQ_AUTO_DEFAULTS) - if("${${_dmq_var}}" STREQUAL "${_DMQ_AUTO_VALUE_${_dmq_var}}") - unset(${_dmq_var}) - endif() -endforeach() -set(_DMQ_AUTO_DEFAULTS "") - -# --- Threading Defaults --- -if(NOT DEFINED DMQ_THREAD) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_THREAD) - if(WIN32 OR UNIX) - set(DMQ_THREAD "DMQ_THREAD_STDLIB") - elseif(FREERTOS OR FREE_RTOS) - set(DMQ_THREAD "DMQ_THREAD_FREERTOS") - elseif(THREADX) - set(DMQ_THREAD "DMQ_THREAD_THREADX") - elseif(ZEPHYR) - set(DMQ_THREAD "DMQ_THREAD_ZEPHYR") - elseif(CMSIS_RTOS2) - set(DMQ_THREAD "DMQ_THREAD_CMSIS_RTOS2") - elseif(NUTTX) - set(DMQ_THREAD "DMQ_THREAD_NUTTX") - else() - set(DMQ_THREAD "DMQ_THREAD_NONE") - endif() -endif() - -# --- Transport Defaults --- -if(NOT DEFINED DMQ_TRANSPORT) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_TRANSPORT) - if(WIN32) - set(DMQ_TRANSPORT "DMQ_TRANSPORT_WIN32_UDP") - elseif(UNIX AND NOT APPLE) - set(DMQ_TRANSPORT "DMQ_TRANSPORT_LINUX_UDP") - else() - set(DMQ_TRANSPORT "DMQ_TRANSPORT_NONE") - endif() -endif() - -# --- Serialization Defaults --- -if(NOT DEFINED DMQ_SERIALIZE) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_SERIALIZE) - if(WIN32 OR UNIX) - set(DMQ_SERIALIZE "DMQ_SERIALIZE_SERIALIZE") - else() - set(DMQ_SERIALIZE "DMQ_SERIALIZE_NONE") - endif() -endif() - -# --- Utility Class Defaults --- -if(NOT DEFINED DMQ_UTIL) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_UTIL) - set(DMQ_UTIL "ON") -endif() - -# --- DataBus Defaults --- -# Keyed off DMQ_THREAD (the actual target), not WIN32/UNIX (the host doing -# the compiling) -- DMQ_THREAD is already resolved above, and every RTOS -# simulator sample (freertos-linux, threadx-linux, zephyr-linux) compiles -# with a host GCC on a UNIX box despite targeting an embedded thread port, -# which used to default DMQ_DATABUS on for them too. DataBus's -# NetworkConnect.h reaches for the host's own BSD socket headers -# unconditionally on Linux/macOS/Windows, which both wastes flash on a real -# embedded build and can conflict outright with a target's own native -# network stack headers (e.g. Zephyr's redefining -# sockaddr_in et al.) if a sample also pulls those in directly. RTOS/bare- -# metal targets that genuinely want DataBus (e.g. databus-freertos/server) -# already opt in explicitly by setting DMQ_DATABUS "ON" themselves. -# -# This exclusion list must stay in sync with DelegateSelect.h's -# DMQ_THREAD_IS_EMBEDDED_RTOS macro (FreeRTOS/ThreadX/Zephyr/CMSIS-RTOS2/ -# NuttX) -- adding a new DMQ_THREAD_* port there means adding it here too. -# DMQ_THREAD_NONE (bare metal) is excluded as well: there is no host to -# speak of. -if(NOT DEFINED DMQ_DATABUS) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_DATABUS) - if(DMQ_THREAD STREQUAL "DMQ_THREAD_FREERTOS" OR DMQ_THREAD STREQUAL "DMQ_THREAD_THREADX" OR - DMQ_THREAD STREQUAL "DMQ_THREAD_ZEPHYR" OR DMQ_THREAD STREQUAL "DMQ_THREAD_CMSIS_RTOS2" OR - DMQ_THREAD STREQUAL "DMQ_THREAD_NUTTX" OR - DMQ_THREAD STREQUAL "DMQ_THREAD_NONE") - set(DMQ_DATABUS "OFF") - else() - set(DMQ_DATABUS "ON") - endif() -endif() - -# --- DataBus Tools Defaults --- -if(NOT DEFINED DMQ_DATABUS_TOOLS) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_DATABUS_TOOLS) - if(DMQ_DATABUS STREQUAL "ON" AND (WIN32 OR UNIX)) - set(DMQ_DATABUS_TOOLS "ON") - else() - set(DMQ_DATABUS_TOOLS "OFF") - endif() -endif() - -# --- Allocator Defaults --- -if(NOT DEFINED DMQ_ALLOCATOR) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_ALLOCATOR) - set(DMQ_ALLOCATOR "OFF") -endif() - -# --- Assert Defaults --- -if(NOT DEFINED DMQ_ASSERTS) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_ASSERTS) - set(DMQ_ASSERTS "OFF") -endif() - -# --- Logging Defaults --- -if(NOT DEFINED DMQ_LOG) - list(APPEND _DMQ_AUTO_DEFAULTS DMQ_LOG) - set(DMQ_LOG "OFF") -endif() - -# Remember what was filled in for the next include (see top of file) -foreach(_dmq_var IN LISTS _DMQ_AUTO_DEFAULTS) - set(_DMQ_AUTO_VALUE_${_dmq_var} "${${_dmq_var}}") -endforeach() diff --git a/DelegateMQ/DelegateMQ.cmake b/DelegateMQ/DelegateMQ.cmake deleted file mode 100644 index 92e007a..0000000 --- a/DelegateMQ/DelegateMQ.cmake +++ /dev/null @@ -1,99 +0,0 @@ -# DelegateMQ cmake module -# -# This module sets the following variables in your project: -# -# DMQ_INCLUDE_DIR - the directory containing DelegateMQ headers. -# DMQ_LIB_SOURCES - the core DelegateMQ delegate library files. -# DMQ_PORT_SOURCES - the predefined supporting source code files -# based on the DMQ build options. -# -# Set DMQ build options: -# -# # Optional: Set DMQ build options to override defaults. -# set(DMQ_THREAD "DMQ_THREAD_STDLIB") -# include("${CMAKE_SOURCE_DIR}/src/delegate-mq/DelegateMQ.cmake") -# -# Use variables to build: -# -# # Collect DelegateMQ port/extras source files -# list(APPEND SOURCES ${DMQ_PORT_SOURCES}) -# -# # Add include directory -# include_directories(${DMQ_INCLUDE_DIR}) -# -# Or build a library target that carries the options with it: -# -# dmq_add_library(dmq) -# target_link_libraries(my_app PRIVATE dmq) -# -# DMQ_COMPILE_DEFINITIONS, DMQ_COMPILE_OPTIONS, DMQ_EXTERNAL_INCLUDE_DIRS and -# DMQ_LINK_LIBRARIES hold that target's usage requirements. Definitions are -# also applied directory-wide (add_compile_definitions) unless -# DMQ_NO_GLOBAL_DEFINITIONS is set before the include. -# -# DMQ_USER_CONFIG - optional user config header name (e.g. "DelegateMQConfig.h") -# DMQ_USER_CONFIG_DIR - optional directory holding it, added to the target's includes - -macro(check _file) - if(NOT EXISTS "${_file}") - message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist!") - endif() -endmacro() - -macro(set_and_check _var _file) - set(${_var} "${_file}") - check("${_file}") -endmacro() - -# Reset per include so each configuration in one build tree starts clean. -set(DMQ_COMPILE_DEFINITIONS "") -set(DMQ_COMPILE_OPTIONS "") - -set_and_check(DMQ_ROOT_DIR "${CMAKE_CURRENT_LIST_DIR}") -set_and_check(DMQ_INCLUDE_DIR "${DMQ_ROOT_DIR}") - -# DMQ_DEPS_DIR: third-party repos fetched by 01_fetch_repos.py -check("${DMQ_ROOT_DIR}/DepsDir.cmake") -include ("${DMQ_ROOT_DIR}/DepsDir.cmake") - -check("${DMQ_ROOT_DIR}/Defaults.cmake") -include ("${DMQ_ROOT_DIR}/Defaults.cmake") - -check("${DMQ_ROOT_DIR}/Macros.cmake") -include ("${DMQ_ROOT_DIR}/Macros.cmake") - -check("${DMQ_ROOT_DIR}/Common.cmake") -include ("${DMQ_ROOT_DIR}/Common.cmake") - -check("${DMQ_ROOT_DIR}/Port.cmake") -include ("${DMQ_ROOT_DIR}/Port.cmake") - -check("${DMQ_ROOT_DIR}/External.cmake") -include ("${DMQ_ROOT_DIR}/External.cmake") - -if(DMQ_USER_CONFIG) - # Accept the name with or without surrounding quotes (-DDMQ_USER_CONFIG=\"x.h\") - string(REGEX REPLACE "^\"(.*)\"$" "\\1" _dmq_user_config "${DMQ_USER_CONFIG}") - dmq_compile_definitions(DMQ_USER_CONFIG="${_dmq_user_config}") -endif() - -if(DMQ_FORCE_OPTIMIZE_DEBUG) - dmq_compile_definitions(DMQ_FORCE_OPTIMIZE_DEBUG) -endif() - -# New option (Default OFF) -option(DMQ_STRICT "Enable strict DelegateMQ compiler warnings and errors" OFF) - -if (DMQ_STRICT) - message(STATUS "DelegateMQ: Strict build enabled (${DMQ_STRICT_FLAGS})") - - # Apply strict compile flags only to DelegateMQ source files - set_source_files_properties(${DMQ_LIB_SOURCES} ${DMQ_PORT_SOURCES} PROPERTIES COMPILE_OPTIONS "${DMQ_STRICT_FLAGS}") - - # On MSVC, different warning levels cause a PCH mismatch error (C4652). - # We disable PCH for these specific files to allow strict checking without affecting the whole target. - if (MSVC) - set_source_files_properties(${DMQ_LIB_SOURCES} ${DMQ_PORT_SOURCES} PROPERTIES COMPILE_FLAGS "/Y-") - endif() -endif() - diff --git a/DelegateMQ/DelegateMQ.h b/DelegateMQ/DelegateMQ.h deleted file mode 100644 index ccabfc8..0000000 --- a/DelegateMQ/DelegateMQ.h +++ /dev/null @@ -1,297 +0,0 @@ -#ifndef _DELEGATE_MQ_H -#define _DELEGATE_MQ_H - -// Delegate.h -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, 2025. - -/// @file DelegateMQ.h -/// @brief A single-include header for the complete DelegateMQ library functionality. -/// -/// @details -/// DelegateMQ is a robust C++ delegate library that enables invoking any callable function -/// (synchronously or asynchronously) on a specific user-defined thread of control. It also -/// supports remote function invocation over any transport protocol. -/// -/// **Key Features:** -/// * **Universal Target Support:** Binds to free functions, class member functions, static functions, -/// lambdas, and `std::function`. -/// * **Any Signature:** Handles any function signature with any number of arguments or return values. -/// * **Argument Safety:** Supports all argument types (value, pointer, pointer-to-pointer, reference) -/// and safely marshals them across thread boundaries for asynchronous calls. -/// * **Thread Control:** Unlike `std::async` (which uses a random thread pool), DelegateMQ executes -/// the target function on a *specific* destination thread you control. -/// * **Remote Invocation:** Capable of serializing arguments and invoking functions across network -/// boundaries (UDP, TCP, ZeroMQ, etc.). -/// -/// **Delegate Capabilities:** -/// A delegate instance behaves like a first-class object: -/// * **Copyable:** Can be copied freely. -/// * **Comparable:** Supports equality checks against other delegates or `nullptr`. -/// * **Assignable:** Can be reassigned at runtime. -/// * **Callable:** Invoked via `operator()`. -/// -/// **Common Use Cases:** -/// * Asynchronous Method Invocation (AMI) on specific worker threads. -/// * Publish / Subscribe (Observer) patterns. -/// * Anonymous, thread-safe asynchronous callbacks. -/// * Event-Driven Programming architectures. -/// * Thread-Safe Asynchronous APIs. -/// * Active Object design patterns. -/// -/// **Asynchronous Safety:** -/// Asynchronous variants automatically copy argument data into the event queue. This provides true -/// 'fire and forget' functionality, ensuring that out-of-scope stack variables in the caller -/// do not cause data races or corruption in the target thread. -/// -/// **Error Handling:** -/// The `Async` and `AsyncWait` variants may throw `std::bad_alloc` if heap allocation fails during -/// invocation. Alternatively, defining `DMQ_ASSERTS` switches error handling to assertions. -/// All other delegate functions are `noexcept`. -/// -/// **Documentation & Source:** -/// * Repository: https://github.com/DelegateMQ/DelegateMQ -/// * See `README.md`, `DETAILS.md`, and `EXAMPLES.md` for comprehensive guides. - -// ----------------------------------------------------------------------------- -// 0. Platform Configuration -// ----------------------------------------------------------------------------- -#if defined(_WIN32) || defined(_WIN64) - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #endif - #ifndef NOMINMAX - #define NOMINMAX - #endif -#endif - -// ----------------------------------------------------------------------------- -// 1. Core Non-Thread-Safe Delegates -// (Always available: Bare Metal, FreeRTOS, Windows, Linux) -// ----------------------------------------------------------------------------- -#include "delegate/Delegate.h" -#include "delegate/DelegateRemote.h" -#include "delegate/MulticastDelegate.h" -#include "delegate/UnicastDelegate.h" -#include "delegate/Signal.h" - -// ----------------------------------------------------------------------------- -// 2. Thread-Safe Wrappers (Mutex Only) -// ----------------------------------------------------------------------------- -// - FreeRTOS: Uses FreeRTOSRecursiveMutex -// - Bare Metal: Uses NullMutex -// - StdLib: Uses std::recursive_mutex -// Valid for any platform where a Mutex is defined in DelegateOpt.h -#if defined(DMQ_THREAD_STDLIB) || \ - defined(DMQ_THREAD_WIN32) || \ - defined(DMQ_THREAD_POSIX) || \ - defined(DMQ_THREAD_FREERTOS) || \ - defined(DMQ_THREAD_THREADX) || \ - defined(DMQ_THREAD_ZEPHYR) || \ - defined(DMQ_THREAD_CMSIS_RTOS2) || \ - defined(DMQ_THREAD_NUTTX) || \ - defined(DMQ_THREAD_QT) || \ - defined(DMQ_THREAD_NONE) - #include "delegate/MulticastDelegateSafe.h" - #include "delegate/UnicastDelegateSafe.h" -#endif - -// ----------------------------------------------------------------------------- -// 3. Asynchronous "Fire and Forget" Delegates -// ----------------------------------------------------------------------------- -// - FreeRTOS: OK -// - Bare Metal: OK (Requires you to implement IThread wrapper for Event Loop) -// - StdLib / Win32: OK -// Valid for any platform that implements the IThread interface -#if defined(DMQ_THREAD_STDLIB) || \ - defined(DMQ_THREAD_WIN32) || \ - defined(DMQ_THREAD_POSIX) || \ - defined(DMQ_THREAD_FREERTOS) || \ - defined(DMQ_THREAD_THREADX) || \ - defined(DMQ_THREAD_ZEPHYR) || \ - defined(DMQ_THREAD_CMSIS_RTOS2) || \ - defined(DMQ_THREAD_NUTTX) || \ - defined(DMQ_THREAD_QT) - #include "delegate/DelegateAsync.h" -#endif - -// ----------------------------------------------------------------------------- -// 4. Asynchronous "Blocking" Delegates (Wait for Result) -// ----------------------------------------------------------------------------- -// Depends on Semaphore/Mutex and C++17 (std::optional). -// Valid for StdLib/Win32 (Windows/Linux), Qt, ThreadX, FreeRTOS (if C++17 -// enabled), Zephyr, and CMSIS-RTOS2 -- the latter two via their native -// k_sem/osSemaphore-backed dmq::Semaphore, not the generic condvar+mutex -// implementation. DMQ_HAS_SEMAPHORE (DelegateOpt.h) is defined for exactly -// this set of ports, so it's used directly here instead of hand-copying the -// port list again. -#if defined(DMQ_HAS_SEMAPHORE) - #include "delegate/DelegateAsyncWait.h" -#endif - -#if defined(DMQ_THREAD_STDLIB) - #include "port/os/stdlib/StdlibThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_WIN32) - #include "port/os/win32/Win32Thread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_POSIX) - #include "port/os/posix/PosixThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_FREERTOS) - #include "port/os/freertos/FreeRTOSThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_THREADX) - #include "port/os/threadx/ThreadXThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_ZEPHYR) - #include "port/os/zephyr/ZephyrThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - #include "port/os/cmsis-rtos2/CmsisRtos2Thread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_NUTTX) - #include "port/os/nuttx/NuttXThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_QT) - #include "port/os/qt/QtThread.h" - #include "port/os/common/ThreadMsg.h" -#elif defined(DMQ_THREAD_NONE) - // Bare metal: User must implement their own polling/interrupt logic -#else - #warning "Thread implementation not found." - #define DMQ_THREAD_NONE -#endif - -#if defined(DMQ_SERIALIZE_MSGPACK) - #include "port/serialize/msgpack/MsgpackSerializer.h" -#elif defined(DMQ_SERIALIZE_CEREAL) - #include "port/serialize/cereal/CerealSerializer.h" -#elif defined(DMQ_SERIALIZE_BITSERY) - #include "port/serialize/bitsery/BitserySerializer.h" -#elif defined(DMQ_SERIALIZE_RAPIDJSON) - #include "port/serialize/rapidjson/RapidJsonSerializer.h" -#elif defined(DMQ_SERIALIZE_SERIALIZE) - #include "port/serialize/serialize/DmqSerializer.h" -#elif defined(DMQ_SERIALIZE_NONE) - // Create a custom application-specific serializer -#else - #warning "Serialize implementation not found." -#endif - -#if defined(DMQ_TRANSPORT_ZEROMQ) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/zeromq/ZeroMqTransport.h" -#elif defined(DMQ_TRANSPORT_NNG) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/nng/NngTransport.h" -#elif defined(DMQ_TRANSPORT_WIN32_PIPE) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/win32-pipe/Win32PipeTransport.h" -#elif defined(DMQ_TRANSPORT_WIN32_UDP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/win32-udp/Win32UdpTransport.h" - #include "port/transport/win32-udp/MulticastTransport.h" -#elif defined(DMQ_TRANSPORT_WIN32_TCP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/win32-tcp/Win32TcpTransport.h" -#elif defined(DMQ_TRANSPORT_LINUX_UDP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/linux-udp/LinuxUdpTransport.h" - #include "port/transport/linux-udp/MulticastTransport.h" -#elif defined(DMQ_TRANSPORT_LINUX_UDS) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/linux-uds/LinuxUdsTransport.h" -#elif defined(DMQ_TRANSPORT_LINUX_TCP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/linux-tcp/LinuxTcpTransport.h" -#elif defined(DMQ_TRANSPORT_MQTT) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/mqtt/MqttTransport.h" -#elif defined(DMQ_TRANSPORT_SERIAL_PORT) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/serial/SerialTransport.h" -#elif defined(DMQ_TRANSPORT_ARM_LWIP_UDP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/arm-lwip-udp/ArmLwipUdpTransport.h" -#elif defined(DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/arm-lwip-netconn-udp/ArmLwipNetconnUdpTransport.h" -#elif defined(DMQ_TRANSPORT_THREADX_UDP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/netx-udp/NetXUdpTransport.h" -#elif defined(DMQ_TRANSPORT_STM32_UART) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/stm32-uart/Stm32UartTransport.h" -#elif defined(DMQ_TRANSPORT_ZEPHYR_UDP) - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/zephyr-udp/ZephyrUdpTransport.h" -#elif defined(DMQ_TRANSPORT_NONE) - // No built-in transport. Include the interface and dispatcher so application code - // can implement a custom ITransport and use RemoteChannel with a mock or stub. - #include "extras/dispatcher/Dispatcher.h" - #include "port/transport/common/ITransport.h" -#else - #warning "Transport implementation not found." -#endif - -// Include RemoteChannel whenever Dispatcher.h has been included (all transport -// configurations including NONE, where a mock ITransport can be supplied). -// RemoteChannel aggregates dispatcher, serializer, and stream into one object, -// mirroring how Thread aggregates async delegate wiring behind a single IThread. -#if defined(DMQ_TRANSPORT_ZEROMQ) || defined(DMQ_TRANSPORT_NNG) || \ - defined(DMQ_TRANSPORT_WIN32_PIPE) || defined(DMQ_TRANSPORT_WIN32_UDP) || \ - defined(DMQ_TRANSPORT_WIN32_TCP) || defined(DMQ_TRANSPORT_LINUX_UDP) || \ - defined(DMQ_TRANSPORT_LINUX_TCP) || defined(DMQ_TRANSPORT_LINUX_UDS) || \ - defined(DMQ_TRANSPORT_MQTT) || \ - defined(DMQ_TRANSPORT_SERIAL_PORT) || defined(DMQ_TRANSPORT_ARM_LWIP_UDP) || \ - defined(DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP) || defined(DMQ_TRANSPORT_THREADX_UDP) || \ - defined(DMQ_TRANSPORT_STM32_UART) || defined(DMQ_TRANSPORT_ZEPHYR_UDP) || \ - defined(DMQ_TRANSPORT_NONE) - #include "extras/dispatcher/RemoteChannel.h" -#endif - -#include "extras/util/Fault.h" -#include "extras/util/ClockHelper.h" - -// Timer only needs dmq::Clock/dmq::CriticalSection (both of which the -// bare-metal port -- BareMetalClock.h/BareMetalCriticalSection.h -- provides -// specifically so Timer::ProcessTimers() can be driven from a hardware ISR -// with no RTOS at all, e.g. a SysTick_Handler; see BareMetalCriticalSection.h's -// own doc comment). It has no dependency on dmq::os::Thread, so it's -// available even under DMQ_THREAD_NONE. -#include "extras/util/Timer.h" - -// TimerDelegate/AsyncInvoke/TransportMonitor/ThreadMonitor/RetryMonitor/ -// ReliableTransport/RemoteDispatcher all take or operate on a dmq::IThread& -// (RetryMonitor/ReliableTransport indirectly, via TransportMonitor), which -// doesn't exist under DMQ_THREAD_NONE. -// RetryMonitor/ReliableTransport are listed explicitly here as first-class -// extras/util components usable directly with Participant/DataBus, independent -// of RemoteDispatcher -- the old NetworkEngine used to pull both in as a side -// effect of its own per-transport #include block, which any DelegateMQ.h -// consumer (not just RPC users) could end up silently depending on. That -// implicit path is gone now that RemoteDispatcher itself no longer knows about -// ReliableTransport (only RetryMonitor, for AttachRetryMonitor()'s signature), -// so both are pulled in explicitly instead. RemoteDispatcher itself no longer -// depends on which transport (if any) is selected -- it only ever sees -// dmq::transport::ITransport -- so unlike the old NetworkEngine it needs no -// DMQ_TRANSPORT_* guard here. -#if !defined(DMQ_THREAD_NONE) - #include "extras/util/TimerDelegate.h" - #include "extras/util/AsyncInvoke.h" - #include "extras/util/TransportMonitor.h" - #include "extras/util/ThreadMonitor.h" - #include "extras/util/RetryMonitor.h" - #include "extras/util/ReliableTransport.h" - #include "extras/rpc/RemoteDispatcher.h" -#endif - -#if defined(DMQ_DATABUS) - #include "extras/databus/DataBus.h" - #include "extras/databus/Participant.h" - #include "extras/databus/DeadlineSubscription.h" -#endif - - -#endif diff --git a/DelegateMQ/DepsDir.cmake b/DelegateMQ/DepsDir.cmake deleted file mode 100644 index 8ff2fef..0000000 --- a/DelegateMQ/DepsDir.cmake +++ /dev/null @@ -1,25 +0,0 @@ -# DepsDir.cmake -# Resolves DMQ_DEPS_DIR: the directory holding the third-party repos fetched by -# 01_fetch_repos.py (zeromq, nng, mqtt, msgpack-c, FreeRTOS, ftxui, ...). -# -# Order: -# 1. -DDMQ_DEPS_DIR= on the cmake command line -# 2. DMQ_DEPS_DIR environment variable -# 3. /external (the default, gitignored) -# -# Included by DelegateMQ.cmake. Build files that need a dependency before -# including DelegateMQ.cmake can include this file directly. -# -# No include_guard: CMake variables are directory-scoped, so a project that -# includes DelegateMQ.cmake from several subdirectories needs DMQ_DEPS_DIR set -# in each of them. - -if(NOT DMQ_DEPS_DIR AND DEFINED ENV{DMQ_DEPS_DIR}) - set(DMQ_DEPS_DIR "$ENV{DMQ_DEPS_DIR}") -endif() - -if(NOT DMQ_DEPS_DIR) - set(DMQ_DEPS_DIR "${CMAKE_CURRENT_LIST_DIR}/../../external") -endif() - -get_filename_component(DMQ_DEPS_DIR "${DMQ_DEPS_DIR}" ABSOLUTE) diff --git a/DelegateMQ/External.cmake b/DelegateMQ/External.cmake deleted file mode 100644 index 2c197dd..0000000 --- a/DelegateMQ/External.cmake +++ /dev/null @@ -1,459 +0,0 @@ -include(CMakeFindDependencyMacro) - -# Previously, this checked if "${_var}" (the variable name) existed as a file. -# Now it correctly checks "${_file}" (the actual path). -macro(set_and_check _var _file) - set(${_var} "${_file}") - if(NOT EXISTS "${_file}") - message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist!") - endif() -endmacro() - -# Outputs below are only set for the selected ports; clear what an earlier -# include in this scope (or a parent's) may have left. -foreach(_dmq_var FREERTOS_SOURCES FREERTOS_LIBRARIES THREADX_LIBRARIES LWIP_SOURCES NETX_SOURCES) - set(${_dmq_var} "") -endforeach() - -# --------------------------------------------------------------------------- -# ZeroMQ library package -# --------------------------------------------------------------------------- -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ZEROMQ") - set(ZMQ_ROOT "${DMQ_DEPS_DIR}/zeromq/install") - list(APPEND CMAKE_PREFIX_PATH "${ZMQ_ROOT}") - - find_package(ZeroMQ CONFIG REQUIRED) - - if (ZeroMQ_FOUND) - message(STATUS "ZeroMQ found: ${ZeroMQ_VERSION}") - if(TARGET libzmq-static AND NOT TARGET libzmq) - add_library(libzmq ALIAS libzmq-static) - endif() - dmq_compile_definitions(ZMQ_STATIC) - else() - message(FATAL_ERROR "ZeroMQ not found in ${ZMQ_ROOT}") - endif() -endif() - -# --------------------------------------------------------------------------- -# NNG library -# --------------------------------------------------------------------------- -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_NNG") - if(CMAKE_SYSTEM_NAME STREQUAL "Windows") - # Fixed: Point to the 'install' folder where headers actually live after build - set_and_check(NNG_INCLUDE_DIR "${DMQ_DEPS_DIR}/nng/install/include") - set_and_check(NNG_LIBRARY_DIR "${DMQ_DEPS_DIR}/nng/install/lib") - elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - # The copy 02_build_libs.py installs under DMQ_DEPS_DIR, as on Windows. - # Set -DDMQ_NNG_PREFIX= to use another install (e.g. /usr/local). - if(DMQ_NNG_PREFIX) - set(_dmq_nng_prefix "${DMQ_NNG_PREFIX}") - else() - set(_dmq_nng_prefix "${DMQ_DEPS_DIR}/nng/install") - endif() - set_and_check(NNG_INCLUDE_DIR "${_dmq_nng_prefix}/include") - if(EXISTS "${_dmq_nng_prefix}/lib64" AND NOT EXISTS "${_dmq_nng_prefix}/lib") - set_and_check(NNG_LIBRARY_DIR "${_dmq_nng_prefix}/lib64") # some distros' GNUInstallDirs - else() - set_and_check(NNG_LIBRARY_DIR "${_dmq_nng_prefix}/lib") - endif() - endif() -endif() - -# --------------------------------------------------------------------------- -# MQTT C library -# --------------------------------------------------------------------------- -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_MQTT") - # Define root relative to DelegateMQ source - set(MQTT_ROOT "${DMQ_DEPS_DIR}/mqtt") - - if(CMAKE_SYSTEM_NAME STREQUAL "Windows") - # 1. Headers - # Note: If 'install' step wasn't run, headers might be in "${MQTT_ROOT}/src" - set_and_check(MQTT_INCLUDE_DIR "${MQTT_ROOT}/install/include") - - # 2. Library (Lib) Directory (for linking) - # Point to build/src where the .lib files are generated - set(MQTT_LIBRARY_DIR "${MQTT_ROOT}/build/src") - - # 3. Binary (DLL) Directory (for runtime copy) - # Point to build/src where the .dll files are generated - set(MQTT_BINARY_DIR "${MQTT_ROOT}/build/src") - - # Fallback for manual definition if needed - set(MQTT_LIBRARY - "${MQTT_LIBRARY_DIR}/paho-mqtt3c.lib" - "ws2_32" "Rpcrt4" "Crypt32" - ) - elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - # The copy 02_build_libs.py installs under DMQ_DEPS_DIR, as on Windows. - # Set -DDMQ_MQTT_PREFIX= to use another install (e.g. /usr/local). - if(DMQ_MQTT_PREFIX) - set(_dmq_mqtt_prefix "${DMQ_MQTT_PREFIX}") - else() - set(_dmq_mqtt_prefix "${MQTT_ROOT}/install") - endif() - set_and_check(MQTT_INCLUDE_DIR "${_dmq_mqtt_prefix}/include") - if(EXISTS "${_dmq_mqtt_prefix}/lib64" AND NOT EXISTS "${_dmq_mqtt_prefix}/lib") - set(MQTT_LIBRARY_DIR "${_dmq_mqtt_prefix}/lib64") # some distros' GNUInstallDirs - else() - set(MQTT_LIBRARY_DIR "${_dmq_mqtt_prefix}/lib") - endif() - set_and_check(MQTT_LIBRARY "${MQTT_LIBRARY_DIR}/libpaho-mqtt3c.so") - set(MQTT_BINARY_DIR "${_dmq_mqtt_prefix}/bin") # used only for the Windows DLL copy - endif() -endif() - -# --------------------------------------------------------------------------- -# libserialport library -# --------------------------------------------------------------------------- -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_SERIAL_PORT") - set(SERIALPORT_ROOT "${DMQ_DEPS_DIR}/libserialport") - - if(CMAKE_SYSTEM_NAME STREQUAL "Windows") - # 1. Header: Found in the root of the source folder (libserialport.h) - set_and_check(SERIALPORT_INCLUDE_DIR "${SERIALPORT_ROOT}") - - # 2. Library: Found in the Visual Studio build output folder - # Note: Change 'Debug' to 'Release' if building in Release mode - set_and_check(SERIALPORT_LIBRARY_DIR "${SERIALPORT_ROOT}/x64/Debug") - - elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - # 1. Header: Found in the root of the source folder - set_and_check(SERIALPORT_INCLUDE_DIR "${SERIALPORT_ROOT}") - - # 2. Library: Found in the local build directory - # Standard Autotools builds (./configure && make) place .so files in the hidden .libs/ directory - if(EXISTS "${SERIALPORT_ROOT}/.libs") - set_and_check(SERIALPORT_LIBRARY_DIR "${SERIALPORT_ROOT}/.libs") - else() - # Fallback: Check root if built differently - set_and_check(SERIALPORT_LIBRARY_DIR "${SERIALPORT_ROOT}") - endif() - endif() -endif() - -# --------------------------------------------------------------------------- -# lwIP library (For ARM/Embedded) -# --------------------------------------------------------------------------- -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ARM_LWIP_UDP" OR DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP") - - # Adjust this path if your lwIP root is different - set(LWIP_ROOT "${DMQ_DEPS_DIR}/lwip") - - # lwIP requires 3 main include directories for the socket API - set_and_check(LWIP_INCLUDE_DIR_1 "${LWIP_ROOT}/src/include") - set_and_check(LWIP_INCLUDE_DIR_2 "${LWIP_ROOT}/src/include/ipv4") - - # Often required for lwipopts.h or arch/cc.h. - # NOTE: You may need to customize this depending on where your project keeps 'lwipopts.h' - set(LWIP_INCLUDE_DIR_3 "${LWIP_ROOT}/contrib/ports/unix/port/include") - - set(LWIP_INCLUDE_DIRS - "${LWIP_INCLUDE_DIR_1}" - "${LWIP_INCLUDE_DIR_2}" - "${LWIP_INCLUDE_DIR_3}" - ) - - # Collect core lwIP sources - file(GLOB_RECURSE LWIP_SOURCES - "${LWIP_ROOT}/src/core/*.c" - "${LWIP_ROOT}/src/api/*.c" - "${LWIP_ROOT}/src/netif/*.c" - ) -endif() - -# --------------------------------------------------------------------------- -# NetX / NetX Duo library (For ThreadX) -# --------------------------------------------------------------------------- -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_THREADX_UDP") - # Adjust this path to your NetX / NetX Duo root - set(NETX_ROOT "${DMQ_DEPS_DIR}/netxduo") - - # Verify root - set_and_check(NETX_INCLUDE_DIR "${NETX_ROOT}/common/inc") - - # Collect common sources - file(GLOB NETX_SOURCES - "${NETX_ROOT}/common/src/*.c" - "${NETX_ROOT}/common/inc/*.h" - ) - - # Note: Architecture-specific ports usually handled by your main ThreadX build system -endif() - -# --------------------------------------------------------------------------- -# MessagePack -# --------------------------------------------------------------------------- -if(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_MSGPACK") - dmq_compile_definitions(MSGPACK_NO_BOOST) - set_and_check(MSGPACK_INCLUDE_DIR "${DMQ_DEPS_DIR}/msgpack-c/include") -endif() - -# --------------------------------------------------------------------------- -# Cereal -# --------------------------------------------------------------------------- -if(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_CEREAL") - set_and_check(CEREAL_INCLUDE_DIR "${DMQ_DEPS_DIR}/cereal/include") -endif() - -# --------------------------------------------------------------------------- -# Bitsery -# --------------------------------------------------------------------------- -if(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_BITSERY") - set_and_check(BITSERY_INCLUDE_DIR "${DMQ_DEPS_DIR}/bitsery/include") -endif() - -# --------------------------------------------------------------------------- -# RapidJSON -# --------------------------------------------------------------------------- -if(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_RAPIDJSON") - set_and_check(RAPIDJSON_INCLUDE_DIR "${DMQ_DEPS_DIR}/rapidjson/include") - - # Globally silence C++17 std::iterator warnings on RapidJSON library - if(MSVC) - dmq_compile_definitions(_SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING) - endif() -endif() - -# --------------------------------------------------------------------------- -# FreeRTOS -# --------------------------------------------------------------------------- -if(DMQ_THREAD STREQUAL "DMQ_THREAD_FREERTOS") - set_and_check(FREERTOS_ROOT_DIR "${DMQ_DEPS_DIR}/FreeRTOS") - - file(GLOB FREERTOS_SOURCES - "${FREERTOS_ROOT_DIR}/*.c" - "${FREERTOS_ROOT_DIR}/include/*.h" - ) - - # A cross-compiled hardware target selects its own port (e.g. - # set(FREERTOS_PORT_DIR "GCC/ARM_CM4F")) before including DelegateMQ.cmake; - # otherwise the host simulator port is chosen. - if(DEFINED FREERTOS_PORT_DIR) - # Caller-selected port - elseif(WIN32) - set(FREERTOS_PORT_DIR "MSVC-MingW") - elseif(APPLE) - set(FREERTOS_PORT_DIR "ThirdParty/GCC/Posix") - elseif(UNIX) - set(FREERTOS_PORT_DIR "ThirdParty/GCC/Posix") - else() - message(FATAL_ERROR "DelegateMQ: Unsupported OS for FreeRTOS simulation. " - "For a hardware target, set FREERTOS_PORT_DIR (e.g. GCC/ARM_CM4F).") - endif() - - if(NOT DEFINED FREERTOS_HEAP) - set(FREERTOS_HEAP "heap_5") - endif() - - list(APPEND FREERTOS_SOURCES - "${FREERTOS_ROOT_DIR}/portable/${FREERTOS_PORT_DIR}/port.c" - "${FREERTOS_ROOT_DIR}/portable/MemMang/${FREERTOS_HEAP}.c" - ) - - if(UNIX AND NOT APPLE AND FREERTOS_PORT_DIR STREQUAL "ThirdParty/GCC/Posix") - file(GLOB POSIX_UTILS "${FREERTOS_ROOT_DIR}/portable/${FREERTOS_PORT_DIR}/utils/*.c") - list(APPEND FREERTOS_SOURCES ${POSIX_UTILS}) - set(FREERTOS_LIBRARIES pthread rt) - endif() -endif() - -# --------------------------------------------------------------------------- -# ThreadX -# --------------------------------------------------------------------------- -if(DMQ_THREAD STREQUAL "DMQ_THREAD_THREADX") - set_and_check(THREADX_ROOT_DIR "${DMQ_DEPS_DIR}/threadx") - - # ThreadX ships its own top-level CMakeLists.txt, which builds a real - # "azrtos::threadx" target from THREADX_ARCH / THREADX_TOOLCHAIN. We link - # against that instead of hand-globbing sources (unlike the FreeRTOS case - # above, which has no such CMake integration). - # - # Deliberately NOT using ThreadX's own cmake/linux.cmake toolchain file: - # it forces -fno-exceptions -fno-rtti build-wide, which would fight the - # desktop exception-based error path (DelegateOpt.h auto-switches to - # DMQ_ASSERTS only when the compiler itself lacks exception support). - if(UNIX AND NOT APPLE) - if(NOT DEFINED THREADX_ARCH) - set(THREADX_ARCH "linux") - endif() - if(NOT DEFINED THREADX_TOOLCHAIN) - set(THREADX_TOOLCHAIN "gnu") - endif() - - # Guard against add_subdirectory() being reached more than once in the - # same top-level CMake project -- e.g. two executables (Cellutron's - # controller and safety nodes) each including DelegateMQ.cmake with - # DMQ_THREAD_THREADX. The "threadx" target, once created, is visible - # project-wide, so every caller after the first just reuses it; without - # this guard the second add_subdirectory() call fails outright (CMake - # refuses to bind the same source directory to a second binary - # directory, and a plain unique-binary-dir fix would still collide on - # the "threadx" target name itself). - if(NOT TARGET threadx) - add_subdirectory("${THREADX_ROOT_DIR}" "${CMAKE_BINARY_DIR}/threadx_build") - endif() - - # ThreadX's own ports/linux/gnu/CMakeLists.txt unconditionally adds - # -DTX_LINUX_DEBUG_ENABLE as a PUBLIC compile definition on the - # "threadx" target. That macro wraps every TX_DISABLE/TX_RESTORE - # kernel-wide (see tx_port.h) in a call to _tx_linux_debug_entry_insert(), - # which serializes through one global mutex (_tx_linux_mutex) -- a real - # risk under genuine multi-thread contention. Stripped here rather - # than patching the vendored ThreadX source, so 01_fetch_repos.py can - # still pull a clean, unmodified ThreadX tree. - # - # Not a fix for the threadx-linux two-worker-thread deadlock (see - # example/sample-projects/threadx-linux/DelegateThreadsTests.cpp) -- - # that hang reproduces identically with this macro stripped, still - # blocked on _tx_linux_mutex via plain _tx_thread_interrupt_control(). - # ThreadX's CMakeLists.txt passes both defines as one combined string - # ("-D_GNU_SOURCE -DTX_LINUX_DEBUG_ENABLE"), not as separate list - # items, so a targeted list(REMOVE_ITEM) on COMPILE_DEFINITIONS can't - # match it. -U processes in command-line order after -D, so append it - # as a compile option instead of trying to edit the define out. - if(TARGET threadx) - target_compile_options(threadx PUBLIC "-UTX_LINUX_DEBUG_ENABLE") - endif() - - # The Linux/GNU port implements ThreadX scheduling on top of POSIX - # threads (pthread_create per tx_thread_create, signals for suspend). - find_package(Threads REQUIRED) - set(THREADX_LIBRARIES azrtos::threadx Threads::Threads) - else() - message(WARNING "DelegateMQ: No ThreadX simulation port configured for this host platform.") - endif() -endif() - -# --------------------------------------------------------------------------- -# Zephyr -# --------------------------------------------------------------------------- -if(DMQ_THREAD STREQUAL "DMQ_THREAD_ZEPHYR") - # Zephyr is a build system, not just a library. - # We typically do NOT manually glob source files here. - # The application's main CMakeLists.txt must call `find_package(Zephyr)` - # (before including DelegateMQ.cmake), which sets up the include paths - # and kernel linking automatically -- unlike ThreadX/FreeRTOS, Zephyr - # isn't vendored as a plain sibling directory; its location is a west - # workspace found via the ZEPHYR_BASE environment variable that - # find_package(Zephyr) itself sets. Sanity-check against that instead - # of assuming a "${DMQ_DEPS_DIR}/zephyr" clone that doesn't apply here. - if(NOT DEFINED ENV{ZEPHYR_BASE}) - message(WARNING "DelegateMQ: DMQ_THREAD_ZEPHYR is set, but ZEPHYR_BASE " - "is not defined -- ensure find_package(Zephyr) ran " - "before including DelegateMQ.cmake.") - endif() - - # Do NOT glob sources. Zephyr builds itself. -endif() - -# --------------------------------------------------------------------------- -# CMSIS-RTOS2 -# --------------------------------------------------------------------------- -if(DMQ_THREAD STREQUAL "DMQ_THREAD_CMSIS_RTOS2") - # CMSIS is usually provided by the IDE (Keil/IAR) or a silicon vendor pack (STM32Cube). - # We do NOT glob sources here by default. - # Users must ensure the 'cmsis_os2.h' path is in their include path. -endif() - -# --------------------------------------------------------------------------- -# NuttX -# --------------------------------------------------------------------------- -if(DMQ_THREAD STREQUAL "DMQ_THREAD_NUTTX") - # Like Zephyr, NuttX is a build system, not just a library -- an - # application is normally built as a NuttX "app" from inside a NuttX - # source tree (nuttx + apps repos), using NuttX's own Make-based - # (or, on recent versions, CMake-based) build, which already supplies - # the cross-toolchain and POSIX-compatible include paths (pthread.h, - # mqueue.h, semaphore.h, nuttx/irq.h, etc.) that this port's headers - # need. DelegateMQ.cmake does not vendor or fetch NuttX itself; the - # including project's build must already be running under a NuttX - # toolchain (or the `sim` simulation target) before this file is hit. - # - # Do NOT glob NuttX kernel sources here -- only DelegateMQ's own - # port/os/nuttx/*.cpp adapter files, already collected via - # Port.cmake's THREAD_SOURCES glob. -endif() - -# --------------------------------------------------------------------------- -# Qt Framework -# --------------------------------------------------------------------------- -if(DMQ_THREAD STREQUAL "DMQ_THREAD_QT") - # DMQ_THREAD_QT and the port/os/qt sources come from Port.cmake. - - # Find the Qt packages (Core is usually sufficient for QThread) - find_package(Qt6 COMPONENTS Core REQUIRED) - # Or Qt5: find_package(Qt5 COMPONENTS Core REQUIRED) - - # Important: Enable CMAKE_AUTOMOC for the Qt Meta-Object system - # (needed for signals/slots in Thread.h) - set(CMAKE_AUTOMOC ON) - - # Link Qt6::Core to your target (dmq_add_library() targets link it already): - # target_link_libraries(YourApp PRIVATE Qt6::Core) -endif() - -# --------------------------------------------------------------------------- -# spdlog -# --------------------------------------------------------------------------- -if (DMQ_LOG STREQUAL "ON") - set_and_check(SPDLOG_INCLUDE_DIR "${DMQ_DEPS_DIR}/spdlog/include") -endif() - -# --------------------------------------------------------------------------- -# Usage requirements for dmq_add_library(): third-party headers the selected -# ports include, and libraries resolvable here. Transports whose library is -# located by the application (NNG, MQTT, libserialport) are linked by the -# application itself; their include directories are still carried. -# --------------------------------------------------------------------------- -# Each entry is gated on its own option, not on whether the variable is set: -# an earlier include in this scope may have left another port's paths behind. -set(DMQ_EXTERNAL_INCLUDE_DIRS "") -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ZEROMQ") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${ZeroMQ_INCLUDE_DIR}) -elseif(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_NNG") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${NNG_INCLUDE_DIR}) -elseif(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_MQTT") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${MQTT_INCLUDE_DIR}) -elseif(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_SERIAL_PORT") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${SERIALPORT_INCLUDE_DIR}) -elseif(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ARM_LWIP_UDP" OR DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${LWIP_INCLUDE_DIRS}) -elseif(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_THREADX_UDP") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${NETX_INCLUDE_DIR}) -endif() -if(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_MSGPACK") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${MSGPACK_INCLUDE_DIR}) -elseif(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_CEREAL") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${CEREAL_INCLUDE_DIR}) -elseif(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_BITSERY") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${BITSERY_INCLUDE_DIR}) -elseif(DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_RAPIDJSON") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${RAPIDJSON_INCLUDE_DIR}) -endif() -if(DMQ_LOG STREQUAL "ON") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS ${SPDLOG_INCLUDE_DIR}) -endif() -# FreeRTOS kernel headers only. The kernel sources (FREERTOS_SOURCES) build -# against the application's FreeRTOSConfig.h and stay in the application. -if(DMQ_THREAD STREQUAL "DMQ_THREAD_FREERTOS") - list(APPEND DMQ_EXTERNAL_INCLUDE_DIRS - "${FREERTOS_ROOT_DIR}/include" - "${FREERTOS_ROOT_DIR}/portable/${FREERTOS_PORT_DIR}") -endif() - -set(DMQ_LINK_LIBRARIES "") -if(DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ZEROMQ" AND TARGET libzmq) - list(APPEND DMQ_LINK_LIBRARIES libzmq) -endif() -if(DMQ_THREAD STREQUAL "DMQ_THREAD_FREERTOS") - list(APPEND DMQ_LINK_LIBRARIES ${FREERTOS_LIBRARIES}) -elseif(DMQ_THREAD STREQUAL "DMQ_THREAD_THREADX") - list(APPEND DMQ_LINK_LIBRARIES ${THREADX_LIBRARIES}) -elseif(DMQ_THREAD STREQUAL "DMQ_THREAD_QT" AND TARGET Qt6::Core) - list(APPEND DMQ_LINK_LIBRARIES Qt6::Core) -elseif(UNIX AND (DMQ_THREAD STREQUAL "DMQ_THREAD_STDLIB" OR DMQ_THREAD STREQUAL "DMQ_THREAD_POSIX")) - find_package(Threads REQUIRED) - list(APPEND DMQ_LINK_LIBRARIES Threads::Threads) -endif() diff --git a/DelegateMQ/Macros.cmake b/DelegateMQ/Macros.cmake deleted file mode 100644 index a930274..0000000 --- a/DelegateMQ/Macros.cmake +++ /dev/null @@ -1,52 +0,0 @@ -# Function to copy .dll files from vcpkg bin directory to the build output directory -function(copy_files _src_files _dest_dir) - # Copy each DLL file to the build output directory - foreach(FILE ${_src_files}) - add_custom_command(TARGET ${DELEGATE_APP} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - ${FILE} # Copy files - ${_dest_dir} # Destination directory - COMMENT "Copying ${FILE} to build output" - ) - endforeach() -endfunction() - -# Record DelegateMQ compile definitions in DMQ_COMPILE_DEFINITIONS (used by -# dmq_add_library) and, unless DMQ_NO_GLOBAL_DEFINITIONS is set, also apply -# them directory-wide the way add_compile_definitions() always has. -macro(dmq_compile_definitions) - list(APPEND DMQ_COMPILE_DEFINITIONS ${ARGN}) - if(NOT DMQ_NO_GLOBAL_DEFINITIONS) - add_compile_definitions(${ARGN}) - endif() -endmacro() - -# dmq_add_library() -# -# Creates a static library target from the port/extras sources selected by the -# current DMQ_* options. Compile definitions, include directories (DelegateMQ, -# DMQ_USER_CONFIG_DIR if set, and enabled third-party headers as SYSTEM) and -# link dependencies are PUBLIC, so a consumer only needs -# target_link_libraries(app PRIVATE ). -# -# Call in the same directory, after including DelegateMQ.cmake. Each call -# captures that include's options, so a build tree with several configurations -# (e.g. a FreeRTOS controller and a stdlib GUI) creates one target per config. -# -# RTOS ports (FreeRTOS, ThreadX, Zephyr, NuttX, CMSIS-RTOS2) compile against the -# application's own RTOS config headers; add those to the target, e.g. -# target_include_directories( PUBLIC path/to/FreeRTOSConfig_dir) -function(dmq_add_library _name) - add_library(${_name} STATIC ${DMQ_PORT_SOURCES} ${DMQ_LIB_SOURCES}) - target_compile_features(${_name} PUBLIC cxx_std_17) - target_compile_definitions(${_name} PUBLIC ${DMQ_COMPILE_DEFINITIONS}) - target_compile_options(${_name} PUBLIC ${DMQ_COMPILE_OPTIONS}) - target_include_directories(${_name} PUBLIC ${DMQ_INCLUDE_DIR} ${DMQ_USER_CONFIG_DIR}) - # SYSTEM: keep third-party header warnings out of DMQ_STRICT and the app's own warning level - target_include_directories(${_name} SYSTEM PUBLIC ${DMQ_EXTERNAL_INCLUDE_DIRS}) - target_link_libraries(${_name} PUBLIC ${DMQ_LINK_LIBRARIES}) - - source_group("DelegateMQ/Delegate Files" FILES ${DMQ_LIB_SOURCES}) - source_group("DelegateMQ/Port Files" FILES ${DMQ_PORT_ONLY_SOURCES}) - source_group("DelegateMQ/Extras Files" FILES ${DMQ_EXTRAS_SOURCES}) -endfunction() diff --git a/DelegateMQ/Port.cmake b/DelegateMQ/Port.cmake deleted file mode 100644 index 12a0369..0000000 --- a/DelegateMQ/Port.cmake +++ /dev/null @@ -1,261 +0,0 @@ -# Port build options - -# Start each include from empty lists: only some branches below set these, so a -# value left by an earlier include in this scope (or a parent's) would leak -# into this configuration. -foreach(_dmq_list THREAD SERIALIZE TRANSPORT OS DISPATCHER ALLOCATOR UTIL RPC FAULT DATABUS) - set(${_dmq_list}_SOURCES "") -endforeach() - -if (DMQ_THREAD STREQUAL "DMQ_THREAD_STDLIB") - dmq_compile_definitions(DMQ_THREAD_STDLIB) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/stdlib/*.c*" - "${DMQ_ROOT_DIR}/port/os/stdlib/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_WIN32") - dmq_compile_definitions(DMQ_THREAD_WIN32) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/win32/*.c*" - "${DMQ_ROOT_DIR}/port/os/win32/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_POSIX") - dmq_compile_definitions(DMQ_THREAD_POSIX) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/posix/*.c*" - "${DMQ_ROOT_DIR}/port/os/posix/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_FREERTOS") - dmq_compile_definitions(DMQ_THREAD_FREERTOS) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/freertos/*.c*" - "${DMQ_ROOT_DIR}/port/os/freertos/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_THREADX") - dmq_compile_definitions(DMQ_THREAD_THREADX) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/threadx/*.c*" - "${DMQ_ROOT_DIR}/port/os/threadx/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_ZEPHYR") - dmq_compile_definitions(DMQ_THREAD_ZEPHYR) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/zephyr/*.c*" - "${DMQ_ROOT_DIR}/port/os/zephyr/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_CMSIS_RTOS2") - dmq_compile_definitions(DMQ_THREAD_CMSIS_RTOS2) - file(GLOB THREAD_SOURCES - "${DMQ_ROOT_DIR}/port/os/cmsis-rtos2/*.c*" - "${DMQ_ROOT_DIR}/port/os/cmsis-rtos2/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_NUTTX") - dmq_compile_definitions(DMQ_THREAD_NUTTX) - file(GLOB THREAD_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/os/nuttx/*.c*" - "${DMQ_ROOT_DIR}/port/os/nuttx/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_QT") - dmq_compile_definitions(DMQ_THREAD_QT) - file(GLOB THREAD_SOURCES - "${DMQ_ROOT_DIR}/port/os/qt/*.c*" - "${DMQ_ROOT_DIR}/port/os/qt/*.h" - ) -elseif (DMQ_THREAD STREQUAL "DMQ_THREAD_NONE") - dmq_compile_definitions(DMQ_THREAD_NONE) -else() - message(FATAL_ERROR "Must set DMQ_THREAD option.") -endif() - -if (DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_NONE") - dmq_compile_definitions(DMQ_SERIALIZE_NONE) -elseif (DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_SERIALIZE") - dmq_compile_definitions(DMQ_SERIALIZE_SERIALIZE) - file(GLOB SERIALIZE_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/serialize/serialize/*.h") -elseif (DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_RAPIDJSON") - dmq_compile_definitions(DMQ_SERIALIZE_RAPIDJSON) - file(GLOB SERIALIZE_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/serialize/rapidjson/*.h") -elseif (DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_MSGPACK") - dmq_compile_definitions(DMQ_SERIALIZE_MSGPACK) - file(GLOB SERIALIZE_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/serialize/msgpack/*.h") -elseif (DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_CEREAL") - dmq_compile_definitions(DMQ_SERIALIZE_CEREAL) - file(GLOB SERIALIZE_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/serialize/cereal/*.h") -elseif (DMQ_SERIALIZE STREQUAL "DMQ_SERIALIZE_BITSERY") - dmq_compile_definitions(DMQ_SERIALIZE_BITSERY) - file(GLOB SERIALIZE_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/serialize/bitsery/*.h") -else() - message(FATAL_ERROR "Must set DMQ_SERIALIZE option.") -endif() - -if (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_NONE") - dmq_compile_definitions(DMQ_TRANSPORT_NONE) -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ZEROMQ") - dmq_compile_definitions(DMQ_TRANSPORT_ZEROMQ) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/zeromq/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_NNG") - dmq_compile_definitions(DMQ_TRANSPORT_NNG) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/nng/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_MQTT") - dmq_compile_definitions(DMQ_TRANSPORT_MQTT) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/mqtt/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_WIN32_PIPE") - dmq_compile_definitions(DMQ_TRANSPORT_WIN32_PIPE) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/win32-pipe/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_WIN32_UDP") - dmq_compile_definitions(DMQ_TRANSPORT_WIN32_UDP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/win32-udp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_WIN32_TCP") - dmq_compile_definitions(DMQ_TRANSPORT_WIN32_TCP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/win32-tcp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_LINUX_UDP") - dmq_compile_definitions(DMQ_TRANSPORT_LINUX_UDP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/linux-udp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_LINUX_UDS") - dmq_compile_definitions(DMQ_TRANSPORT_LINUX_UDS) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/linux-uds/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_LINUX_TCP") - dmq_compile_definitions(DMQ_TRANSPORT_LINUX_TCP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/linux-tcp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_SERIAL_PORT") - dmq_compile_definitions(DMQ_TRANSPORT_SERIAL_PORT) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/serial/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ARM_LWIP_UDP") - dmq_compile_definitions(DMQ_TRANSPORT_ARM_LWIP_UDP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/arm-lwip-udp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP") - dmq_compile_definitions(DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/arm-lwip-netconn-udp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_THREADX_UDP") - dmq_compile_definitions(DMQ_TRANSPORT_THREADX_UDP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/netx-udp/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_STM32_UART") - dmq_compile_definitions(DMQ_TRANSPORT_STM32_UART) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/stm32-uart/*.h") -elseif (DMQ_TRANSPORT STREQUAL "DMQ_TRANSPORT_ZEPHYR_UDP") - dmq_compile_definitions(DMQ_TRANSPORT_ZEPHYR_UDP) - file(GLOB TRANSPORT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/transport/zephyr-udp/*.h") -else() - message(FATAL_ERROR "Must set DMQ_TRANSPORT option.") -endif() - -file(GLOB DISPATCHER_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/extras/dispatcher/*.h" -) - -if (DMQ_ALLOCATOR STREQUAL "ON") - dmq_compile_definitions(DMQ_ALLOCATOR) - file(GLOB ALLOCATOR_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/extras/allocator/*.c*" - "${DMQ_ROOT_DIR}/extras/allocator/*.h" - ) -endif() - -if (DMQ_UTIL STREQUAL "ON") - if (DMQ_THREAD STREQUAL "DMQ_THREAD_NONE") - # Bare metal: only include utilities with no dmq::os::Thread/IThread - # dependency. Fault.cpp lives in port/fault/ and is always included - # separately. Timer.cpp is included -- it only needs dmq::Clock/ - # dmq::CriticalSection (BareMetalClock.h/BareMetalCriticalSection.h - # exist specifically so Timer::ProcessTimers() can be driven from a - # hardware ISR, e.g. SysTick_Handler, with no RTOS at all -- see - # BareMetalCriticalSection.h's own doc comment). AsyncInvoke.h/ - # TimerDelegate.h/RemoteDispatcher.cpp/ThreadMonitor.cpp all genuinely - # need a real dmq::IThread and stay excluded. - file(GLOB UTIL_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/extras/util/Fault.h" - "${DMQ_ROOT_DIR}/extras/util/Timer.h" - "${DMQ_ROOT_DIR}/extras/util/Timer.cpp" - ) - else() - # OS/RTOS present: Include everything - file(GLOB UTIL_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/extras/util/*.c*" - "${DMQ_ROOT_DIR}/extras/util/*.h" - ) - # RPC sources (RemoteDispatcher/RemoteEndpoint) need a real dmq::IThread, - # same reasoning as the bare-metal exclusion above -- only globbed here. - file(GLOB RPC_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/extras/rpc/*.c*" - "${DMQ_ROOT_DIR}/extras/rpc/*.h" - ) - endif() -endif() - -# Fault handler port — always included; override by filtering Fault.cpp from DMQ_PORT_SOURCES -file(GLOB FAULT_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/port/fault/Fault.cpp" -) - -if (DMQ_ASSERTS STREQUAL "ON") - dmq_compile_definitions(DMQ_ASSERTS) -endif() - -if (DMQ_LOG STREQUAL "ON") - dmq_compile_definitions(DMQ_LOG) -endif() - -# Port sources: OS/transport/serialization adapters (port/ directory) -set(DMQ_PORT_ONLY_SOURCES "") -list(APPEND DMQ_PORT_ONLY_SOURCES ${TRANSPORT_SOURCES}) -list(APPEND DMQ_PORT_ONLY_SOURCES ${SERIALIZE_SOURCES}) -list(APPEND DMQ_PORT_ONLY_SOURCES ${THREAD_SOURCES}) -list(APPEND DMQ_PORT_ONLY_SOURCES ${OS_SOURCES}) -list(APPEND DMQ_PORT_ONLY_SOURCES ${FAULT_SOURCES}) - -# Extras sources: optional higher-level infrastructure (extras/ directory) -set(DMQ_EXTRAS_SOURCES "") -list(APPEND DMQ_EXTRAS_SOURCES ${DISPATCHER_SOURCES}) -list(APPEND DMQ_EXTRAS_SOURCES ${ALLOCATOR_SOURCES}) -list(APPEND DMQ_EXTRAS_SOURCES ${UTIL_SOURCES}) -list(APPEND DMQ_EXTRAS_SOURCES ${RPC_SOURCES}) - -if (DMQ_DATABUS STREQUAL "ON") - dmq_compile_definitions(DMQ_DATABUS) - file(GLOB DATABUS_SOURCES CONFIGURE_DEPENDS "${DMQ_ROOT_DIR}/extras/databus/*.h") - list(APPEND DMQ_EXTRAS_SOURCES ${DATABUS_SOURCES}) -endif() - -# DelegateSelect.h turns DataBus and its tools on for desktop builds unless -# DMQ_DATABUS_OFF / DMQ_DATABUS_TOOLS_OFF is defined, so an explicit -# set(... "OFF") must be passed on for it to take effect there. A default -# Defaults.cmake filled in is left to DelegateSelect.h, as before. -list(FIND _DMQ_AUTO_DEFAULTS DMQ_DATABUS _dmq_databus_auto) -if (NOT DMQ_DATABUS AND _dmq_databus_auto EQUAL -1) - dmq_compile_definitions(DMQ_DATABUS_OFF) -endif() -list(FIND _DMQ_AUTO_DEFAULTS DMQ_DATABUS_TOOLS _dmq_tools_auto) -if (NOT DMQ_DATABUS_TOOLS AND _dmq_tools_auto EQUAL -1) - dmq_compile_definitions(DMQ_DATABUS_TOOLS_OFF) -endif() - -# Combined list for compilation -set(DMQ_PORT_SOURCES "") -list(APPEND DMQ_PORT_SOURCES ${DMQ_PORT_ONLY_SOURCES}) -list(APPEND DMQ_PORT_SOURCES ${DMQ_EXTRAS_SOURCES}) - -# Collect all DelegateMQ files -file(GLOB DMQ_LIB_SOURCES CONFIGURE_DEPENDS - "${DMQ_ROOT_DIR}/*.h" - "${DMQ_ROOT_DIR}/delegate/*.h" -) \ No newline at end of file diff --git a/DelegateMQ/delegate/Delegate.h b/DelegateMQ/delegate/Delegate.h deleted file mode 100644 index e7ee3f1..0000000 --- a/DelegateMQ/delegate/Delegate.h +++ /dev/null @@ -1,997 +0,0 @@ -#ifndef _DELEGATE_H -#define _DELEGATE_H - -// Delegate.h -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, Aug 2020. - -/// @file -/// @brief Delegate series of classes are used to invoke a function synchronously. -/// @details Delegates support binding to free functions, class instance functions, class -/// static function, and std::function targets. Lambda functions can be bound to a delegate -/// when assigned to a `std::function`. The classes are not thread-safe. -/// -/// Limitations: -/// -/// * Cannot insert `DelegateMember` into an ordered container. e.g. `std::list` ok, -/// `std::set` not ok. -/// -/// * `std::function` compares the function signature type, not the underlying object instance. -/// See `DelegateFunction<>` class for more info. - -#include -#include -#include "DelegateOpt.h" - -/// The delegate library namespace -DMQ_OPTIMIZE_ON - -namespace dmq { - -namespace trait -{ - // Helper trait to check if a type is a reference to a std::shared_ptr - template - struct is_shared_ptr_reference : std::false_type {}; - - template - struct is_shared_ptr_reference&> : std::true_type {}; - - template - struct is_shared_ptr_reference&> : std::true_type {}; - - template - struct is_shared_ptr_reference*> : std::true_type {}; - - template - struct is_shared_ptr_reference*> : std::true_type {}; - - // Helper trait to check if a type is a non-const reference to a std::shared_ptr - template - struct is_non_const_shared_ptr_reference : std::false_type {}; - - template - struct is_non_const_shared_ptr_reference&> : std::true_type {}; - - template - struct is_non_const_shared_ptr_reference*> : std::true_type {}; - - - - // Helper trait to check if a type is a double pointer (e.g., int**) - template - struct is_double_pointer { - // Remove 'const', 'volatile', and references first - using RawT = std::remove_cv_t>; - - static constexpr bool value = - std::is_pointer_v && - std::is_pointer_v>; - }; - - // Helper trait to detect std::function specializations. - template - struct is_std_function : std::false_type {}; - - template - struct is_std_function> : std::true_type {}; - - // Helper trait to check if a type is a callable (lambda, functor) - // but NOT a function pointer or std::function (which have their own MakeDelegate overloads). - template - struct is_callable : std::false_type {}; - - template - struct is_callable::operator())>> : - std::integral_constant> && - !is_std_function>::value> {}; - - // Helper to deduce function signature from a member function pointer (like operator()) - template - struct function_traits; - - template - struct function_traits { - using function_type = RetType(Args...); - }; - - template - struct function_traits { - using function_type = RetType(Args...); - }; -} - -/// @brief Non-template base class for all delegates. -class DelegateBase { -public: - DelegateBase() = default; - virtual ~DelegateBase() noexcept = default; - - /// @brief Compares two delegate objects for equality. - /// @param rhs The delegate object to compare with the current object. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const DelegateBase& rhs) const noexcept { return Equal(rhs); } - - /// @brief Compares two delegate objects for inequality. - /// @param rhs The delegate object to compare with the current object. - /// @return `true` if the objects are not equal, `false` otherwise. - bool operator!=(const DelegateBase& rhs) const { return !Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept = 0; - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept = 0; - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& other) const = 0; - - /// @brief Clone a delegate instance. - /// @details Use Clone() to provide a deep copy using a base pointer. Covariant - /// overloading is used so that a Clone() method return type is a more - /// specific type in the derived class implementations. - /// @return A dynamic copy of this instance created with `operator new()`. - /// @post The caller is responsible for deleting the clone instance. - virtual DelegateBase* Clone() const = 0; - - // Optional fixed block allocator for delegates created on the heap - // using operator new(). See DMQ_ALLOCATOR in DelegateOpt.h and - // ENABLE_ALLOCATOR in CMakeLists.txt. - XALLOCATOR -}; - -template -class Delegate; // Not defined - -/// @brief Template base class for all delegates. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class Delegate : public DelegateBase { -public: - /// @brief Invoke the bound callable function stored within the - /// delegate instance. - /// @param[in] args The bound function argument(s), if any. - /// @return The bound function return value, if any. - virtual RetType operator()(Args... args) = 0; - - /// @brief Clone an instance of a Delegate instance. - /// @return A new Delegate instance created on the heap. - /// @post The caller is responsible for deleting the instance. - virtual Delegate* Clone() const override = 0; -}; - -template -class DelegateFree; // Not defined - -/// @brief `DelegateFree<>` class synchronously invokes a free target function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFree : public Delegate { -public: - typedef RetType(*FreeFunc)(Args...); - using ClassType = DelegateFree; - - /// @brief Constructor to create a class instance. - /// @param[in] func The target free function to store. - DelegateFree(FreeFunc func) { Bind(func); } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFree(const ClassType& rhs) { Assign(rhs); } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFree(ClassType&& rhs) noexcept : m_func(rhs.m_func) { rhs.Clear(); } - - /// @brief Default constructor creates an empty delegate. - DelegateFree() = default; - - /// @brief Destructor ensures empty when destroyed. - ~DelegateFree() override { Clear(); } - - /// @brief Bind a free function to the delegate. - /// @details This method associates a free function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The free function to bind to the delegate. This function must - /// match the signature of the delegate. - void Bind(FreeFunc func) { m_func = func; } - - /// Compares two ClassType objects using the '<' operator. - /// @param rhs The object to compare with. - /// @return `true` if the current object's value is less than the other object's value, - /// `false` otherwise. - bool operator<(const ClassType& rhs) const { - return m_func < rhs.m_func; - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_func = rhs.m_func; - } - - /// @brief Invoke the bound delegate function synchronously. Always safe to call. - /// @param[in] args - the function arguments, if any. - /// @return The bound function return value, if any. If empty delegate - /// default return type returned. - virtual RetType operator()(Args... args) override { - if (Empty()) - return RetType(); - return std::invoke(m_func, std::forward(args)...); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - m_func = rhs.m_func; - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept { - return Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_func == derivedRhs->m_func; - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Check if the delegate is bound to a target function. - /// @return `true` if the delegate has a target function, `false` otherwise. - bool Empty() const noexcept { return !m_func; } - - /// @brief Clear the target function. - /// @post The delegate is empty. - void Clear() noexcept { m_func = nullptr; } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the object is not empty, `false` if the object is empty. - explicit operator bool() const noexcept { return !Empty(); } - -private: - /// @brief Pointer to a free function, representing the bound target function. - FreeFunc m_func = nullptr; -}; - -template -class DelegateMember; // Not defined - -/// @brief `DelegateMember<>` class synchronously invokes a class member target -/// function using a class object pointer or shared pointer. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMember : public Delegate { -public: - typedef TClass* ObjectPtr; - typedef std::shared_ptr SharedPtr; - typedef RetType(TClass::* MemberFunc)(Args...); - typedef RetType(TClass::* ConstMemberFunc)(Args...) const; - using ClassType = DelegateMember; - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - DelegateMember(SharedPtr object, MemberFunc func) { Bind(object, func); } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - DelegateMember(SharedPtr object, ConstMemberFunc func) { Bind(object, func); } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - DelegateMember(ObjectPtr object, MemberFunc func) { Bind(object, func); } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - DelegateMember(ObjectPtr object, ConstMemberFunc func) { Bind(object, func); } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateMember(const ClassType& rhs) { Assign(rhs); } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateMember(ClassType&& rhs) noexcept : m_object(std::move(rhs.m_object)), m_func(rhs.m_func) { rhs.Clear(); } - - /// @brief Default constructor creates an empty delegate. - DelegateMember() = default; - - /// @brief Destructor ensures empty when destroyed. - ~DelegateMember() override { Clear(); } - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - void Bind(SharedPtr object, MemberFunc func) { - static_assert(!std::is_const::value, "Cannot bind non-const function to const object."); - m_object = object; - m_func = func; - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. The member function to - /// bind to the delegate. This function must match the signature of the delegate. - void Bind(SharedPtr object, ConstMemberFunc func) { - m_object = object; - // Note: Casting ConstMemberFunc to MemberFunc is formally UB when invoked - // through the non-const pointer, but works safely on all mainstream ABIs. - m_func = reinterpret_cast(func); - } - - /// @brief Bind a member function to a raw pointer. - /// @details Wraps the raw object pointer in a `std::shared_ptr` with a no-op - /// deleter, ensuring the delegate references the object without taking ownership - /// or attempting to delete it. The caller must ensure the object outlives the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance (raw pointer). - /// @param[in] func The const member function to bind. - void Bind(ObjectPtr object, MemberFunc func) { - static_assert(!std::is_const::value, "Cannot bind non-const function to const object."); - auto deleter = [](TClass*) {}; // No-op deleter - m_object = std::shared_ptr(object, deleter, ::dmq::stl_allocator>()); // Not deleted when out of scope - m_func = func; - } - - /// @brief Bind a const member function to a raw pointer. - /// @details Wraps the raw object pointer in a `std::shared_ptr` with a no-op - /// deleter, ensuring the delegate references the object without taking ownership - /// or attempting to delete it. The caller must ensure the object outlives the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance (raw pointer). - /// @param[in] func The const member function to bind. - void Bind(ObjectPtr object, ConstMemberFunc func) { - auto deleter = [](TClass*) {}; // No-op deleter - m_object = std::shared_ptr(object, deleter, ::dmq::stl_allocator>()); // Not deleted when out of scope - // Note: Casting ConstMemberFunc to MemberFunc is formally UB when invoked - // through the non-const pointer, but works safely on all mainstream ABIs. - m_func = reinterpret_cast(func); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_object = rhs.m_object; - m_func = rhs.m_func; - } - - /// @brief Invoke the bound delegate function synchronously. Always safe to call. - /// @param[in] args - the function arguments, if any. - /// @return The bound function return value, if any. If empty delegate - /// default return type returned. - virtual RetType operator()(Args... args) override { - if (Empty()) - return RetType(); - - if constexpr (std::is_const::value) - return std::invoke(reinterpret_cast(m_func), m_object, std::forward(args)...); - else - return std::invoke(m_func, m_object, std::forward(args)...); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - m_object = std::move(rhs.m_object); - m_func = rhs.m_func; - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept { - return Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_func == derivedRhs->m_func && - m_object == derivedRhs->m_object; - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Check if the delegate is bound to a target function. - /// @return `true` if the delegate has a target function, `false` otherwise. - bool Empty() const noexcept { return !(m_object && m_func); } - - /// @brief Clear the target function. - /// @post The delegate is empty. - void Clear() noexcept { m_object = nullptr; m_func = nullptr; } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the object is not empty, `false` if the object is empty. - explicit operator bool() const noexcept { return !Empty(); } - -private: - /// Compares two ClassType objects using the '<' operator. - /// @param rhs The object to compare with. - /// @return `true` if the current object's value is less than the other object's value, - /// `false` otherwise. - /// @note Do not call! Not allowed since comparing member function - /// pointers for operator< not allowed in C++. - bool operator<(const ClassType& rhs) const = delete; - - /// Pointer to a class object, representing the bound target instance. - SharedPtr m_object = nullptr; - - /// Pointer to a member function, representing the bound target function. - MemberFunc m_func = nullptr; -}; - -template -class DelegateMemberSp; // Not defined - -/// @brief `DelegateMemberSp<>` class synchronously invokes a class member target -/// function using a weak pointer. -/// @details This class is a "safe" version of DelegateMember. It holds a std::weak_ptr -/// to the target. If the target is destroyed, the callback is silently dropped. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMemberSp : public Delegate { -public: - typedef TClass* ObjectPtr; - typedef std::shared_ptr SharedPtr; - typedef std::weak_ptr WeakPtr; - typedef RetType(TClass::* MemberFunc)(Args...); - typedef RetType(TClass::* ConstMemberFunc)(Args...) const; - using ClassType = DelegateMemberSp; - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - DelegateMemberSp(SharedPtr object, MemberFunc func) { Bind(object, func); } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - DelegateMemberSp(SharedPtr object, ConstMemberFunc func) { Bind(object, func); } - - /// @brief Copy constructor. - DelegateMemberSp(const ClassType& rhs) { Assign(rhs); } - - /// @brief Move constructor. - DelegateMemberSp(ClassType&& rhs) noexcept : m_object(std::move(rhs.m_object)), m_func(rhs.m_func) { rhs.Clear(); } - - /// @brief Default constructor. - DelegateMemberSp() = default; - - /// @brief Destructor. - ~DelegateMemberSp() override { Clear(); } - - /// @brief Bind a member function to the delegate. - void Bind(SharedPtr object, MemberFunc func) { - static_assert(!std::is_const::value, "Cannot bind non-const function to const object."); - m_object = object; // Implicit conversion from shared_ptr to weak_ptr - m_func = func; - } - - /// @brief Bind a const member function to the delegate. - void Bind(SharedPtr object, ConstMemberFunc func) { - m_object = object; // Implicit conversion from shared_ptr to weak_ptr - // Note: Casting ConstMemberFunc to MemberFunc is formally UB when invoked - // through the non-const pointer, but works safely on all mainstream ABIs. - m_func = reinterpret_cast(func); - } - - /// @brief Creates a copy of the current object. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assigns the state of one object to another. - void Assign(const ClassType& rhs) { - m_object = rhs.m_object; - m_func = rhs.m_func; - } - - /// @brief Invoke the bound delegate function synchronously. - /// @details SAFELY locks the weak pointer. If object is dead, returns default. - virtual RetType operator()(Args... args) override { - // 1. Try to promote weak_ptr to strong shared_ptr - if (auto strongPtr = m_object.lock()) - { - // 2. SUCCESS: Object is alive. Invoke. - if constexpr (std::is_const::value) - return std::invoke(reinterpret_cast(m_func), strongPtr, std::forward(args)...); - else - return std::invoke(m_func, strongPtr, std::forward(args)...); - } - - // 3. FAILURE: Object is dead. Silently ignore. - return RetType(); - } - - /// @brief Assignment operator. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - m_object = std::move(rhs.m_object); - m_func = rhs.m_func; - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept { - return Clear(); - } - - /// @brief Compares two delegate objects for equality. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - if (!derivedRhs) return false; - - // Compare Weak Pointers by locking them first - auto ptr1 = m_object.lock(); - auto ptr2 = derivedRhs->m_object.lock(); - - return (ptr1 == ptr2) && (m_func == derivedRhs->m_func); - } - - // Standard operator== overloads - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - virtual bool operator==(std::nullptr_t) const noexcept override { return Empty(); } - virtual bool operator!=(std::nullptr_t) const noexcept override { return !Empty(); } - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { return rhs.Empty(); } - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { return !rhs.Empty(); } - - /// @brief Check if the delegate is bound and the object is alive. - bool Empty() const noexcept { return m_object.expired() || !m_func; } - - /// @brief Clear the target function. - void Clear() noexcept { m_object.reset(); m_func = nullptr; } - - explicit operator bool() const noexcept { return !Empty(); } - -private: - bool operator<(const ClassType& rhs) const = delete; - - /// Weak pointer to the target object. - WeakPtr m_object; - - /// Pointer to a member function. - MemberFunc m_func = nullptr; -}; - -template -class DelegateFunction; // Not defined - -/// @brief `DelegateFunction<>` class synchronously invokes a `std::function` target function. -/// @details Caution when binding to a `std::function` using this class. `std::function` cannot be -/// compared for equality directly in a meaningful way using `operator==`. Therefore, the delegate -/// library uses `target_type()` for comparison. `target_type()` only compares the types of the -/// stored callable objects, but the not actual instances. The code below shows the issue. -/// -/// `Test t1, t2;` -/// `std::function f1 = std::bind(&Test::Func, &t1, std::placeholders::_1);` -/// `std::function f2 = std::bind(&Test::Func, &t2, std::placeholders::_1);` -/// `MulticastDelegateSafe safe;` -/// `safe += MakeDelegate(f1);` -/// `safe += MakeDelegate(f2);` -/// `safe -= MakeDelegate(f2); // Should remove f2, not f1!` -/// -/// Depending on how usage, this may never be a issue but its worth noting. -/// -/// The other delegate classes has no such limitations and works under all conditions, -/// including comparing two instance functions of the same class. -/// -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFunction : public Delegate { -public: - using FunctionType = std::function; - using ClassType = DelegateFunction; - - /// @brief Constructor to create a class instance. - /// @param[in] func The target `std::function` to store. - DelegateFunction(FunctionType func) { Bind(func); } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFunction(const ClassType& rhs) { Assign(rhs); } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFunction(ClassType&& rhs) noexcept : m_func(std::move(rhs.m_func)) { rhs.Clear(); } - - /// @brief Default constructor creates an empty delegate. - DelegateFunction() = default; - - /// @brief Destructor ensures empty when destroyed. - ~DelegateFunction() override { Clear(); } - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The `std::function` to bind to the delegate. This function must - /// match the signature of the delegate. - void Bind(FunctionType func) { -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // No exceptions: Direct assignment. - // If the STL needs to allocate memory here and fails, - // it will likely abort() internally on embedded systems. - m_func = func; -#else - // Exceptions enabled: Safe to try-catch. - try { - m_func = func; - } - catch (const std::bad_alloc&) { - BAD_ALLOC(); - } -#endif - } - - /// Compares two ClassType objects using the '<' operator. - /// @param rhs The object to compare with. - /// @return `true` if the current object's value is less than the other object's value, - /// `false` otherwise. - bool operator<(const ClassType& rhs) const { - return m_func.template target() < rhs.m_func.template target(); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_func = rhs.m_func; - } - - /// @brief Invoke the bound delegate function synchronously. Always safe to call. - /// @param[in] args - the function arguments, if any. - /// @return The bound function return value, if any. If empty delegate - /// default return type returned. - virtual RetType operator()(Args... args) override { - if (Empty()) - return RetType(); - return m_func(std::forward(args)...); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - m_func = std::move(rhs.m_func); - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept { - return Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - if (derivedRhs) { - // If both delegates are empty, they are equal - if (Empty() && derivedRhs->Empty()) - return true; - - if (m_func && derivedRhs->m_func) - return m_func.target_type() == derivedRhs->m_func.target_type(); - - return false; - } - - return false; // Return false if dynamic cast failed - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Check if the delegate is bound to a target function. - /// @return `true` if the delegate has a target function, `false` otherwise. - bool Empty() const noexcept { return !m_func; } - - /// @brief Clear the target function. - /// @post The delegate is empty. - void Clear() noexcept { m_func = nullptr; } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the object is not empty, `false` if the object is empty. - explicit operator bool() const noexcept { return !Empty(); } - -private: - /// A std::function instance, representing the bound target function. - FunctionType m_func; -}; - -/// @brief Creates a delegate that binds to a free function. -/// @tparam RetType The return type of the free function. -/// @tparam Args The types of the function arguments. -/// @param[in] func A pointer to the free function to bind to the delegate. -/// @return A `DelegateFree` object bound to the specified free function. -template -auto MakeDelegate(RetType(*func)(Args... args)) { - return DelegateFree(func); -} - -/// @brief Creates a delegate that binds to a non-const member function. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @return A `DelegateMember` object bound to the specified non-const member function. -template -auto MakeDelegate(TClass* object, RetType(TClass::*func)(Args... args)) { - return DelegateMember(object, func); -} - -/// @brief Creates a delegate that binds to a const member function. -/// @tparam TClass The class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @return A `DelegateMember` object bound to the specified const member function. -template -auto MakeDelegate(TClass* object, RetType(TClass::*func)(Args... args) const) { - return DelegateMember(object, func); -} - -/// @brief Creates a delegate that binds to a const member function. -/// @tparam TClass The const class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @return A `DelegateMember` object bound to the specified non-const member function. -template -auto MakeDelegate(const TClass* object, RetType(TClass::* func)(Args... args) const) { - return DelegateMember(object, func); -} - -/// @brief Creates a delegate that binds to a non-const member function with a shared pointer to the object. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @return A `DelegateMember` shared pointer bound to the specified non-const member function. -template -auto MakeDelegate(std::shared_ptr object, RetType(TClass::* func)(Args... args)) { - return DelegateMemberSp(object, func); -} - -/// @brief Creates a delegate that binds to a const member function with a shared pointer to the object. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @return A `DelegateMember` shared pointer bound to the specified const member function. -template -auto MakeDelegate(std::shared_ptr object, RetType(TClass::* func)(Args... args) const) { - return DelegateMemberSp(object, func); -} - -/// @brief Creates a delegate that binds to a `std::function`. -/// @tparam RetType The return type of the `std::function`. -/// @tparam Args The types of the function arguments. -/// @param[in] func The `std::function` to bind to the delegate. -/// @return A `DelegateFunction` object bound to the specified `std::function`. -template -auto MakeDelegate(std::function func) { - return DelegateFunction(func); -} - -/// @brief Creates a delegate that binds to a raw lambda or functor. -/// @tparam F The lambda or functor type. -/// @param[in] func The lambda or functor to bind. -/// @return A `DelegateFunction` object bound to the specified lambda or functor. -template ::value>> -auto MakeDelegate(F&& func) { - // Deduce the signature from the operator() - using Sig = typename trait::function_traits::operator())>::function_type; - return DelegateFunction(std::forward(func)); -} - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/DelegateAsync.h b/DelegateMQ/delegate/DelegateAsync.h deleted file mode 100644 index e9bc4f3..0000000 --- a/DelegateMQ/delegate/DelegateAsync.h +++ /dev/null @@ -1,1230 +0,0 @@ -#ifndef _DELEGATE_ASYNC_H -#define _DELEGATE_ASYNC_H - -// DelegateAsync.h -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, Aug 2020. - -/// @file -/// @brief Delegate "`Async`" series of classes used to invoke a function asynchronously. -/// -/// @details The classes are not thread safe. Invoking a function asynchronously requires -/// sending a clone of the object to the destination thread message queue. The destination -/// thread calls `Invoke()` to invoke the target function. -/// -/// A `IThread` implementation is required to serialize and dispatch an async delegate onto -/// a destination thread of control. -/// -/// Argument data is created on the heap using `operator new` for transport thought a thread -/// message queue. An optional fixed-block allocator is available. See `DMQ_ALLOCATOR`. -/// -/// `RetType operator()(Args... args)` - called by the source thread to initiate the async -/// function call. May throw `std::bad_alloc` if dynamic storage allocation fails and `DMQ_ASSERTS` -/// is not defined. Clone() may also throw `std::bad_alloc` unless `DMQ_ASSERTS`. All other delegate -/// class functions do not throw exceptions. -/// -/// `void Invoke(std::shared_ptr msg)` - called by the destination -/// thread to invoke the target function. The destination thread must not call any other -/// delegate instance functions. -/// -/// Limitations: -/// -/// * The target function return value is not valid after invoke since the delegate does -/// not wait for the target function to be called. -/// -/// * Cannot use a `void*` as a target function argument. -/// -/// * Cannot use rvalue reference (T&&) as a target function argument. -/// -/// * Cannot insert `DelegateMemberAsync` into an ordered container. e.g. `std::list` ok, -/// `std::set` not ok. -/// -/// * `std::function` compares the function signature type, not the underlying object instance. -/// See `DelegateFunction<>` class for more info. -/// -/// Code within `` and `` is updated using src_dup.py. Manually update -/// the code within the `DelegateFreeAsync` `common_code` tags, then run the script to -/// propagate to the remaining delegate classes to simplify code maintenance. -/// -/// `python src_dup.py DelegateAsync.h` - -#include "Delegate.h" -#include "IThread.h" -#include "IInvoker.h" -#include -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -/// @brief Stores all function arguments suitable for non-blocking asynchronous calls. -/// By-value arguments are stored in the message itself; the data behind reference and -/// pointer arguments is copied to the heap, so it outlives the caller's stack. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateAsyncMsg : public DelegateMsg -{ -public: - /// Constructor - /// @param[in] invoker - the invoker instance - /// @param[in] priority - the delegate message priority - /// @param[in] args - a parameter pack of all target function arguments - /// @throws std::bad_alloc If a heap copy of a reference or pointer argument fails and DMQ_ASSERTS not defined. - DelegateAsyncMsg(std::shared_ptr invoker, Priority priority, Args... args) : DelegateMsg(invoker, priority), - m_args{ store_async_arg(m_heapMem, std::forward(args))... } { - } - - /// Delete the default constructor - DelegateAsyncMsg() = delete; - - /// Delete the copy constructor - DelegateAsyncMsg(const DelegateAsyncMsg&) = delete; - - /// Delete the copy assignment operator - DelegateAsyncMsg& operator=(const DelegateAsyncMsg&) = delete; - - /// Delete the move constructor and move assignment - DelegateAsyncMsg(DelegateAsyncMsg&&) = delete; - DelegateAsyncMsg& operator=(DelegateAsyncMsg&&) = delete; - - virtual ~DelegateAsyncMsg() = default; - - /// Get all function arguments that were created on the heap - /// @return A tuple of all function arguments - std::tuple& GetArgs() { return m_args; } - -private: - /// A list of heap allocated argument memory blocks - xlist> m_heapMem; - - /// The arguments: by-value ones held here, reference/pointer ones referring to - /// heap copies owned by `m_heapMem`. Declared after `m_heapMem`, so it is - /// constructed after it and destroyed before it. - std::tuple m_args; -}; - -namespace detail { - -/// @brief Non-template holder for a `DelegateXAsync<...>` instance's dispatch state -/// (destination thread, message priority). None of this depends on the bound function's -/// signature or target class, so every `DelegateFreeAsync`/`DelegateMemberAsync`/ -/// `DelegateMemberAsyncSp`/`DelegateFunctionAsync` instantiation composes this one -/// definition instead of each generating its own copy of the same two fields plus their -/// Assign()/Equal()/move-ctor plumbing. -class AsyncDispatchState { -public: - IThread* GetThread() const noexcept { return m_thread; } - void SetThread(IThread* thread) noexcept { m_thread = thread; } - Priority GetPriority() const noexcept { return m_priority; } - void SetPriority(Priority priority) noexcept { m_priority = priority; } - - bool Equal(const AsyncDispatchState& rhs) const noexcept { - return m_thread == rhs.m_thread && m_priority == rhs.m_priority; - } - -private: - IThread* m_thread = nullptr; - Priority m_priority = Priority::NORMAL; -}; - -/// @brief Builds the heap-copied argument message and dispatches it to `thread`. -/// @details Templated only on `Args...`, not on the owning delegate's target-object or -/// return type, so this single instantiation is shared by every `DelegateXAsync<...>` -/// signature that takes the same arguments, instead of each owning class generating its -/// own copy of this logic. -/// @param[in] invoker The already-cloned delegate to invoke on the destination thread, -/// type-erased through `IThreadInvoker`. -/// @param[in] thread The destination thread, or `nullptr` if unbound. -/// @param[in] priority The message priority. -/// @param[in] args The function arguments, if any. -template -void DispatchAsync(std::shared_ptr invoker, IThread* thread, Priority priority, Args&&... args) { - // Create a new message instance for sending to the destination thread. Erase to - // the non-templated DelegateMsg base BEFORE constructing the shared_ptr (rather - // than xmake_shared>) so the shared_ptr control block - // is not templated on Args... -- one control-block type is then shared across - // every DelegateAsync signature instead of duplicated per signature. - auto* rawMsg = new(std::nothrow) DelegateAsyncMsg(std::move(invoker), priority, std::forward(args)...); - if (!rawMsg) - BAD_ALLOC(); - DelegateMsg* msgBase = rawMsg; - std::shared_ptr msg(msgBase, std::default_delete(), dmq::stl_allocator()); - - if (thread) { - // Dispatch message onto the callback destination thread. Invoke() - // will be called by the destintation thread. - bool success = thread->DispatchDelegate(msg); - if (!success) { - LOG_ERROR("DelegateAsync dispatch failed"); - } - } -} - -} // namespace detail - -template -class DelegateFreeAsync; // Not defined - -/// @brief `DelegateFreeAsync<>` class asynchronously invokes a free target function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFreeAsync : public DelegateFree, public IThreadInvoker { -public: - typedef RetType(*FreeFunc)(Args...); - using ClassType = DelegateFreeAsync; - using BaseType = DelegateFree; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor to create a class instance. - /// @param[in] func The target free function to store. - /// @param[in] thread The execution thread to invoke `func`. - DelegateFreeAsync(FreeFunc func, IThread& thread) : - BaseType(func) { - Bind(func, thread); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFreeAsync(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFreeAsync(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateFreeAsync() = default; - - /// @brief Bind a free function to the delegate. - /// @details This method associates a free function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The free function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - void Bind(FreeFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - BaseType::Assign(rhs); - } - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function asynchronously. Called by the source thread. - /// @details Invoke delegate function asynchronously and do not wait for return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// The `DelegateAsyncMsg` duplicates and copies the function arguments into heap memory. - /// The source thread is not required to place function arguments into the heap. The delegate - /// library performs all necessary heap and argument coping for the caller. Ensure complex - /// argument data types can be safely copied by creating a copy constructor if necessary. - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - /// @throws std::bad_alloc If dynamic memory allocation fails and DMQ_ASSERTS not defined. - virtual RetType operator()(Args... args) override { - if (this->Empty()) - return RetType(); - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsync kind and signature instead of duplicated per signature. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - detail::DispatchAsync(delegate, m_state.GetThread(), m_state.GetPriority(), std::forward(args)...); - - // Do not wait for destination thread return value from async function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the source thread. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destintation thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. Unlike `DelegateAsyncWait`, a lock is not required between - /// source and destination `delegateMsg` access because the source thread is not waiting - /// for the function call to complete. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - return true; - } - - /// @brief Get the destination thread that the target function is invoked on. - /// @return The target thread. - IThread* GetThread() const noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Destination thread and message priority. Not templated on Sig/TClass — see - /// `detail::AsyncDispatchState`. - detail::AsyncDispatchState m_state; - - // -}; - -template -class DelegateMemberAsync; // Not defined - -/// @brief `DelegateMemberAsync<>` class asynchronously invokes a class member target function. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMemberAsync : public DelegateMember, public IThreadInvoker { -public: - typedef TClass* ObjectPtr; - typedef std::shared_ptr SharedPtr; - typedef RetType(TClass::* MemberFunc)(Args...); - typedef RetType(TClass::* ConstMemberFunc)(Args...) const; - using ClassType = DelegateMemberAsync; - using BaseType = DelegateMember; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - /// @param[in] thread The execution thread to invoke `func`. - DelegateMemberAsync(SharedPtr object, MemberFunc func, IThread& thread) : BaseType(object, func) { - Bind(object, func, thread); - } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - /// @param[in] thread The execution thread to invoke `func`. - DelegateMemberAsync(SharedPtr object, ConstMemberFunc func, IThread& thread) : BaseType(object, func) { - Bind(object, func, thread); - } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - /// @param[in] thread The execution thread to invoke `func`. - DelegateMemberAsync(ObjectPtr object, MemberFunc func, IThread& thread) : BaseType(object, func) { - Bind(object, func, thread); - } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - /// @param[in] thread The execution thread to invoke `func`. - DelegateMemberAsync(ObjectPtr object, ConstMemberFunc func, IThread& thread) : BaseType(object, func) { - Bind(object, func, thread); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateMemberAsync(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateMemberAsync(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateMemberAsync() = default; - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - void Bind(SharedPtr object, MemberFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - void Bind(SharedPtr object, ConstMemberFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(object, func); - } - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - void Bind(ObjectPtr object, MemberFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - void Bind(ObjectPtr object, ConstMemberFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(object, func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - BaseType::Assign(rhs); - } - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function asynchronously. Called by the source thread. - /// @details Invoke delegate function asynchronously and do not wait for return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// The `DelegateAsyncMsg` duplicates and copies the function arguments into heap memory. - /// The source thread is not required to place function arguments into the heap. The delegate - /// library performs all necessary heap and argument coping for the caller. Ensure complex - /// argument data types can be safely copied by creating a copy constructor if necessary. - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - /// @throws std::bad_alloc If dynamic memory allocation fails and DMQ_ASSERTS not defined. - virtual RetType operator()(Args... args) override { - if (this->Empty()) - return RetType(); - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsync kind and signature instead of duplicated per signature. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - detail::DispatchAsync(delegate, m_state.GetThread(), m_state.GetPriority(), std::forward(args)...); - - // Do not wait for destination thread return value from async function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the source thread. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destintation thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. Unlike `DelegateAsyncWait`, a lock is not required between - /// source and destination `delegateMsg` access because the source thread is not waiting - /// for the function call to complete. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - return true; - } - - /// @brief Get the destination thread that the target function is invoked on. - /// @return The target thread. - IThread* GetThread() const noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Destination thread and message priority. Not templated on Sig/TClass — see - /// `detail::AsyncDispatchState`. - detail::AsyncDispatchState m_state; - - // -}; - -template -class DelegateMemberAsyncSp; // Not defined - -/// @brief `DelegateMemberAsyncSp<>` class asynchronously invokes a class member target function -/// using a weak pointer (safe from use-after-free). -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMemberAsyncSp : public DelegateMemberSp, public IThreadInvoker { -public: - typedef TClass* ObjectPtr; - typedef std::shared_ptr SharedPtr; - typedef RetType(TClass::* MemberFunc)(Args...); - typedef RetType(TClass::* ConstMemberFunc)(Args...) const; - using ClassType = DelegateMemberAsyncSp; - using BaseType = DelegateMemberSp; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - DelegateMemberAsyncSp(SharedPtr object, MemberFunc func, IThread& thread) : BaseType(object, func) { - Bind(object, func, thread); - } - - DelegateMemberAsyncSp(SharedPtr object, ConstMemberFunc func, IThread& thread) : BaseType(object, func) { - Bind(object, func, thread); - } - - DelegateMemberAsyncSp(const ClassType& rhs) : BaseType(rhs) { Assign(rhs); } - - DelegateMemberAsyncSp(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateMemberAsyncSp() = default; - - void Bind(SharedPtr object, MemberFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(object, func); - } - - void Bind(SharedPtr object, ConstMemberFunc func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(object, func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - BaseType::Assign(rhs); - } - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function asynchronously. Called by the source thread. - /// @details Invoke delegate function asynchronously and do not wait for return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// The `DelegateAsyncMsg` duplicates and copies the function arguments into heap memory. - /// The source thread is not required to place function arguments into the heap. The delegate - /// library performs all necessary heap and argument coping for the caller. Ensure complex - /// argument data types can be safely copied by creating a copy constructor if necessary. - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - /// @throws std::bad_alloc If dynamic memory allocation fails and DMQ_ASSERTS not defined. - virtual RetType operator()(Args... args) override { - if (this->Empty()) - return RetType(); - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsync kind and signature instead of duplicated per signature. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - detail::DispatchAsync(delegate, m_state.GetThread(), m_state.GetPriority(), std::forward(args)...); - - // Do not wait for destination thread return value from async function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the source thread. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destintation thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. Unlike `DelegateAsyncWait`, a lock is not required between - /// source and destination `delegateMsg` access because the source thread is not waiting - /// for the function call to complete. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - return true; - } - - /// @brief Get the destination thread that the target function is invoked on. - /// @return The target thread. - IThread* GetThread() const noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Destination thread and message priority. Not templated on Sig/TClass — see - /// `detail::AsyncDispatchState`. - detail::AsyncDispatchState m_state; - - // -}; - -template -class DelegateFunctionAsync; // Not defined - -/// @brief `DelegateFunctionAsync<>` class asynchronously invokes a `std::function` target function. -/// @details Caution when binding to a `std::function` using this class. `std::function` cannot be -/// compared for equality directly in a meaningful way using `operator==`. Therefore, the delegate -/// library used -/// -/// See `DelegateFunction<>` base class for important usage limitations. -/// -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFunctionAsync : public DelegateFunction, public IThreadInvoker { -public: - using FunctionType = std::function; - using ClassType = DelegateFunctionAsync; - using BaseType = DelegateFunction; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor to create a class instance. - /// @param[in] func The target `std::function` to store. - /// @param[in] thread The execution thread to invoke `func`. - DelegateFunctionAsync(FunctionType func, IThread& thread) : - BaseType(func) { - Bind(func, thread); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFunctionAsync(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFunctionAsync(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateFunctionAsync() = default; - - /// @brief Bind a `std::function` to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The `std::function` to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - void Bind(FunctionType func, IThread& thread) { - m_state.SetThread(&thread); - BaseType::Bind(func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - BaseType::Assign(rhs); - } - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function asynchronously. Called by the source thread. - /// @details Invoke delegate function asynchronously and do not wait for return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// The `DelegateAsyncMsg` duplicates and copies the function arguments into heap memory. - /// The source thread is not required to place function arguments into the heap. The delegate - /// library performs all necessary heap and argument coping for the caller. Ensure complex - /// argument data types can be safely copied by creating a copy constructor if necessary. - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - /// @throws std::bad_alloc If dynamic memory allocation fails and DMQ_ASSERTS not defined. - virtual RetType operator()(Args... args) override { - if (this->Empty()) - return RetType(); - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsync kind and signature instead of duplicated per signature. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - detail::DispatchAsync(delegate, m_state.GetThread(), m_state.GetPriority(), std::forward(args)...); - - // Do not wait for destination thread return value from async function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the source thread. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destintation thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. Unlike `DelegateAsyncWait`, a lock is not required between - /// source and destination `delegateMsg` access because the source thread is not waiting - /// for the function call to complete. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - return true; - } - - /// @brief Get the destination thread that the target function is invoked on. - /// @return The target thread. - IThread* GetThread() const noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Destination thread and message priority. Not templated on Sig/TClass — see - /// `detail::AsyncDispatchState`. - detail::AsyncDispatchState m_state; - - // -}; - -/// @brief Creates an asynchronous delegate that binds to a free function. -/// @tparam RetType The return type of the free function. -/// @tparam Args The types of the function arguments. -/// @param[in] func A pointer to the free function to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateFreeAsync` object bound to the specified free function and thread. -template -auto MakeDelegate(RetType(*func)(Args... args), IThread& thread) { - return DelegateFreeAsync(func, thread); -} - -/// @brief Creates an asynchronous delegate that binds to a non-const member function. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateMemberAsync` object bound to the specified non-const member function and thread. -template -auto MakeDelegate(TClass* object, RetType(TClass::* func)(Args... args), IThread& thread) { - return DelegateMemberAsync(object, func, thread); -} - -/// @brief Creates an asynchronous delegate that binds to a const member function. -/// @tparam TClass The class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateMemberAsync` object bound to the specified const member function and thread. -template -auto MakeDelegate(TClass* object, RetType(TClass::* func)(Args... args) const, IThread& thread) { - return DelegateMemberAsync(object, func, thread); -} - -/// @brief Creates a delegate that binds to a const member function. -/// @tparam TClass The const class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateMemberAsync` object bound to the specified non-const member function. -template -auto MakeDelegate(const TClass* object, RetType(TClass::* func)(Args... args) const, IThread& thread) { - return DelegateMemberAsync(object, func, thread); -} - -/// @brief Creates an asynchronous delegate that binds to a non-const member function using a shared pointer. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateMemberAsyncSp` (SAFE) bound to the specified non-const member function and thread. -template -auto MakeDelegate(std::shared_ptr object, RetVal(TClass::* func)(Args... args), IThread& thread) { - return DelegateMemberAsyncSp(object, func, thread); -} - - -/// @brief Creates an asynchronous delegate that binds to a const member function using a shared pointer. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetVal The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateMemberAsyncSp` (SAFE) bound to the specified const member function and thread. -template -auto MakeDelegate(std::shared_ptr object, RetVal(TClass::* func)(Args... args) const, IThread& thread) { - return DelegateMemberAsyncSp(object, func, thread); -} - -/// @brief Creates an asynchronous delegate that binds to a `std::function`. -/// @tparam RetType The return type of the `std::function`. -/// @tparam Args The types of the function arguments. -/// @param[in] func The `std::function` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateFunctionAsync` object bound to the specified `std::function` and thread. -template -auto MakeDelegate(std::function func, IThread& thread) { - return DelegateFunctionAsync(func, thread); -} - -/// @brief Creates an asynchronous delegate that binds to a raw lambda or functor. -/// @tparam F The lambda or functor type. -/// @param[in] func The lambda or functor to bind. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @return A `DelegateFunctionAsync` object bound to the specified lambda or functor and thread. -template ::value>> -auto MakeDelegate(F&& func, IThread& thread) { - using Sig = typename trait::function_traits::operator())>::function_type; - return DelegateFunctionAsync(std::forward(func), thread); -} - -} - -DMQ_OPTIMIZE_OFF - -#endif \ No newline at end of file diff --git a/DelegateMQ/delegate/DelegateAsyncWait.h b/DelegateMQ/delegate/DelegateAsyncWait.h deleted file mode 100644 index 0a85dc4..0000000 --- a/DelegateMQ/delegate/DelegateAsyncWait.h +++ /dev/null @@ -1,1891 +0,0 @@ -#ifndef _DELEGATE_ASYNC_WAIT_H -#define _DELEGATE_ASYNC_WAIT_H - -#include "DelegateOpt.h" -#ifdef DMQ_HAS_SEMAPHORE - -// DelegateAsyncWait.h -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, Aug 2020. - -/// @file -/// @brief Delegate "`AsyncWait`" series of classes used to invoke a function asynchronously and -/// block waiting for completion by the target thread. -/// -/// @details Asynchronous delegate that invokes the target function on the specified thread of control -/// and waits for the function to be executed or a timeout occurs. Use IsSuccess() to determine if -/// asynchronous call succeeded before using the return value and outgoing argument values. -/// -/// A `IThread` implementation is required to serialize and dispatch an async delegate onto -/// a destination thread of control. -/// -/// Delegate "`AsyncWait`" series of classes used to invoke a function asynchronously and wait for -/// completion by the destination target thread. Invoking a function asynchronously requires making -/// a clone of the object to be sent to the destination thread message queue. The destination thread -/// calls `Invoke()` to invoke the target function. The source thread blocks on a semaphore -/// waiting for the destination thread to complete the function invoke. If the caller timeout expires, -/// the target function is not invoked. -/// -/// The `m_lock` mutex is used to protect shared state data between the source and destination -/// threads using the two thread-safe functions below: -/// -/// `RetType operator()(Args... args)` - called by the source thread to initiate the async -/// function call. May throw `std::bad_alloc` if dynamic storage allocation fails and `DMQ_ASSERTS` -/// is not defined. Clone() also may throw `std::bad_alloc` unless 'DMQ_ASSERTS'. All other delegate -/// class functions do not throw exceptions. -/// -/// `void Invoke(std::shared_ptr msg)` - called by the destination -/// thread to invoke the target function. The destination thread must not call any other -/// delegate instance functions. -/// -/// Limitations: -/// -/// * Cannot use rvalue reference (T&&) as a target function argument. -/// -/// * The target function cannot return a `std::unique_ptr` since `AsyncWait` destination -/// target thread stores the return value (`m_retVal`) for later use by the calling source thread. -/// -/// * Cannot insert `DelegateMemberAsyncWait` into an ordered container. e.g. `std::list` ok, -/// `std::set` not ok. -/// -/// * `std::function` compares the function signature type, not the underlying object instance. -/// See `DelegateFunction<>` class for more info. -/// -/// Code within `` and `` is updated using src_dup.py. Manually update -/// the code within the `DelegateFreeAsyncWait` `common_code` tags, then run the script to -/// propagate to the remaining delegate classes to simplify code maintenance. -/// -/// `python src_dup.py DelegateAsyncWait.h` - -#include "Delegate.h" -#include "Semaphore.h" -#include "IThread.h" -#include "IInvoker.h" -#include -#include -#include -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -// 1000 Hours (approx 41 days). -// Safe "infinite" wait that prevents integer overflow when added to current time -// on systems with nanosecond clock resolution (Linux/Windows). -constexpr auto WAIT_INFINITE = std::chrono::hours(1000); - -/// @brief Stores all function arguments suitable for blocking asynchronous calls. -/// Argument data is not stored in the heap. -/// @tparam Args The target function arguments. -template -class DelegateAsyncWaitMsg : public DelegateMsg -{ -public: - /// Constructor - /// @param[in] invoker - the invoker instance - /// @param[in] priority - the delegate message priority - /// @param[in] args - a parameter pack of all target function arguments - DelegateAsyncWaitMsg(std::shared_ptr invoker, Priority priority, Args... args) : DelegateMsg(invoker, priority), - m_args(std::forward(args)...) {} - - /// Delete the default constructor - DelegateAsyncWaitMsg() = delete; - - /// Delete the copy constructor - DelegateAsyncWaitMsg(const DelegateAsyncWaitMsg&) = delete; - - /// Delete the copy assignment operator - DelegateAsyncWaitMsg& operator=(const DelegateAsyncWaitMsg&) = delete; - - /// Delete the move constructor and move assignment - DelegateAsyncWaitMsg(DelegateAsyncWaitMsg&&) = delete; - DelegateAsyncWaitMsg& operator=(DelegateAsyncWaitMsg&&) = delete; - - virtual ~DelegateAsyncWaitMsg() = default; - - /// Release the blocked sender without invoking: its wait ends with the invoke - /// not succeeded (GetInvokeSucceeded() stays false), so the call reports failure. - void Cancel() override { m_sema.Signal(); } - - /// Get all function arguments - /// @return A tuple of all function arguments - std::tuple& GetArgs() { return m_args; } - - /// Get the semaphore used to signal the sending thread that the receiving - /// thread has invoked the target function. - /// @return The semaphore reference. - Semaphore& GetSema() { return m_sema; } - - /// Get a mutex shared between sender and receiver threads. - /// @return The lock reference. - Mutex& GetLock() { return m_lock; } - - /// True if the sending thread is waiting for the receiver thread to call the function. - /// False if the sending thread delegate timeout occurred and is not waiting. - /// @return `true` if the sending thread is waiting for the receiving thread to complete - /// the target function invoke. - bool GetInvokerWaiting() { return m_invokerWaiting; } - - /// Set to true when source thread is waiting for destination thread to complete the - /// function call. - /// @param[in] invokerWaiting The status of the invoker waiting flag. - void SetInvokerWaiting(bool invokerWaiting) { m_invokerWaiting = invokerWaiting; } - - /// True if the destination thread's target function invoke completed without an - /// exception propagating out of it. False if the target function threw (or hasn't - /// been invoked yet). Distinct from the source thread's semaphore wait succeeding: - /// the semaphore is always signaled on scope exit from `Invoke()`, including via an - /// exception, so this flag is what lets the source thread tell the two cases apart. - /// @return `true` if the target function invoke completed successfully. - bool GetInvokeSucceeded() { return m_invokeSucceeded; } - - /// Set to true by the destination thread immediately after the target function - /// invoke returns without throwing. - /// @param[in] invokeSucceeded The status of the invoke-succeeded flag. - void SetInvokeSucceeded(bool invokeSucceeded) { m_invokeSucceeded = invokeSucceeded; } - -private: - /// A tuple with each function argument element - std::tuple m_args; - - /// Semaphore to signal waiting thread - Semaphore m_sema; - - /// Lock to protect shared data - Mutex m_lock; - - /// True if source thread is waiting for destination thread invoke to complete - bool m_invokerWaiting = false; - - /// True once the destination thread's target function invoke has completed - /// without an exception propagating out of it - bool m_invokeSucceeded = false; -}; - -namespace detail { - -/// @brief Lock guarding every `DelegateXAsyncWait` instance's last-call result. -/// @details One lock shared by all instances rather than one per instance: each call -/// clones its delegate, and on RTOS ports a `dmq::Mutex` is a kernel object, so a -/// per-instance lock would create one on every call. It is held only to copy one -/// result in or out. Intentionally never destroyed (same as `Timer::GetLock()`), so a -/// delegate destroyed during static destruction can still use it. -inline RecursiveMutex& AsyncWaitResultLock() { - static RecursiveMutex* lock = new(std::nothrow) RecursiveMutex(); - if (!lock) - BAD_ALLOC(); - return *lock; -} - -/// @brief Non-template holder for a `DelegateXAsyncWait<...>` instance's dispatch state -/// (destination thread, message priority, timeout, and whether the last async call -/// succeeded). The last call's return value is stored, typed, on the owning delegate. -/// None of this depends on the bound function's signature or target class, so every -/// `DelegateFreeAsyncWait`/`DelegateMemberAsyncWait`/`DelegateMemberAsyncWaitSp`/ -/// `DelegateFunctionAsyncWait` instantiation composes this one definition instead of each -/// generating its own copy of these five fields plus their Assign()/Equal()/move-ctor -/// plumbing. -class AsyncWaitDispatchState { -public: - AsyncWaitDispatchState() = default; - - /// A copy takes the dispatch settings but not the last-call result. - AsyncWaitDispatchState(const AsyncWaitDispatchState& rhs) noexcept - : m_thread(rhs.m_thread), m_priority(rhs.m_priority), m_timeout(rhs.m_timeout) {} - - AsyncWaitDispatchState& operator=(const AsyncWaitDispatchState& rhs) noexcept { - if (this != &rhs) { - m_thread = rhs.m_thread; - m_priority = rhs.m_priority; - m_timeout = rhs.m_timeout; - ResetResult(); - } - return *this; - } - - IThread* GetThread() const noexcept { return m_thread; } - void SetThread(IThread* thread) noexcept { m_thread = thread; } - Priority GetPriority() const noexcept { return m_priority; } - void SetPriority(Priority priority) noexcept { m_priority = priority; } - Duration GetTimeout() const noexcept { return m_timeout; } - void SetTimeout(Duration timeout) noexcept { m_timeout = timeout; } - - bool IsSuccess() const noexcept { - const dmq::LockGuard lock(AsyncWaitResultLock()); - return m_success; - } - - /// Reset the last call's success flag. - void ResetResult() noexcept { - const dmq::LockGuard lock(AsyncWaitResultLock()); - m_success = false; - } - - /// Record whether the last call succeeded. - void SetSuccess(bool success) noexcept { - const dmq::LockGuard lock(AsyncWaitResultLock()); - m_success = success; - } - - bool Equal(const AsyncWaitDispatchState& rhs) const noexcept { - return m_thread == rhs.m_thread && m_priority == rhs.m_priority && m_timeout == rhs.m_timeout; - } - -private: - IThread* m_thread = nullptr; - Priority m_priority = Priority::NORMAL; - Duration m_timeout = WAIT_INFINITE; - bool m_success = false; -}; - -/// @brief Builds the argument message, dispatches it to `thread`, and waits (up to -/// `timeout`) for the destination thread to signal completion. -/// @details Templated only on `Args...`, not on the owning delegate's target-object or -/// return type, so this single instantiation is shared by every `DelegateXAsyncWait<...>` -/// signature that takes the same arguments, instead of each owning class generating its -/// own copy of this logic. -/// @param[in] invoker The already-cloned delegate to invoke on the destination thread, -/// type-erased through `IThreadInvoker`. -/// @param[in] thread The destination thread, or `nullptr` if unbound. -/// @param[in] priority The message priority. -/// @param[in] timeout How long to wait for the destination thread to invoke the function. -/// @param[in] args The function arguments, if any. -/// @return `true` if the destination thread invoked the target function and the invoke -/// completed without an exception propagating out of it; `false` otherwise. A call that -/// had already started when `timeout` expired is waited for and counts as success. -/// The caller is responsible for pulling the return value off its own cloned delegate -/// (written there by `Invoke()` on the destination thread) when this returns `true`. -template -bool DispatchAsyncWait(std::shared_ptr invoker, IThread* thread, Priority priority, - Duration timeout, Args&&... args) { - // Create a new message instance for sending to the destination thread. Erase to - // the non-templated DelegateMsg base BEFORE constructing the shared_ptr (rather - // than xmake_shared>) so the shared_ptr control - // block is not templated on Args... -- one control-block type is then shared - // across every DelegateAsyncWait signature instead of duplicated per signature. - // `rawMsg` stays valid for the whole function (kept alive by `msg`) and is used - // for every access specific to the concrete DelegateAsyncWaitMsg type; - // `msg` itself is only needed, as the erased base, for DispatchDelegate(). - auto* rawMsg = new(std::nothrow) DelegateAsyncWaitMsg(std::move(invoker), priority, std::forward(args)...); - if (!rawMsg) - BAD_ALLOC(); - DelegateMsg* msgBase = rawMsg; - std::shared_ptr msg(msgBase, std::default_delete(), dmq::stl_allocator()); - rawMsg->SetInvokerWaiting(true); - - if (thread) { - // Dispatch message onto the callback destination thread. Invoke() - // will be called by the destination thread. - if (thread->DispatchDelegate(msg)) { - // Wait for destination thread to execute the delegate function and get return value - // Its result isn't needed: GetInvokeSucceeded() below is the answer. - (void)rawMsg->GetSema().Wait(timeout); - } - } - - // Single lock: read the result and clear InvokerWaiting atomically. Invoke() - // holds this lock for the whole target call, so once it's acquired the call has - // either completed or will never run (InvokerWaiting is cleared below). - const dmq::LockGuard lock(rawMsg->GetLock()); - // Success means the target call completed without throwing -- including a call - // that was already running when the timeout expired (the lock above waited for - // it). The semaphore is signaled even when the target threw or the message was - // cancelled, so the wait succeeding doesn't mean the call succeeded. - bool success = rawMsg->GetInvokeSucceeded(); - // Set flag that source is not waiting anymore - rawMsg->SetInvokerWaiting(false); - return success; -} - -} // namespace detail - -template -class DelegateFreeAsyncWait; // Not defined - -/// @brief `DelegateFreeAsyncWait<>` class asynchronously block invokes a free target function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFreeAsyncWait : public DelegateFree, public IThreadInvoker { -public: - typedef RetType(*FreeFunc)(Args...); - using ClassType = DelegateFreeAsyncWait; - using BaseType = DelegateFree; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor to create a class instance. - /// @param[in] func The target free function to store. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - DelegateFreeAsyncWait(FreeFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) : - BaseType(func) { - Bind(func, thread, timeout); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFreeAsyncWait(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFreeAsyncWait(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateFreeAsyncWait() = default; - - /// @brief Bind a free function to the delegate. - /// @details This method associates a free function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The free function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - void Bind(FreeFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_retVal.reset(); - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - m_retVal.reset(); - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. - /// @details Invoke delegate function asynchronously and wait for the return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// If the destination thread invokes the function within `m_timeout`, the return - /// value is obtained from the destination thread function call. If `m_timeout` expires - /// before the destination thread starts the call, the target function is not invoked - /// and a default return value is returned. If the call has already started when - /// `m_timeout` expires, the caller waits for it to finish and gets its return value. - /// Use `IsSuccess()` to check for success before using the return value. Alternatively, - /// use `AsyncInvoke()` and check the `std::optional` return value. - /// - /// The `DelegateAsyncWaitMsg` does not duplicate and copy the function arguments into heap - /// memory. The source thread waits on the destintation thread to complete, therefore argument - /// data is shared between the source and destination threads and simultaneous access is prevented - /// using a mutex. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value, if any. Use `IsSuccess()` to determine if - /// the return value is valid before use. - virtual RetType operator()(Args... args) override { - // The result lives in locals, so concurrent callers sharing this instance - // (e.g. one Signal emitted from two threads) each get their own return value. - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == false) { - return success ? TakeRet(retVal) : RetType(); - } - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. Always safe to call, including concurrently. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value stored withing `std::optional`. Use - /// `has_value()` to check if the the return value is valid. `value()` contains - /// the target function return value. - auto AsyncInvoke(Args... args) { - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == true) { - return success ? std::optional(true) : std::optional(); - } else { - return success ? std::optional(TakeRet(retVal)) : std::optional(); - } - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destination thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. A lock is used to protect source and destination thread shared - /// data. A semaphore is used to signal the source thread when the destination thread - /// completes the target function call. - /// - /// If source thread timeout expires and before the destination thread invokes the - /// target function, the target function is not called. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked or timeout expired; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - static_assert(!(is_unique_ptr::value), "std::unique_ptr return value not allowed"); - - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Protect data shared between source and destination threads - const dmq::LockGuard lock(delegateMsg->GetLock()); - - // Is the source thread waiting for the target function invoke to complete? - if (delegateMsg->GetInvokerWaiting()) { - // Signals the source thread when this scope exits, including via an exception - // propagating out of the target function invoke below. Without this, a target - // function that throws would leave the source thread blocked until timeout. - struct SemaSignalGuard { - Semaphore& sema; - ~SemaSignalGuard() { sema.Signal(); } - } semaSignalGuard{ delegateMsg->GetSema() }; - - // Does target function have a void return value? - if constexpr (std::is_void::value == true) { - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - } else { - // As above, and keep the return value (in this clone's typed slot). - m_retVal.emplace(std::apply( - [this](auto&... args) -> RetType { return this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs())); - } - - // Only reached if the std::apply() call above did not throw - delegateMsg->SetInvokeSucceeded(true); - } - return true; - } - - /// Returns `true` if the last asynchronous call on this delegate succeeded. - /// @return `true` if the target asynchronous function call succeeded. `false` if - /// the timeout expired before the target function could be invoked. - /// @note If several threads call this delegate concurrently, this reports whichever - /// call finished last. Use `AsyncInvoke()`'s return value to get each call's own result. - bool IsSuccess() noexcept { return m_state.IsSuccess(); } - - /// Get the asynchronous function return value of the last call on this delegate. - /// @return The destination thread target function return value - /// @note Same caveat as `IsSuccess()` for concurrent callers. - RetType GetRetVal() noexcept { - if constexpr (std::is_void::value == false) { - std::optional copy; - { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - copy = m_retVal; - } - return TakeRet(copy); - } - } - ///@brief Get the destination thread that the target function is invoked on. - // @return The target thread. - IThread* GetThread() noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Return value storage type (std::optional can't hold void). - using RetStorage = std::conditional_t::value, bool, std::decay_t>; - - /// Dispatch to the destination thread and wait (up to the timeout) for the call. - /// @param[out] retVal The target function's return value, set when this returns `true`. - /// @return `true` if the target function was invoked and completed. - bool DispatchWait(std::optional& retVal, Args&&... args) { - if (this->Empty()) - return false; - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsyncWait kind and signature instead of duplicated per signature. - // `rawClone` stays valid for the whole function (kept alive by `delegate`) - // and is used below to read back the clone's own result state. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - bool success = detail::DispatchAsyncWait(delegate, m_state.GetThread(), m_state.GetPriority(), - m_state.GetTimeout(), std::forward(args)...); - if (success) { - // Invoke() (running as the clone, on the destination thread) wrote the - // target function's return value into the clone's own m_retVal. - retVal = std::move(rawClone->m_retVal); - } - return success; - } - - /// Move the value out of `v`, or return a default value if it holds none. - static RetType TakeRet(std::optional& v) noexcept { - if (v) return std::move(*v); -#if defined(DMQ_ASSERTS) - DMQ_ASSERT(); // no result stored (e.g. GetRetVal() before any successful call) -#endif - return RetType(); - } - - /// Record a call's result as this delegate's last result, for IsSuccess()/GetRetVal(). - void SetLastResult(bool success, const std::optional& retVal) { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - m_state.SetSuccess(success); - m_retVal = retVal; - } - - /// Destination thread, message priority, timeout, and whether the last async call - /// succeeded. Not templated on Sig/TClass — see `detail::AsyncWaitDispatchState`. - detail::AsyncWaitDispatchState m_state; - - /// Return value, typed so a large return type needs no heap allocation (std::any - /// put anything over its small buffer on the global heap). On the per-call clone: - /// that call's result, written by Invoke() on the destination thread and read by - /// the caller after the message lock. On the caller's delegate: the last call's - /// result for GetRetVal(), guarded by detail::AsyncWaitResultLock(). - std::optional m_retVal; - - // -}; - -template -class DelegateMemberAsyncWait; // Not defined - -/// @brief `DelegateMemberAsyncWait<>` class asynchronously block invokes a class member target function. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMemberAsyncWait : public DelegateMember, public IThreadInvoker { -public: - typedef TClass* ObjectPtr; - typedef std::shared_ptr SharedPtr; - typedef RetType(TClass::* MemberFunc)(Args...); - typedef RetType(TClass::* ConstMemberFunc)(Args...) const; - using ClassType = DelegateMemberAsyncWait; - using BaseType = DelegateMember; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - DelegateMemberAsyncWait(SharedPtr object, MemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) : - BaseType(object, func) { - Bind(object, func, thread, timeout); - } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - DelegateMemberAsyncWait(SharedPtr object, ConstMemberFunc func, IThread& thread, Duration timeout) : - BaseType(object, func) { - Bind(object, func, thread, timeout); - } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - DelegateMemberAsyncWait(ObjectPtr object, MemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) : - BaseType(object, func) { - Bind(object, func, thread, timeout); - } - - /// @brief Constructor to create a class instance. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - DelegateMemberAsyncWait(ObjectPtr object, ConstMemberFunc func, IThread& thread, Duration timeout) : - BaseType(object, func) { - Bind(object, func, thread, timeout); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateMemberAsyncWait(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateMemberAsyncWait(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateMemberAsyncWait() = default; - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - void Bind(SharedPtr object, MemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - void Bind(SharedPtr object, ConstMemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(object, func); - } - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - void Bind(ObjectPtr object, MemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - void Bind(ObjectPtr object, ConstMemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(object, func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_retVal.reset(); - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - m_retVal.reset(); - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. - /// @details Invoke delegate function asynchronously and wait for the return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// If the destination thread invokes the function within `m_timeout`, the return - /// value is obtained from the destination thread function call. If `m_timeout` expires - /// before the destination thread starts the call, the target function is not invoked - /// and a default return value is returned. If the call has already started when - /// `m_timeout` expires, the caller waits for it to finish and gets its return value. - /// Use `IsSuccess()` to check for success before using the return value. Alternatively, - /// use `AsyncInvoke()` and check the `std::optional` return value. - /// - /// The `DelegateAsyncWaitMsg` does not duplicate and copy the function arguments into heap - /// memory. The source thread waits on the destintation thread to complete, therefore argument - /// data is shared between the source and destination threads and simultaneous access is prevented - /// using a mutex. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value, if any. Use `IsSuccess()` to determine if - /// the return value is valid before use. - virtual RetType operator()(Args... args) override { - // The result lives in locals, so concurrent callers sharing this instance - // (e.g. one Signal emitted from two threads) each get their own return value. - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == false) { - return success ? TakeRet(retVal) : RetType(); - } - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. Always safe to call, including concurrently. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value stored withing `std::optional`. Use - /// `has_value()` to check if the the return value is valid. `value()` contains - /// the target function return value. - auto AsyncInvoke(Args... args) { - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == true) { - return success ? std::optional(true) : std::optional(); - } else { - return success ? std::optional(TakeRet(retVal)) : std::optional(); - } - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destination thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. A lock is used to protect source and destination thread shared - /// data. A semaphore is used to signal the source thread when the destination thread - /// completes the target function call. - /// - /// If source thread timeout expires and before the destination thread invokes the - /// target function, the target function is not called. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked or timeout expired; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - static_assert(!(is_unique_ptr::value), "std::unique_ptr return value not allowed"); - - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Protect data shared between source and destination threads - const dmq::LockGuard lock(delegateMsg->GetLock()); - - // Is the source thread waiting for the target function invoke to complete? - if (delegateMsg->GetInvokerWaiting()) { - // Signals the source thread when this scope exits, including via an exception - // propagating out of the target function invoke below. Without this, a target - // function that throws would leave the source thread blocked until timeout. - struct SemaSignalGuard { - Semaphore& sema; - ~SemaSignalGuard() { sema.Signal(); } - } semaSignalGuard{ delegateMsg->GetSema() }; - - // Does target function have a void return value? - if constexpr (std::is_void::value == true) { - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - } else { - // As above, and keep the return value (in this clone's typed slot). - m_retVal.emplace(std::apply( - [this](auto&... args) -> RetType { return this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs())); - } - - // Only reached if the std::apply() call above did not throw - delegateMsg->SetInvokeSucceeded(true); - } - return true; - } - - /// Returns `true` if the last asynchronous call on this delegate succeeded. - /// @return `true` if the target asynchronous function call succeeded. `false` if - /// the timeout expired before the target function could be invoked. - /// @note If several threads call this delegate concurrently, this reports whichever - /// call finished last. Use `AsyncInvoke()`'s return value to get each call's own result. - bool IsSuccess() noexcept { return m_state.IsSuccess(); } - - /// Get the asynchronous function return value of the last call on this delegate. - /// @return The destination thread target function return value - /// @note Same caveat as `IsSuccess()` for concurrent callers. - RetType GetRetVal() noexcept { - if constexpr (std::is_void::value == false) { - std::optional copy; - { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - copy = m_retVal; - } - return TakeRet(copy); - } - } - ///@brief Get the destination thread that the target function is invoked on. - // @return The target thread. - IThread* GetThread() noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Return value storage type (std::optional can't hold void). - using RetStorage = std::conditional_t::value, bool, std::decay_t>; - - /// Dispatch to the destination thread and wait (up to the timeout) for the call. - /// @param[out] retVal The target function's return value, set when this returns `true`. - /// @return `true` if the target function was invoked and completed. - bool DispatchWait(std::optional& retVal, Args&&... args) { - if (this->Empty()) - return false; - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsyncWait kind and signature instead of duplicated per signature. - // `rawClone` stays valid for the whole function (kept alive by `delegate`) - // and is used below to read back the clone's own result state. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - bool success = detail::DispatchAsyncWait(delegate, m_state.GetThread(), m_state.GetPriority(), - m_state.GetTimeout(), std::forward(args)...); - if (success) { - // Invoke() (running as the clone, on the destination thread) wrote the - // target function's return value into the clone's own m_retVal. - retVal = std::move(rawClone->m_retVal); - } - return success; - } - - /// Move the value out of `v`, or return a default value if it holds none. - static RetType TakeRet(std::optional& v) noexcept { - if (v) return std::move(*v); -#if defined(DMQ_ASSERTS) - DMQ_ASSERT(); // no result stored (e.g. GetRetVal() before any successful call) -#endif - return RetType(); - } - - /// Record a call's result as this delegate's last result, for IsSuccess()/GetRetVal(). - void SetLastResult(bool success, const std::optional& retVal) { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - m_state.SetSuccess(success); - m_retVal = retVal; - } - - /// Destination thread, message priority, timeout, and whether the last async call - /// succeeded. Not templated on Sig/TClass — see `detail::AsyncWaitDispatchState`. - detail::AsyncWaitDispatchState m_state; - - /// Return value, typed so a large return type needs no heap allocation (std::any - /// put anything over its small buffer on the global heap). On the per-call clone: - /// that call's result, written by Invoke() on the destination thread and read by - /// the caller after the message lock. On the caller's delegate: the last call's - /// result for GetRetVal(), guarded by detail::AsyncWaitResultLock(). - std::optional m_retVal; - - // -}; - -template -class DelegateMemberAsyncWaitSp; // Not defined - -/// @brief `DelegateMemberAsyncWaitSp<>` class asynchronously block invokes a class member target function -/// using a weak/shared pointer semantics. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMemberAsyncWaitSp : public DelegateMemberSp, public IThreadInvoker { -public: - using SharedPtr = std::shared_ptr; - using MemberFunc = RetType(TClass::*)(Args...); - using ConstMemberFunc = RetType(TClass::*)(Args...) const; - using ClassType = DelegateMemberAsyncWaitSp; - using BaseType = DelegateMemberSp; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor for non-const member function - DelegateMemberAsyncWaitSp(SharedPtr object, MemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) : - BaseType(object, func) { - Bind(object, func, thread, timeout); - } - - /// @brief Constructor for const member function - DelegateMemberAsyncWaitSp(SharedPtr object, ConstMemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) : - BaseType(object, func) { - Bind(object, func, thread, timeout); - } - - /// @brief Copy constructor - DelegateMemberAsyncWaitSp(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor - DelegateMemberAsyncWaitSp(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateMemberAsyncWaitSp() = default; - - /// @brief Bind a non-const member function - void Bind(SharedPtr object, MemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function - void Bind(SharedPtr object, ConstMemberFunc func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(object, func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_retVal.reset(); - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - m_retVal.reset(); - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. - /// @details Invoke delegate function asynchronously and wait for the return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// If the destination thread invokes the function within `m_timeout`, the return - /// value is obtained from the destination thread function call. If `m_timeout` expires - /// before the destination thread starts the call, the target function is not invoked - /// and a default return value is returned. If the call has already started when - /// `m_timeout` expires, the caller waits for it to finish and gets its return value. - /// Use `IsSuccess()` to check for success before using the return value. Alternatively, - /// use `AsyncInvoke()` and check the `std::optional` return value. - /// - /// The `DelegateAsyncWaitMsg` does not duplicate and copy the function arguments into heap - /// memory. The source thread waits on the destintation thread to complete, therefore argument - /// data is shared between the source and destination threads and simultaneous access is prevented - /// using a mutex. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value, if any. Use `IsSuccess()` to determine if - /// the return value is valid before use. - virtual RetType operator()(Args... args) override { - // The result lives in locals, so concurrent callers sharing this instance - // (e.g. one Signal emitted from two threads) each get their own return value. - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == false) { - return success ? TakeRet(retVal) : RetType(); - } - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. Always safe to call, including concurrently. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value stored withing `std::optional`. Use - /// `has_value()` to check if the the return value is valid. `value()` contains - /// the target function return value. - auto AsyncInvoke(Args... args) { - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == true) { - return success ? std::optional(true) : std::optional(); - } else { - return success ? std::optional(TakeRet(retVal)) : std::optional(); - } - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destination thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. A lock is used to protect source and destination thread shared - /// data. A semaphore is used to signal the source thread when the destination thread - /// completes the target function call. - /// - /// If source thread timeout expires and before the destination thread invokes the - /// target function, the target function is not called. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked or timeout expired; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - static_assert(!(is_unique_ptr::value), "std::unique_ptr return value not allowed"); - - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Protect data shared between source and destination threads - const dmq::LockGuard lock(delegateMsg->GetLock()); - - // Is the source thread waiting for the target function invoke to complete? - if (delegateMsg->GetInvokerWaiting()) { - // Signals the source thread when this scope exits, including via an exception - // propagating out of the target function invoke below. Without this, a target - // function that throws would leave the source thread blocked until timeout. - struct SemaSignalGuard { - Semaphore& sema; - ~SemaSignalGuard() { sema.Signal(); } - } semaSignalGuard{ delegateMsg->GetSema() }; - - // Does target function have a void return value? - if constexpr (std::is_void::value == true) { - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - } else { - // As above, and keep the return value (in this clone's typed slot). - m_retVal.emplace(std::apply( - [this](auto&... args) -> RetType { return this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs())); - } - - // Only reached if the std::apply() call above did not throw - delegateMsg->SetInvokeSucceeded(true); - } - return true; - } - - /// Returns `true` if the last asynchronous call on this delegate succeeded. - /// @return `true` if the target asynchronous function call succeeded. `false` if - /// the timeout expired before the target function could be invoked. - /// @note If several threads call this delegate concurrently, this reports whichever - /// call finished last. Use `AsyncInvoke()`'s return value to get each call's own result. - bool IsSuccess() noexcept { return m_state.IsSuccess(); } - - /// Get the asynchronous function return value of the last call on this delegate. - /// @return The destination thread target function return value - /// @note Same caveat as `IsSuccess()` for concurrent callers. - RetType GetRetVal() noexcept { - if constexpr (std::is_void::value == false) { - std::optional copy; - { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - copy = m_retVal; - } - return TakeRet(copy); - } - } - ///@brief Get the destination thread that the target function is invoked on. - // @return The target thread. - IThread* GetThread() noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Return value storage type (std::optional can't hold void). - using RetStorage = std::conditional_t::value, bool, std::decay_t>; - - /// Dispatch to the destination thread and wait (up to the timeout) for the call. - /// @param[out] retVal The target function's return value, set when this returns `true`. - /// @return `true` if the target function was invoked and completed. - bool DispatchWait(std::optional& retVal, Args&&... args) { - if (this->Empty()) - return false; - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsyncWait kind and signature instead of duplicated per signature. - // `rawClone` stays valid for the whole function (kept alive by `delegate`) - // and is used below to read back the clone's own result state. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - bool success = detail::DispatchAsyncWait(delegate, m_state.GetThread(), m_state.GetPriority(), - m_state.GetTimeout(), std::forward(args)...); - if (success) { - // Invoke() (running as the clone, on the destination thread) wrote the - // target function's return value into the clone's own m_retVal. - retVal = std::move(rawClone->m_retVal); - } - return success; - } - - /// Move the value out of `v`, or return a default value if it holds none. - static RetType TakeRet(std::optional& v) noexcept { - if (v) return std::move(*v); -#if defined(DMQ_ASSERTS) - DMQ_ASSERT(); // no result stored (e.g. GetRetVal() before any successful call) -#endif - return RetType(); - } - - /// Record a call's result as this delegate's last result, for IsSuccess()/GetRetVal(). - void SetLastResult(bool success, const std::optional& retVal) { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - m_state.SetSuccess(success); - m_retVal = retVal; - } - - /// Destination thread, message priority, timeout, and whether the last async call - /// succeeded. Not templated on Sig/TClass — see `detail::AsyncWaitDispatchState`. - detail::AsyncWaitDispatchState m_state; - - /// Return value, typed so a large return type needs no heap allocation (std::any - /// put anything over its small buffer on the global heap). On the per-call clone: - /// that call's result, written by Invoke() on the destination thread and read by - /// the caller after the message lock. On the caller's delegate: the last call's - /// result for GetRetVal(), guarded by detail::AsyncWaitResultLock(). - std::optional m_retVal; - - // -}; - -template -class DelegateFunctionAsyncWait; // Not defined - -/// @brief `DelegateFunctionAsyncWait<>` class asynchronously block invokes a std::function target function. -/// -/// See `DelegateFunction<>` base class for important usage limitations. -/// -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFunctionAsyncWait : public DelegateFunction, public IThreadInvoker { -public: - using FunctionType = std::function; - using ClassType = DelegateFunctionAsyncWait; - using BaseType = DelegateFunction; - - static_assert(!(std::disjunction_v...>), - "Non-const std::shared_ptr reference/pointer arguments are not allowed"); - - /// @brief Constructor to create a class instance. - /// @param[in] func The target `std::function` to store. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - DelegateFunctionAsyncWait(FunctionType func, IThread& thread, Duration timeout = WAIT_INFINITE) : - BaseType(func) { - Bind(func, thread, timeout); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFunctionAsyncWait(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFunctionAsyncWait(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(rhs.m_state) { - rhs.Clear(); - } - - DelegateFunctionAsyncWait() = default; - - /// @brief Bind a `std::function` to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The `std::function` to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] thread The execution thread to invoke `func`. - /// @param[in] timeout The calling thread timeout for destination thread to - /// invoke the target function. - void Bind(FunctionType func, IThread& thread, Duration timeout = WAIT_INFINITE) { - m_state.SetThread(&thread); - m_state.SetTimeout(timeout); - BaseType::Bind(func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_retVal.reset(); - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = rhs.m_state; // Use the resource - m_retVal.reset(); - rhs.Clear(); - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. - /// @details Invoke delegate function asynchronously and wait for the return value. - /// This function is called by the source thread. Dispatches the delegate data into the - /// destination thread message queue. `Invoke()` must be called by the destination - /// thread to invoke the target function. Always safe to call. - /// - /// If the destination thread invokes the function within `m_timeout`, the return - /// value is obtained from the destination thread function call. If `m_timeout` expires - /// before the destination thread starts the call, the target function is not invoked - /// and a default return value is returned. If the call has already started when - /// `m_timeout` expires, the caller waits for it to finish and gets its return value. - /// Use `IsSuccess()` to check for success before using the return value. Alternatively, - /// use `AsyncInvoke()` and check the `std::optional` return value. - /// - /// The `DelegateAsyncWaitMsg` does not duplicate and copy the function arguments into heap - /// memory. The source thread waits on the destintation thread to complete, therefore argument - /// data is shared between the source and destination threads and simultaneous access is prevented - /// using a mutex. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value, if any. Use `IsSuccess()` to determine if - /// the return value is valid before use. - virtual RetType operator()(Args... args) override { - // The result lives in locals, so concurrent callers sharing this instance - // (e.g. one Signal emitted from two threads) each get their own return value. - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == false) { - return success ? TakeRet(retVal) : RetType(); - } - } - - /// @brief Invoke delegate function asynchronously and block for function return value. - /// Called by the source thread. Always safe to call, including concurrently. - /// @param[in] args The function arguments, if any. - /// @return The bound function return value stored withing `std::optional`. Use - /// `has_value()` to check if the the return value is valid. `value()` contains - /// the target function return value. - auto AsyncInvoke(Args... args) { - std::optional retVal; - bool success = DispatchWait(retVal, std::forward(args)...); - SetLastResult(success, retVal); - - if constexpr (std::is_void::value == true) { - return success ? std::optional(true) : std::optional(); - } else { - return success ? std::optional(TakeRet(retVal)) : std::optional(); - } - } - - /// @brief Invoke the delegate function on the destination thread. Called by the - /// destination thread. - /// @details Each source thread call to `operator()` generate a call to `Invoke()` - /// on the destination thread. A lock is used to protect source and destination thread shared - /// data. A semaphore is used to signal the source thread when the destination thread - /// completes the target function call. - /// - /// If source thread timeout expires and before the destination thread invokes the - /// target function, the target function is not called. - /// @param[in] msg The delegate message created and sent within `operator()(Args... args)`. - /// @return `true` if target function invoked or timeout expired; `false` if error. - virtual bool Invoke(std::shared_ptr msg) override { - static_assert(!(is_unique_ptr::value), "std::unique_ptr return value not allowed"); - - // Typecast the base pointer to back correct derived to instance - auto delegateMsg = std::dynamic_pointer_cast>(msg); - if (delegateMsg == nullptr) - return false; - - // Protect data shared between source and destination threads - const dmq::LockGuard lock(delegateMsg->GetLock()); - - // Is the source thread waiting for the target function invoke to complete? - if (delegateMsg->GetInvokerWaiting()) { - // Signals the source thread when this scope exits, including via an exception - // propagating out of the target function invoke below. Without this, a target - // function that throws would leave the source thread blocked until timeout. - struct SemaSignalGuard { - Semaphore& sema; - ~SemaSignalGuard() { sema.Signal(); } - } semaSignalGuard{ delegateMsg->GetSema() }; - - // Does target function have a void return value? - if constexpr (std::is_void::value == true) { - // Call the target with the message's stored arguments: a qualified, non-virtual - // call, so there is no copy of the argument tuple and no virtual hop back through - // operator(). Each argument is forwarded as declared: by-value arguments are moved - // out of the message (each message is invoked exactly once), references bind to - // the stored copies. - std::apply([this](auto&... args) { this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs()); - } else { - // As above, and keep the return value (in this clone's typed slot). - m_retVal.emplace(std::apply( - [this](auto&... args) -> RetType { return this->BaseType::operator()(std::forward(args)...); }, - delegateMsg->GetArgs())); - } - - // Only reached if the std::apply() call above did not throw - delegateMsg->SetInvokeSucceeded(true); - } - return true; - } - - /// Returns `true` if the last asynchronous call on this delegate succeeded. - /// @return `true` if the target asynchronous function call succeeded. `false` if - /// the timeout expired before the target function could be invoked. - /// @note If several threads call this delegate concurrently, this reports whichever - /// call finished last. Use `AsyncInvoke()`'s return value to get each call's own result. - bool IsSuccess() noexcept { return m_state.IsSuccess(); } - - /// Get the asynchronous function return value of the last call on this delegate. - /// @return The destination thread target function return value - /// @note Same caveat as `IsSuccess()` for concurrent callers. - RetType GetRetVal() noexcept { - if constexpr (std::is_void::value == false) { - std::optional copy; - { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - copy = m_retVal; - } - return TakeRet(copy); - } - } - ///@brief Get the destination thread that the target function is invoked on. - // @return The target thread. - IThread* GetThread() noexcept { return m_state.GetThread(); } - - /// @brief Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const noexcept { return m_state.GetPriority(); } - void SetPriority(Priority priority) noexcept { m_state.SetPriority(priority); } - -private: - /// Return value storage type (std::optional can't hold void). - using RetStorage = std::conditional_t::value, bool, std::decay_t>; - - /// Dispatch to the destination thread and wait (up to the timeout) for the call. - /// @param[out] retVal The target function's return value, set when this returns `true`. - /// @return `true` if the target function was invoked and completed. - bool DispatchWait(std::optional& retVal, Args&&... args) { - if (this->Empty()) - return false; - - // Create a clone instance of this delegate. Erase to the non-templated - // IThreadInvoker interface BEFORE constructing the shared_ptr (rather than - // xmake_shared) so the shared_ptr control block is not templated - // on RetType/Args... -- one control-block type is then shared across every - // DelegateAsyncWait kind and signature instead of duplicated per signature. - // `rawClone` stays valid for the whole function (kept alive by `delegate`) - // and is used below to read back the clone's own result state. - ClassType* rawClone = this->Clone(); - if (!rawClone) - BAD_ALLOC(); - IThreadInvoker* invokerBase = rawClone; - std::shared_ptr delegate(invokerBase, std::default_delete(), dmq::stl_allocator()); - - bool success = detail::DispatchAsyncWait(delegate, m_state.GetThread(), m_state.GetPriority(), - m_state.GetTimeout(), std::forward(args)...); - if (success) { - // Invoke() (running as the clone, on the destination thread) wrote the - // target function's return value into the clone's own m_retVal. - retVal = std::move(rawClone->m_retVal); - } - return success; - } - - /// Move the value out of `v`, or return a default value if it holds none. - static RetType TakeRet(std::optional& v) noexcept { - if (v) return std::move(*v); -#if defined(DMQ_ASSERTS) - DMQ_ASSERT(); // no result stored (e.g. GetRetVal() before any successful call) -#endif - return RetType(); - } - - /// Record a call's result as this delegate's last result, for IsSuccess()/GetRetVal(). - void SetLastResult(bool success, const std::optional& retVal) { - const dmq::LockGuard lock(detail::AsyncWaitResultLock()); - m_state.SetSuccess(success); - m_retVal = retVal; - } - - /// Destination thread, message priority, timeout, and whether the last async call - /// succeeded. Not templated on Sig/TClass — see `detail::AsyncWaitDispatchState`. - detail::AsyncWaitDispatchState m_state; - - /// Return value, typed so a large return type needs no heap allocation (std::any - /// put anything over its small buffer on the global heap). On the per-call clone: - /// that call's result, written by Invoke() on the destination thread and read by - /// the caller after the message lock. On the caller's delegate: the last call's - /// result for GetRetVal(), guarded by detail::AsyncWaitResultLock(). - std::optional m_retVal; - - // -}; - -/// @brief Creates an asynchronous delegate that binds to a free function with a wait and timeout. -/// @tparam RetType The return type of the free function. -/// @tparam Args The types of the function arguments. -/// @param[in] func A pointer to the free function to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateFreeAsyncWait` object bound to the specified free function, thread, and timeout. -template -auto MakeDelegate(RetType(*func)(Args... args), IThread& thread, Duration timeout) { - return DelegateFreeAsyncWait(func, thread, timeout); -} - -/// @brief Creates an asynchronous delegate that binds to a non-const member function with a wait and timeout. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateMemberAsyncWait` object bound to the specified non-const member function, thread, and timeout. -template -auto MakeDelegate(TClass* object, RetType(TClass::*func)(Args... args), IThread& thread, Duration timeout) { - return DelegateMemberAsyncWait(object, func, thread, timeout); -} - -/// @brief Creates an asynchronous delegate that binds to a const member function with a wait and timeout. -/// @tparam TClass The class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateMemberAsyncWait` object bound to the specified const member function, thread, and timeout. -template -auto MakeDelegate(TClass* object, RetType(TClass::*func)(Args... args) const, IThread& thread, Duration timeout) { - return DelegateMemberAsyncWait(object, func, thread, timeout); -} - -/// @brief Creates a delegate that binds to a const member function. -/// @tparam TClass The const class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateMemberAsyncWait` object bound to the specified non-const member function. -template -auto MakeDelegate(const TClass* object, RetType(TClass::* func)(Args... args) const, IThread& thread, Duration timeout) { - return DelegateMemberAsyncWait(object, func, thread, timeout); -} - -/// @brief Creates an asynchronous delegate that binds to a non-const member function using a shared pointer, with a wait and timeout. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetVal The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateMemberAsyncWait` shared pointer bound to the specified non-const member function, thread, and timeout. -template -auto MakeDelegate(std::shared_ptr object, RetVal(TClass::* func)(Args... args), IThread& thread, Duration timeout) { - return DelegateMemberAsyncWaitSp(object, func, thread, timeout); -} - -/// @brief Creates an asynchronous delegate that binds to a const member function using a shared pointer, with a wait and timeout. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetVal The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateMemberAsyncWait` shared pointer bound to the specified const member function, thread, and timeout. -template -auto MakeDelegate(std::shared_ptr object, RetVal(TClass::* func)(Args... args) const, IThread& thread, Duration timeout) { - return DelegateMemberAsyncWaitSp(object, func, thread, timeout); -} - -/// @brief Creates an asynchronous delegate that binds to a `std::function` with a wait and timeout. -/// @tparam RetType The return type of the `std::function`. -/// @tparam Args The types of the function arguments. -/// @param[in] func The `std::function` to bind to the delegate. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateFunctionAsyncWait` object bound to the specified `std::function`, thread, and timeout. -template -auto MakeDelegate(std::function func, IThread& thread, Duration timeout) { - return DelegateFunctionAsyncWait(func, thread, timeout); -} - -/// @brief Creates an asynchronous delegate that binds to a raw lambda or functor with a wait and timeout. -/// @tparam F The lambda or functor type. -/// @param[in] func The lambda or functor to bind. -/// @param[in] thread The `IThread` on which the function will be invoked asynchronously. -/// @param[in] timeout The duration to wait for the function to complete before returning. -/// @return A `DelegateFunctionAsyncWait` object bound to the specified lambda or functor, thread, and timeout. -template ::value>> -auto MakeDelegate(F&& func, IThread& thread, Duration timeout) { - using Sig = typename trait::function_traits::operator())>::function_type; - return DelegateFunctionAsyncWait(std::forward(func), thread, timeout); -} - -} - -DMQ_OPTIMIZE_OFF - -#endif // DMQ_HAS_SEMAPHORE - -#endif diff --git a/DelegateMQ/delegate/DelegateMQConfig_Default.h b/DelegateMQ/delegate/DelegateMQConfig_Default.h deleted file mode 100644 index 2065094..0000000 --- a/DelegateMQ/delegate/DelegateMQConfig_Default.h +++ /dev/null @@ -1,194 +0,0 @@ -#ifndef _DELEGATEMQ_CONFIG_DEFAULT_H -#define _DELEGATEMQ_CONFIG_DEFAULT_H - -/// @file -/// @brief Default DelegateMQ library configuration. -/// -/// To override, define DMQ_USER_CONFIG as a path to your own config header: -/// -DDMQ_USER_CONFIG="path/to/DelegateMQConfig.h" -/// Your config only needs to define the values you want to change. -/// Unset values fall back to these defaults via DelegateMQConfig_Default.h. - -#ifndef DMQ_DEFAULT_DISPATCH_TIMEOUT - #define DMQ_DEFAULT_DISPATCH_TIMEOUT 2 // seconds -#endif - -#ifndef DMQ_THREAD_IDLE_INTERVAL - #define DMQ_THREAD_IDLE_INTERVAL 100 // milliseconds; default for Thread::SetIdleHandler() -#endif - -#ifndef DMQ_MAX_TIMER_EXPIRED - #define DMQ_MAX_TIMER_EXPIRED 16 -#endif - -#ifndef DMQ_SIGNAL_SBO_COUNT - #define DMQ_SIGNAL_SBO_COUNT 8 -#endif - -#ifndef DMQ_DEFAULT_QUEUE_SIZE - #define DMQ_DEFAULT_QUEUE_SIZE 20 -#endif - -// Stack size of each dmq::os::Thread on the RTOS ports, in each port's native unit. -#ifndef DMQ_FREERTOS_STACK_WORDS - #define DMQ_FREERTOS_STACK_WORDS 4096 // words; dynamic stacks (SetStackMem() overrides) -#endif -#ifndef DMQ_THREADX_STACK_BYTES - #define DMQ_THREADX_STACK_BYTES 2048 -#endif -#ifndef DMQ_ZEPHYR_STACK_BYTES - #define DMQ_ZEPHYR_STACK_BYTES 2048 -#endif -#ifndef DMQ_CMSIS_RTOS2_STACK_BYTES - #define DMQ_CMSIS_RTOS2_STACK_BYTES 2048 -#endif -#ifndef DMQ_NUTTX_STACK_BYTES - #define DMQ_NUTTX_STACK_BYTES 8192 -#endif - -// Default dmq::os::Thread priority on the RTOS ports whose default is a plain number -// (SetThreadPriority() overrides per thread). -#ifndef DMQ_THREADX_THREAD_PRIORITY - #define DMQ_THREADX_THREAD_PRIORITY 10 // 0 = highest -#endif -#ifndef DMQ_ZEPHYR_THREAD_PRIORITY - #define DMQ_ZEPHYR_THREAD_PRIORITY 5 // passed to K_PRIO_PREEMPT() -#endif -#ifndef DMQ_NUTTX_THREAD_PRIORITY - #define DMQ_NUTTX_THREAD_PRIORITY 100 // SCHED_FIFO -#endif - -// Fallback queue size (maxQueueSize == 0) for the desktop stdlib/Win32 Thread ports -// only. Unlike DMQ_DEFAULT_QUEUE_SIZE (sized for real RTOS RAM constraints), these -// ports back their queue with a plain std::deque, so maxQueueSize == 0 otherwise -// means genuinely unbounded growth if the destination thread is dead/stuck. This -// is a high-water-mark safety net, not a throughput limiter -- large enough to -// never interfere with normal desktop bursts, but bounded so a truly dead consumer -// hits a clear FullPolicy::FAULT instead of growing the heap without limit. -#ifndef DMQ_THREAD_DESKTOP_QUEUE_SIZE - #define DMQ_THREAD_DESKTOP_QUEUE_SIZE 1000 -#endif - -#ifndef DMQ_MAX_WATCHDOG_THREADS - #define DMQ_MAX_WATCHDOG_THREADS 16 -#endif - -// A watched thread's queue wait (and Qt's heartbeat timer) is its watchdog timeout -// divided by this, so an idle thread refreshes its heartbeat this many times per -// timeout. At least 2. -#ifndef DMQ_WATCHDOG_HEARTBEAT_DIVISOR - #define DMQ_WATCHDOG_HEARTBEAT_DIVISOR 4 -#endif - -// Max threads registered for dmq::ThisThread::GetCurrent() at once on RTOS ports -// (one per running dmq::os::Thread or custom IThread worker). Exceeding it faults. -#ifndef DMQ_MAX_CURRENT_THREADS - #define DMQ_MAX_CURRENT_THREADS 16 -#endif - -#ifndef DMQ_SEQ_HISTORY_SIZE - #define DMQ_SEQ_HISTORY_SIZE 8 -#endif - -// How long a received sequence number counts toward duplicate detection. A real -// duplicate (a retry after a lost ACK) arrives within the sender's retry window; -// older entries are ignored so a restarted peer's reused numbers aren't dropped. -#ifndef DMQ_SEQ_HISTORY_EXPIRY_MS - #define DMQ_SEQ_HISTORY_EXPIRY_MS ((DMQ_RETRY_MONITOR_MAX_RETRIES + 1) * DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC * 1000) -#endif - -// This node's ID, sent in every DmqHeader (1-255). 0 = unset: receivers then -// track duplicates by remote ID alone, which is only correct with one sender -// per topic. Can be changed at run time with DmqHeader::SetLocalNodeId(). -#ifndef DMQ_NODE_ID - #define DMQ_NODE_ID 0 -#endif - -#ifndef DMQ_MAX_PARTICIPANTS - #define DMQ_MAX_PARTICIPANTS 8 -#endif - -#ifndef DMQ_TRANSPORT_MONITOR_MAX_PENDING - #define DMQ_TRANSPORT_MONITOR_MAX_PENDING 100 -#endif - -// Embedded UDP transports (lwIP, netconn, Zephyr, NetX): datagram buffer size -// (header + payload), and receive timeouts. A PUB socket polls briefly for ACKs; -// a SUB socket waits longer, returning RECEIVE_NO_DATA so its thread can check -// for exit. -#ifndef DMQ_UDP_BUFFER_SIZE - #define DMQ_UDP_BUFFER_SIZE 1500 -#endif -#ifndef DMQ_UDP_PUB_RECV_TIMEOUT_MS - #define DMQ_UDP_PUB_RECV_TIMEOUT_MS 50 -#endif -#ifndef DMQ_UDP_SUB_RECV_TIMEOUT_MS - #define DMQ_UDP_SUB_RECV_TIMEOUT_MS 2000 -#endif - -// STM32 UART transport: RX ring buffer bytes, max payload per frame, blocking -// transmit timeout per frame, and the most it waits for the rest of a frame -// once its marker has arrived. -#ifndef DMQ_UART_RX_RING_SIZE - #define DMQ_UART_RX_RING_SIZE 1024 -#endif -#ifndef DMQ_UART_MAX_PAYLOAD - #define DMQ_UART_MAX_PAYLOAD 512 -#endif -#ifndef DMQ_UART_TX_TIMEOUT_MS - #define DMQ_UART_TX_TIMEOUT_MS 500 -#endif -#ifndef DMQ_UART_FRAME_TIMEOUT_MS - #define DMQ_UART_FRAME_TIMEOUT_MS 100 -#endif - -// Maximum number of distinct fixed-block allocator buckets (heap-blocks mode only). -// Each unique power-of-two allocation size gets one bucket. Most applications use -// 8-12 distinct sizes; raise this only if xallocator's ASSERT fires at runtime. -#ifndef DMQ_XALLOCATOR_MAX_ALLOCATORS - #define DMQ_XALLOCATOR_MAX_ALLOCATORS 15 -#endif - -// Default max remote peers per NetworkNode instance (fixed allocation). -// Override per-instantiation via NetworkNode's MaxPeers template parameter. -#ifndef DMQ_NETWORK_NODE_MAX_PEERS - #define DMQ_NETWORK_NODE_MAX_PEERS 4 -#endif - -// Default max in- or out-topics per NetworkNode instance (fixed allocation). -// Override per-instantiation via NetworkNode's MaxTopics template parameter. -#ifndef DMQ_NETWORK_NODE_MAX_TOPICS - #define DMQ_NETWORK_NODE_MAX_TOPICS 16 -#endif - -// Max messages drained per NetworkNode::ReceiverThread() tick (applies to both -// the incoming-message drain and the per-peer ACK drain). -#ifndef DMQ_NETWORK_NODE_MAX_WORK - #define DMQ_NETWORK_NODE_MAX_WORK 20 -#endif - -// Default number of retries before RetryMonitor gives up on an unacknowledged message. -#ifndef DMQ_RETRY_MONITOR_MAX_RETRIES - #define DMQ_RETRY_MONITOR_MAX_RETRIES 3 -#endif - -// Default per-message ACK timeout (seconds) for TransportMonitor. -#ifndef DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC - #define DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC 2 -#endif - -// serialize (msg_serialize.h, DMQ_SERIALIZE_SERIALIZE) limits. Longer strings or -// larger containers fail with STRING_TOO_LONG / CONTAINER_TOO_MANY, on write and -// on read. Both must be <= 65535 (16-bit length field on the wire). -#ifndef DMQ_SERIALIZE_MAX_STRING_SIZE - #define DMQ_SERIALIZE_MAX_STRING_SIZE 1024 -#endif -#ifndef DMQ_SERIALIZE_MAX_CONTAINER_SIZE - #define DMQ_SERIALIZE_MAX_CONTAINER_SIZE 64 -#endif -// Max depth of serialize::I objects nested inside each other (NESTING_TOO_DEEP beyond). -#ifndef DMQ_SERIALIZE_MAX_NESTING - #define DMQ_SERIALIZE_MAX_NESTING 5 -#endif - -#endif // _DELEGATEMQ_CONFIG_DEFAULT_H diff --git a/DelegateMQ/delegate/DelegateMQConfig_Template.h b/DelegateMQ/delegate/DelegateMQConfig_Template.h deleted file mode 100644 index 02c7c1c..0000000 --- a/DelegateMQ/delegate/DelegateMQConfig_Template.h +++ /dev/null @@ -1,151 +0,0 @@ -#ifndef _DELEGATEMQ_CONFIG_H -#define _DELEGATEMQ_CONFIG_H - -/// @file -/// @brief User configuration for the DelegateMQ library. -/// -/// Copy this file to your project as DelegateMQConfig.h. It is picked up -/// automatically when its directory is on the include path, or point the -/// compiler at it explicitly: -DDMQ_USER_CONFIG="DelegateMQConfig.h" -/// -/// Only define the values you want to change; any omitted values -/// fall back to the defaults in DelegateMQConfig_Default.h. - -// --- Port and option selection (builds without CMake) --- -// Without CMake, choose ports and options here instead of with -D flags. -// Anything left undefined is auto-selected (see delegate/DelegateSelect.h): -// stdlib threads, the built-in serializer and UDP on Windows/Linux, nothing -// on bare metal. With CMake, set DMQ_THREAD etc. in CMake instead and leave -// these commented out; defining a second port here is a compile error. -// -// #define DMQ_THREAD_FREERTOS // or DMQ_THREAD_STDLIB, _WIN32, _POSIX, _THREADX, -// // _ZEPHYR, _CMSIS_RTOS2, _NUTTX, _QT, _NONE -// #define DMQ_SERIALIZE_NONE // or DMQ_SERIALIZE_SERIALIZE, _MSGPACK, ... -// #define DMQ_TRANSPORT_NONE // or DMQ_TRANSPORT_STM32_UART, _ARM_LWIP_UDP, ... -// #define DMQ_ALLOCATOR // fixed-block allocator instead of the heap -// #define DMQ_ASSERTS // FaultHandler() instead of exceptions -// #define DMQ_DATABUS // DataBus on an RTOS (desktop default is on; -// #define DMQ_DATABUS_OFF // DMQ_DATABUS_OFF turns it off there) -// #define DMQ_CUSTOM_FAULT_HANDLER // application defines FaultHandler()/WatchdogHandler() -// // itself; port/fault/Fault.cpp compiles to nothing - -/// Timeout (seconds) used by the TIMEOUT queue-full policy on all threads. -#define DMQ_DEFAULT_DISPATCH_TIMEOUT 2 - -/// Default quiet time (milliseconds) before a Thread's idle handler runs, and -/// between calls while the queue stays empty. See Thread::SetIdleHandler(). -#define DMQ_THREAD_IDLE_INTERVAL 100 - -/// Max timers processed in one tick without heap allocation. -#define DMQ_MAX_TIMER_EXPIRED 16 - -/// Signal Small-Buffer Optimization count. -/// Signals with <= this many subscribers are invoked without heap allocation. -#define DMQ_SIGNAL_SBO_COUNT 8 - -/// Default internal message queue depth (maxQueueSize == 0) for the RTOS -/// dmq::os::Thread ports (FreeRTOS, Zephyr, ThreadX, CMSIS-RTOS2, NuttX), where -/// the backing queue primitive requires a fixed capacity at creation. -#define DMQ_DEFAULT_QUEUE_SIZE 20 - -/// Stack size of each dmq::os::Thread on the RTOS ports, in each port's native -/// unit. FreeRTOS counts words and applies to dynamically allocated stacks -/// (FreeRTOSThread::SetStackMem() supplies a static stack instead); the others -/// count bytes. -#define DMQ_FREERTOS_STACK_WORDS 4096 -#define DMQ_THREADX_STACK_BYTES 2048 -#define DMQ_ZEPHYR_STACK_BYTES 2048 -#define DMQ_CMSIS_RTOS2_STACK_BYTES 2048 -#define DMQ_NUTTX_STACK_BYTES 8192 - -/// Default dmq::os::Thread priority on the RTOS ports whose default is a plain -/// number. SetThreadPriority() overrides it per thread. ThreadX: 0 is highest. -/// Zephyr: passed to K_PRIO_PREEMPT(). NuttX: SCHED_FIFO priority. (FreeRTOS and -/// CMSIS-RTOS2 derive their defaults from configMAX_PRIORITIES / osPriorityNormal.) -#define DMQ_THREADX_THREAD_PRIORITY 10 -#define DMQ_ZEPHYR_THREAD_PRIORITY 5 -#define DMQ_NUTTX_THREAD_PRIORITY 100 - -/// Fallback queue size (maxQueueSize == 0) for the desktop stdlib/Win32 Thread -/// ports only. A high-water-mark safety net (not a throughput limiter) against -/// unbounded growth if the destination thread is dead/stuck -- large enough to -/// never interfere with normal desktop bursts. -#define DMQ_THREAD_DESKTOP_QUEUE_SIZE 1000 - -/// Max number of threads that can be registered with the watchdog. -#define DMQ_MAX_WATCHDOG_THREADS 16 - -/// A watched thread's queue wait (and Qt's heartbeat timer) is its watchdog -/// timeout divided by this: an idle thread refreshes its heartbeat this many -/// times per timeout. Higher is more margin, more wakeups. At least 2. -#define DMQ_WATCHDOG_HEARTBEAT_DIVISOR 4 - -/// Max threads registered for dmq::ThisThread::GetCurrent() at once on RTOS ports -/// (one per running dmq::os::Thread or custom IThread worker). Exceeding it faults. -/// Unused on desktop ports, which use thread_local storage. -#define DMQ_MAX_CURRENT_THREADS 16 - -/// Duplicate-detection ring buffer depth per remote Participant. -/// Larger values catch more out-of-order duplicates; reduce on RAM-constrained targets. -#define DMQ_SEQ_HISTORY_SIZE 8 - -/// How long (ms) a received sequence number counts toward duplicate detection. -/// Should cover the sender's whole retry window: (retries + 1) x ACK timeout. -/// Older entries are ignored so a restarted peer's reused numbers aren't dropped. -#define DMQ_SEQ_HISTORY_EXPIRY_MS ((DMQ_RETRY_MONITOR_MAX_RETRIES + 1) * DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC * 1000) - -/// This node's ID, sent in every message header (1-255). Give every node on a -/// network a unique ID when more than one node publishes the same topic. -/// 0 = unset (duplicates tracked by remote ID alone). Run-time override: -/// dmq::transport::DmqHeader::SetLocalNodeId(). -#define DMQ_NODE_ID 0 - -/// Max number of remote Participants the DataBus can hold without heap allocation. -#define DMQ_MAX_PARTICIPANTS 8 - -/// Default max remote peers per NetworkNode instance (fixed allocation). -/// Override per-instantiation via NetworkNode's MaxPeers template parameter. -#define DMQ_NETWORK_NODE_MAX_PEERS 4 - -/// Default max in- or out-topics per NetworkNode instance (fixed allocation). -/// Override per-instantiation via NetworkNode's MaxTopics template parameter. -#define DMQ_NETWORK_NODE_MAX_TOPICS 16 - -/// Max messages drained per NetworkNode::ReceiverThread() tick (incoming-message -/// drain and per-peer ACK drain). -#define DMQ_NETWORK_NODE_MAX_WORK 20 - -/// Default number of retries before RetryMonitor gives up on an unacknowledged message. -#define DMQ_RETRY_MONITOR_MAX_RETRIES 3 - -/// Default per-message ACK timeout (seconds) for TransportMonitor. -#define DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC 2 - -/// Embedded UDP transports (lwIP, netconn, Zephyr, NetX): datagram buffer size -/// (header + payload, keep within the link MTU), the PUB socket's ACK-poll -/// receive timeout, and the SUB socket's receive timeout (how often its thread -/// can check for exit). -#define DMQ_UDP_BUFFER_SIZE 1500 -#define DMQ_UDP_PUB_RECV_TIMEOUT_MS 50 -#define DMQ_UDP_SUB_RECV_TIMEOUT_MS 2000 - -/// STM32 UART transport: RX ring buffer bytes (absorbs bursts between reads), -/// max payload per frame (both ends must agree), blocking transmit timeout per -/// frame (raise for low baud rates or large payloads), and the most Receive() -/// waits for the rest of a frame once its marker has arrived. -#define DMQ_UART_RX_RING_SIZE 1024 -#define DMQ_UART_MAX_PAYLOAD 512 -#define DMQ_UART_TX_TIMEOUT_MS 500 -#define DMQ_UART_FRAME_TIMEOUT_MS 100 - -/// serialize (msg_serialize.h, DMQ_SERIALIZE_SERIALIZE): max string length and max -/// container element count, on write and on read. Both must be <= 65535 (16-bit -/// length field on the wire). Raising them also raises how much a received message -/// can make the receiver allocate. -#define DMQ_SERIALIZE_MAX_STRING_SIZE 1024 -#define DMQ_SERIALIZE_MAX_CONTAINER_SIZE 64 - -/// serialize: max depth of serialize::I objects nested inside each other. -#define DMQ_SERIALIZE_MAX_NESTING 5 - -#endif // _DELEGATEMQ_CONFIG_H diff --git a/DelegateMQ/delegate/DelegateMsg.h b/DelegateMQ/delegate/DelegateMsg.h deleted file mode 100644 index 95713c5..0000000 --- a/DelegateMQ/delegate/DelegateMsg.h +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef _DELEGATE_MSG_H -#define _DELEGATE_MSG_H - -/// @file -/// @brief Delegate inter-thread message base class. - -#include "IInvoker.h" -#include "DelegateOpt.h" -#include "make_tuple_heap.h" -#include -#include - -namespace dmq { - -// Async delegate message priority -// -// Contract every dmq::os::Thread port's queue implementation must uphold: -// a HIGH message is always dispatched ahead of any NORMAL message already -// waiting, but HIGH does NOT mean "jump to the very front" -- among multiple -// HIGH messages (or multiple NORMAL messages), FIFO order relative to each -// other must be preserved. I.e. per-priority-lane FIFO, not a LIFO stack. -// -// A single queue with a "send to front" primitive (FreeRTOS xQueueSendToFront, -// ThreadX tx_queue_front_send) gets this wrong: a second HIGH message sent to -// the front lands ahead of the first HIGH message, turning HIGH ordering into -// a stack. The correct shape -- used by every port -- is two lanes (one per -// priority) with new messages always pushed to the BACK of their lane, and -// the consumer draining the HIGH lane before the NORMAL lane: -// - StdlibThread / Win32Thread: two std::deque, one shared mutex+condition_variable. -// - ZephyrDelegateQueue: two k_msgq, drained via k_poll on both. -// - FreeRTOSDelegateQueue / ThreadXDelegateQueue / CmsisRtos2DelegateQueue: two native queues, woken by -// one shared counting semaphore "doorbell" (the RTOS-native stand-in for -// the stdlib condition_variable, since none of these queue APIs exposes one). -// CMSIS-RTOS2's osMessageQueuePut msg_prio is not used: implementations may -// ignore it (Zephyr's does). -enum class Priority -{ - NORMAL, - HIGH -}; - -/// @brief Base class for all delegate inter-thread messages -class DelegateMsg -{ -public: - /// Constructor - /// @param[in] invoker - the invoker instance the delegate is registered with. - DelegateMsg(std::shared_ptr invoker, Priority priority) : - m_invoker(invoker), m_priority(priority) - { - } - - virtual ~DelegateMsg() = default; - - /// Get the delegate invoker instance the delegate is registered with. - /// @return The invoker instance. - std::shared_ptr GetInvoker() const { return m_invoker; } - - /// Get the delegate message priority - /// @return Delegate message priority - Priority GetPriority() const { return m_priority; } - - /// @brief Called by a thread that discards this message without invoking it - /// (e.g. dmq::ExitPolicy::DISCARD). Releases a sender blocked waiting on the - /// invoke, which then sees the call as failed instead of waiting out its timeout. - /// No-op for messages nobody waits on. - virtual void Cancel() {} - -private: - /// The IThreadInvoker instance used to invoke the target function - /// on the destination thread of control - std::shared_ptr m_invoker; - - /// The delegate message priority - Priority m_priority = Priority::NORMAL; - - // Use fixed-block memory allocator if DMQ_ALLOCATOR set - XALLOCATOR -}; - -} - -#endif diff --git a/DelegateMQ/delegate/DelegateOpt.h b/DelegateMQ/delegate/DelegateOpt.h deleted file mode 100644 index b27475b..0000000 --- a/DelegateMQ/delegate/DelegateOpt.h +++ /dev/null @@ -1,672 +0,0 @@ -#ifndef _DELEGATE_OPT_H -#define _DELEGATE_OPT_H - -/// @file -/// @brief Delegate library options header file. - -// Option selection (user config, port auto-detection, derived DMQ_* macros) -// comes first so everything below sees the final options. -#include "DelegateSelect.h" - -#if defined(_WIN32) || defined(_WIN64) - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #endif - #ifndef NOMINMAX - #define NOMINMAX - #endif - - // If networking is active, include winsock2.h here to prevent macro - // redefinitions when windows.h is included later (e.g. by FreeRTOS or stdlib). - #if defined(DMQ_DATABUS) || defined(DMQ_TRANSPORT_ZEROMQ) || \ - defined(DMQ_TRANSPORT_WIN32_UDP) || defined(DMQ_TRANSPORT_WIN32_TCP) || \ - defined(DMQ_TRANSPORT_WIN32_PIPE) || defined(DMQ_TRANSPORT_NNG) || \ - defined(DMQ_TRANSPORT_MQTT) - #include - #include - #endif -#endif - -// Host BSD/Winsock socket headers for extras/util/NetworkConnect.h's desktop -// convenience helpers (RAII WSAStartup/WSACleanup, GetLocalAddress()). -// -// _WIN32/__linux__/__APPLE__/__unix__ reflect the compiler/host doing the -// building, not the actual target. A genuine embedded cross-compile (e.g. -// arm-none-eabi-gcc for stm32-freertos) never defines these host-platform -// macros in the first place, so this guard is only ever live for a target -// that is ALSO built with a host compiler -- i.e. a simulator/native sample. -// DMQ_THREAD_HAS_NATIVE_NETWORK_STACK (above) captures exactly which -// embedded RTOS ports bundle a colliding native network stack there and -// must be excluded; see its own comment for why FreeRTOS is deliberately -// not one of them. -#if !defined(DMQ_THREAD_HAS_NATIVE_NETWORK_STACK) - #define DMQ_NETWORK_CONNECT_DESKTOP_HOST_HEADERS - #ifdef _WIN32 - #include - #include - #pragma comment(lib, "ws2_32.lib") - #elif defined(__linux__) || defined(__APPLE__) || defined(__unix__) - #include - #include - #include - #include - #include - #include - #include - #include - #include - #endif -#endif - -#include -#if defined(DMQ_HAS_THREADING) - #include - #if !defined(__cpp_lib_scoped_lock) - // No std::scoped_lock on this toolchain; see dmq::ScopedLock below. - #include "port/os/common/PortableScopedLock.h" - #endif -#endif - -// RTTI Detection Check -#if !defined(__cpp_rtti) && !defined(__GXX_RTTI) && !defined(_CPPRTTI) - #error "RTTI compiler option is disabled but required by the DelegateMQ library." -#endif - -// Some OS port headers below (e.g. ThreadXMutex.h, ThreadXConditionVariable.h) use -// DMQ_ASSERT_TRUE in constructors. Include Fault.h here, ahead of those port headers, -// so the macro is defined before first use. Fault.h is include-guarded, so the -// later #include "extras/util/Fault.h" below is a harmless no-op. -#include "extras/util/Fault.h" - -#if defined(DMQ_THREAD_STDLIB) || defined(DMQ_THREAD_WIN32) || defined(DMQ_THREAD_QT) || defined(DMQ_THREAD_POSIX) - // Windows / Linux / macOS / Qt (Standard Library) / POSIX (raw pthreads, - // but Mutex/ConditionVariable/Clock/ThisThread still reuse std:: here -- - // see port/os/posix/PosixThread.h, the only file this port adds) - #include - #include - #include "port/os/stdlib/StdlibThisThread.h" -#elif defined(DMQ_THREAD_FREERTOS) - #include "port/os/freertos/FreeRTOSClock.h" - #include "port/os/freertos/FreeRTOSMutex.h" - #include "port/os/freertos/FreeRTOSConditionVariable.h" - #include "port/os/freertos/FreeRTOSCriticalSection.h" - #include "port/os/freertos/FreeRTOSThisThread.h" -#elif defined(DMQ_THREAD_THREADX) - #include "port/os/threadx/ThreadXClock.h" - #include "port/os/threadx/ThreadXMutex.h" - #include "port/os/threadx/ThreadXConditionVariable.h" - #include "port/os/threadx/ThreadXCriticalSection.h" - #include "port/os/threadx/ThreadXThisThread.h" -#elif defined(DMQ_THREAD_ZEPHYR) - #include "port/os/zephyr/ZephyrClock.h" - #include "port/os/zephyr/ZephyrMutex.h" - #include "port/os/zephyr/ZephyrCriticalSection.h" - #include "port/os/zephyr/ZephyrSemaphore.h" - #include "port/os/zephyr/ZephyrThisThread.h" -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - #include "port/os/cmsis-rtos2/CmsisRtos2Clock.h" - #include "port/os/cmsis-rtos2/CmsisRtos2Mutex.h" - #include "port/os/cmsis-rtos2/CmsisRtos2CriticalSection.h" - #include "port/os/cmsis-rtos2/CmsisRtos2Semaphore.h" - #include "port/os/cmsis-rtos2/CmsisRtos2ThisThread.h" -#elif defined(DMQ_THREAD_NUTTX) - #include "port/os/nuttx/NuttXClock.h" - #include "port/os/nuttx/NuttXMutex.h" - #include "port/os/nuttx/NuttXCriticalSection.h" - #include "port/os/nuttx/NuttXSemaphore.h" - #include "port/os/nuttx/NuttXThisThread.h" -#elif defined(DMQ_THREAD_NONE) - #include "port/os/bare-metal/BareMetalClock.h" - #include "port/os/bare-metal/BareMetalCriticalSection.h" - #include "port/os/bare-metal/BareMetalThisThread.h" -#else - #include "port/os/bare-metal/BareMetalClock.h" - #include "port/os/bare-metal/BareMetalCriticalSection.h" - #include "port/os/bare-metal/BareMetalThisThread.h" -#endif - -namespace dmq -{ - // --- PORTABLE LOCK GUARD --- - // Does not require . Works with any BasicLockable type (lock/unlock). - template - class PortableLockGuard { - T& m_mutex; - public: - explicit PortableLockGuard(T& m) noexcept : m_mutex(m) { m_mutex.lock(); } - ~PortableLockGuard() noexcept { m_mutex.unlock(); } - PortableLockGuard(const PortableLockGuard&) = delete; - PortableLockGuard& operator=(const PortableLockGuard&) = delete; - }; - - // --- PORTABLE SCOPED LOCK --- - // std::scoped_lock on threaded ports (desktop + RTOS); all RTOS mutex types - // satisfy BasicLockable (lock/unlock), so it works with them directly. Some - // bare-metal standard libraries lack std::scoped_lock without thread support - // (e.g. Arm GNU Toolchain 14); those get dmq::os::PortableScopedLock - // (port/os/common/PortableScopedLock.h). No-op for DMQ_THREAD_NONE and for - // any bare-metal build with no thread model. -#if defined(DMQ_HAS_THREADING) && defined(__cpp_lib_scoped_lock) - template - using ScopedLock = std::scoped_lock; -#elif defined(DMQ_HAS_THREADING) - template - using ScopedLock = dmq::os::PortableScopedLock; -#else - // No-op: DMQ_THREAD_NONE or no thread model defined (bare-metal, single-threaded) - template - class ScopedLock { - public: - explicit ScopedLock(M&...) noexcept {} - ~ScopedLock() noexcept = default; - ScopedLock(const ScopedLock&) = delete; - ScopedLock& operator=(const ScopedLock&) = delete; - }; -#endif - - // @TODO: Change aliases to switch clock type globally if necessary - - // --- CLOCK SELECTION --- -#if defined(DMQ_THREAD_STDLIB) || defined(DMQ_THREAD_WIN32) || defined(DMQ_THREAD_QT) || defined(DMQ_THREAD_POSIX) - // Windows / Linux / macOS / Qt / POSIX - using Clock = std::chrono::steady_clock; - -#elif defined(DMQ_THREAD_FREERTOS) - // Use the custom FreeRTOS wrapper - using Clock = dmq::os::FreeRTOSClock; - -#elif defined(DMQ_THREAD_THREADX) - // Use the custom ThreadX wrapper - using Clock = dmq::os::ThreadXClock; - -#elif defined(DMQ_THREAD_ZEPHYR) - // Use the custom Zephyr wrapper - using Clock = dmq::os::ZephyrClock; - -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - using Clock = dmq::os::CmsisRtos2Clock; - -#elif defined(DMQ_THREAD_NUTTX) - // Use the custom NuttX wrapper - using Clock = dmq::os::NuttXClock; - -#else - // Assuming implemented the 'g_ticks' variable - using Clock = dmq::os::BareMetalClock; -#endif - - // --- GENERIC TYPES --- - // Automatically adapt to the underlying Clock's traits - using Duration = typename Clock::duration; - using TimePoint = typename Clock::time_point; - - // --- THIS_THREAD (sleep_for / yield / GetCurrent) SELECTION --- - // Portable equivalents of std::this_thread::sleep_for()/yield() for the - // calling thread, plus GetCurrent(): the dmq::IThread whose worker is the - // calling thread, or nullptr (registered by dmq::CurrentThreadScope in - // IThread.h). Exists so library internals that need to delay or yield - // (e.g. RetryMonitor backoff) aren't forced to pull in a full - // dmq::os::Thread -- which also drags in the message queue, watchdog, and - // stats machinery -- just to sleep. Each dmq::os::Thread::Sleep() forwards - // here too, so every port's native delay call is implemented exactly once. - // Each port implements it in port/os//ThisThread.h. - // - // A class (not a "this_thread" namespace) deliberately: sample/app code - // throughout this project does `using namespace dmq; ... using namespace - // std;` together, and a same-named nested namespace would make unqualified - // this_thread::sleep_for() calls in that code ambiguous against - // std::this_thread. -#if defined(DMQ_THREAD_STDLIB) || defined(DMQ_THREAD_WIN32) || defined(DMQ_THREAD_QT) || defined(DMQ_THREAD_POSIX) - using ThisThread = dmq::os::StdlibThisThread; -#elif defined(DMQ_THREAD_FREERTOS) - using ThisThread = dmq::os::FreeRTOSThisThread; -#elif defined(DMQ_THREAD_THREADX) - using ThisThread = dmq::os::ThreadXThisThread; -#elif defined(DMQ_THREAD_ZEPHYR) - using ThisThread = dmq::os::ZephyrThisThread; -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - using ThisThread = dmq::os::CmsisRtos2ThisThread; -#elif defined(DMQ_THREAD_NUTTX) - using ThisThread = dmq::os::NuttXThisThread; -#else - // Bare metal (DMQ_THREAD_NONE, or no thread model defined): sleep_for() - // busy-waits against BareMetalClock; yield() is a no-op. - using ThisThread = dmq::os::BareMetalThisThread; -#endif - - /// @brief Policy applied when a dmq::os::Thread port's message queue is full. - /// @details Always enforced -- a constructor's maxQueueSize == 0 is a sentinel meaning - /// "use this port's default capacity" (dmq::DEFAULT_QUEUE_SIZE for the RTOS ports, - /// dmq::THREAD_DESKTOP_QUEUE_SIZE for stdlib/Win32), not "disable the cap." Every port's - /// effective queue capacity is therefore always > 0 at runtime. - /// - DROP: DispatchDelegate() silently discards the message and returns immediately. - /// - FAULT: DispatchDelegate() triggers a system fault if the queue is full. - /// - TIMEOUT: DispatchDelegate() waits up to dispatchTimeout, then logs and drops. - /// - /// Use DROP for high-rate best-effort topics (sensor telemetry, display updates) where - /// a stale sample is preferable to stalling the publisher. Use TIMEOUT for critical topics - /// (commands, state transitions) where every message should be delivered if possible. - /// FAULT is the default. Every dmq::os::Thread port aliases this single definition as - /// dmq::os::FullPolicy so existing port-qualified references keep working. - enum class FullPolicy { DROP, FAULT, TIMEOUT }; - - /// @brief What a dmq::os::Thread does with messages still queued when ExitThread() is called. - /// - DRAIN: Invoke every message queued before ExitThread(), then exit (default). - /// - DISCARD: Invoke only the message already running, then exit. Queued messages are - /// discarded without being invoked; a sender blocked on one (an async-wait - /// delegate) is released and sees the call fail (DelegateMsg::Cancel()). - /// - /// Use DISCARD for fast shutdown when pending work is disposable (telemetry, UI refresh). - /// A thread that exits itself (ExitThread() called from its own message handler) always - /// discards, since the thread's owner may already be destroyed. - enum class ExitPolicy { DRAIN, DISCARD }; - - /// @brief Default timeout for the TIMEOUT queue-full policy across all Thread ports. - /// Override via DMQ_DEFAULT_DISPATCH_TIMEOUT in DelegateMQConfig.h. - inline constexpr std::chrono::seconds DEFAULT_DISPATCH_TIMEOUT{DMQ_DEFAULT_DISPATCH_TIMEOUT}; - - /// @brief Default quiet time before a Thread's idle handler runs, and between - /// calls while its queue stays empty. See Thread::SetIdleHandler(). - /// Override via DMQ_THREAD_IDLE_INTERVAL in DelegateMQConfig.h. - inline constexpr std::chrono::milliseconds THREAD_IDLE_INTERVAL{DMQ_THREAD_IDLE_INTERVAL}; - static_assert(DMQ_THREAD_IDLE_INTERVAL > 0, "DMQ_THREAD_IDLE_INTERVAL must be greater than zero"); - - // --- RESOURCE LIMITS & SBO CONFIGURATION --- - - /// @brief Max timers processed in one tick without heap allocation. - /// Override via DMQ_MAX_TIMER_EXPIRED in delegatemqconfig.h. - inline constexpr size_t MAX_TIMER_EXPIRED = DMQ_MAX_TIMER_EXPIRED; - - /// @brief Signal Small-Buffer Optimization (SBO) count. - /// Signals with <= this many subscribers are invoked heap-free. - /// Override via DMQ_SIGNAL_SBO_COUNT in delegatemqconfig.h. - inline constexpr size_t SIGNAL_SBO_COUNT = DMQ_SIGNAL_SBO_COUNT; - - /// @brief Default internal queue size (maxQueueSize == 0) for the RTOS - /// dmq::os::Thread ports, where the backing queue primitive requires a - /// fixed capacity at creation. - /// Override via DMQ_DEFAULT_QUEUE_SIZE in delegatemqconfig.h. - inline constexpr size_t DEFAULT_QUEUE_SIZE = DMQ_DEFAULT_QUEUE_SIZE; - - /// @brief Stack size of each dmq::os::Thread on the RTOS ports, in each - /// port's native unit (FreeRTOS: words, for dynamically allocated stacks; - /// the others: bytes). - /// Override via DMQ_FREERTOS_STACK_WORDS, DMQ_THREADX_STACK_BYTES, - /// DMQ_ZEPHYR_STACK_BYTES, DMQ_CMSIS_RTOS2_STACK_BYTES and - /// DMQ_NUTTX_STACK_BYTES in delegatemqconfig.h. - inline constexpr uint32_t FREERTOS_STACK_WORDS = DMQ_FREERTOS_STACK_WORDS; - inline constexpr size_t THREADX_STACK_BYTES = DMQ_THREADX_STACK_BYTES; - inline constexpr size_t ZEPHYR_STACK_BYTES = DMQ_ZEPHYR_STACK_BYTES; - inline constexpr size_t CMSIS_RTOS2_STACK_BYTES = DMQ_CMSIS_RTOS2_STACK_BYTES; - inline constexpr size_t NUTTX_STACK_BYTES = DMQ_NUTTX_STACK_BYTES; - - /// @brief Default dmq::os::Thread priority on the ThreadX, Zephyr (passed to - /// K_PRIO_PREEMPT()) and NuttX (SCHED_FIFO) ports. SetThreadPriority() - /// overrides it per thread. - /// Override via DMQ_THREADX_THREAD_PRIORITY, DMQ_ZEPHYR_THREAD_PRIORITY and - /// DMQ_NUTTX_THREAD_PRIORITY in delegatemqconfig.h. - inline constexpr int THREADX_THREAD_PRIORITY = DMQ_THREADX_THREAD_PRIORITY; - inline constexpr int ZEPHYR_THREAD_PRIORITY = DMQ_ZEPHYR_THREAD_PRIORITY; - inline constexpr int NUTTX_THREAD_PRIORITY = DMQ_NUTTX_THREAD_PRIORITY; - - /// @brief Fallback queue size (maxQueueSize == 0) for the desktop - /// stdlib/Win32 Thread ports only, which back their queue with a plain - /// std::deque and would otherwise grow without bound if the destination - /// thread is dead/stuck. A high-water-mark safety net, not a throughput - /// limiter -- large enough to never interfere with normal desktop bursts. - /// Override via DMQ_THREAD_DESKTOP_QUEUE_SIZE in delegatemqconfig.h. - inline constexpr size_t THREAD_DESKTOP_QUEUE_SIZE = DMQ_THREAD_DESKTOP_QUEUE_SIZE; - - /// @brief Max number of threads that can be monitored by the watchdog. - /// Override via DMQ_MAX_WATCHDOG_THREADS in delegatemqconfig.h. - inline constexpr size_t MAX_WATCHDOG_THREADS = DMQ_MAX_WATCHDOG_THREADS; - - /// @brief A watched thread's queue wait (and Qt's heartbeat timer) is its - /// watchdog timeout divided by this. - /// Override via DMQ_WATCHDOG_HEARTBEAT_DIVISOR in delegatemqconfig.h. - inline constexpr int WATCHDOG_HEARTBEAT_DIVISOR = DMQ_WATCHDOG_HEARTBEAT_DIVISOR; - static_assert(WATCHDOG_HEARTBEAT_DIVISOR >= 2, "DMQ_WATCHDOG_HEARTBEAT_DIVISOR must be at least 2"); - - /// @brief Max threads registered for ThisThread::GetCurrent() at once on RTOS - /// ports (see port/os/common/CurrentThreadStorage.h). Exceeding it faults. - /// Override via DMQ_MAX_CURRENT_THREADS in delegatemqconfig.h. - inline constexpr size_t MAX_CURRENT_THREADS = DMQ_MAX_CURRENT_THREADS; - - /// @brief Max number of remote Participants the DataBus can hold without heap allocation. - /// Override via DMQ_MAX_PARTICIPANTS in delegatemqconfig.h. - inline constexpr size_t MAX_PARTICIPANTS = DMQ_MAX_PARTICIPANTS; - - /// @brief serialize (msg_serialize.h) limits: max string length, max container - /// element count and max nesting depth of serialize::I objects. - /// Override via DMQ_SERIALIZE_MAX_STRING_SIZE, DMQ_SERIALIZE_MAX_CONTAINER_SIZE - /// and DMQ_SERIALIZE_MAX_NESTING in delegatemqconfig.h. - inline constexpr uint16_t SERIALIZE_MAX_STRING_SIZE = DMQ_SERIALIZE_MAX_STRING_SIZE; - inline constexpr uint16_t SERIALIZE_MAX_CONTAINER_SIZE = DMQ_SERIALIZE_MAX_CONTAINER_SIZE; - inline constexpr size_t SERIALIZE_MAX_NESTING = DMQ_SERIALIZE_MAX_NESTING; - static_assert(DMQ_SERIALIZE_MAX_STRING_SIZE <= 65535 && DMQ_SERIALIZE_MAX_CONTAINER_SIZE <= 65535, - "serialize length fields are 16 bits"); - static_assert(DMQ_SERIALIZE_MAX_NESTING >= 1, "DMQ_SERIALIZE_MAX_NESTING must be at least 1"); - - /// @brief Default max remote peers per NetworkNode instance (fixed allocation). - /// Override via DMQ_NETWORK_NODE_MAX_PEERS in delegatemqconfig.h, or per-instantiation - /// via NetworkNode's MaxPeers template parameter. - inline constexpr size_t NETWORK_NODE_MAX_PEERS = DMQ_NETWORK_NODE_MAX_PEERS; - - /// @brief Default max in- or out-topics per NetworkNode instance (fixed allocation). - /// Override via DMQ_NETWORK_NODE_MAX_TOPICS in delegatemqconfig.h, or per-instantiation - /// via NetworkNode's MaxTopics template parameter. - inline constexpr size_t NETWORK_NODE_MAX_TOPICS = DMQ_NETWORK_NODE_MAX_TOPICS; - - /// @brief Max messages drained per NetworkNode::ReceiverThread() tick. - /// Override via DMQ_NETWORK_NODE_MAX_WORK in delegatemqconfig.h. - inline constexpr int NETWORK_NODE_MAX_WORK = DMQ_NETWORK_NODE_MAX_WORK; - - /// @brief Default number of retries before RetryMonitor gives up on an unacknowledged message. - /// Override via DMQ_RETRY_MONITOR_MAX_RETRIES in delegatemqconfig.h, or per-call via - /// RetryMonitor's maxRetries constructor/Init() parameter. - inline constexpr int RETRY_MONITOR_MAX_RETRIES = DMQ_RETRY_MONITOR_MAX_RETRIES; - - /// @brief Default per-message ACK timeout for TransportMonitor. - /// Override via DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC in delegatemqconfig.h, or per-instance - /// via TransportMonitor's timeout constructor parameter. - inline constexpr Duration TRANSPORT_MONITOR_TIMEOUT = std::chrono::seconds(DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC); - - /// @brief How long a received sequence number counts toward duplicate detection. - /// Override via DMQ_SEQ_HISTORY_EXPIRY_MS in delegatemqconfig.h. - inline constexpr Duration SEQ_HISTORY_EXPIRY = std::chrono::milliseconds(DMQ_SEQ_HISTORY_EXPIRY_MS); - - /// @brief Default node ID sent in every DmqHeader (0 = unset). - /// Override via DMQ_NODE_ID in delegatemqconfig.h. - static_assert(DMQ_NODE_ID >= 0 && DMQ_NODE_ID <= 255, "DMQ_NODE_ID must be 0-255"); - inline constexpr uint8_t NODE_ID = DMQ_NODE_ID; - - /// @brief Max number of pending messages the TransportMonitor can track. - /// Override via DMQ_TRANSPORT_MONITOR_MAX_PENDING in delegatemqconfig.h. - inline constexpr size_t MAX_TRANSPORT_MONITOR_PENDING = DMQ_TRANSPORT_MONITOR_MAX_PENDING; - - /// @brief Embedded UDP transports: datagram buffer size and receive timeouts. - /// Override via DMQ_UDP_BUFFER_SIZE / DMQ_UDP_PUB_RECV_TIMEOUT_MS / - /// DMQ_UDP_SUB_RECV_TIMEOUT_MS in delegatemqconfig.h. - inline constexpr size_t UDP_BUFFER_SIZE = DMQ_UDP_BUFFER_SIZE; - inline constexpr std::chrono::milliseconds UDP_PUB_RECV_TIMEOUT{ DMQ_UDP_PUB_RECV_TIMEOUT_MS }; - inline constexpr std::chrono::milliseconds UDP_SUB_RECV_TIMEOUT{ DMQ_UDP_SUB_RECV_TIMEOUT_MS }; - - /// @brief STM32 UART transport sizes and timeouts. - /// Override via DMQ_UART_RX_RING_SIZE / DMQ_UART_MAX_PAYLOAD / - /// DMQ_UART_TX_TIMEOUT_MS / DMQ_UART_FRAME_TIMEOUT_MS in delegatemqconfig.h. - inline constexpr size_t UART_RX_RING_SIZE = DMQ_UART_RX_RING_SIZE; - inline constexpr size_t UART_MAX_PAYLOAD = DMQ_UART_MAX_PAYLOAD; - inline constexpr std::chrono::milliseconds UART_TX_TIMEOUT{ DMQ_UART_TX_TIMEOUT_MS }; - inline constexpr std::chrono::milliseconds UART_FRAME_TIMEOUT{ DMQ_UART_FRAME_TIMEOUT_MS }; - - // --- MUTEX / LOCK SELECTION --- -#if defined(DMQ_THREAD_STDLIB) || defined(DMQ_THREAD_WIN32) || defined(DMQ_THREAD_QT) || defined(DMQ_THREAD_POSIX) - // Windows / Linux / macOS / Qt / POSIX - using Mutex = std::mutex; - using RecursiveMutex = std::recursive_mutex; - // No ISR concept reachable from userspace on desktop OSes, and - // Timer::ProcessTimers() is always driven from an ordinary thread here - // in practice -- CriticalSection is just RecursiveMutex. See - // ThreadXCriticalSection.h for what a "real" ISR-safe implementation - // looks like on a port where it matters. - using CriticalSection = RecursiveMutex; - using ConditionVariable = std::condition_variable; - template using LockGuard = std::lock_guard; - template using UniqueLock = std::unique_lock; - #define DMQ_HAS_CV - #define DMQ_HAS_SEMAPHORE // generic dmq::Semaphore (delegate/Semaphore.h) needs a real ConditionVariable - -#elif defined(DMQ_THREAD_FREERTOS) - // Use the custom FreeRTOS wrapper - using Mutex = dmq::os::FreeRTOSMutex; - using RecursiveMutex = dmq::os::FreeRTOSRecursiveMutex; - // ISR-safe on real ARM Cortex-M FreeRTOS ports (auto-detects context via - // xPortIsInsideInterrupt() and selects taskENTER_CRITICAL[_FROM_ISR] - // accordingly); on the desktop simulator ports (POSIX/Win32) it is - // task-context-only, since there is no real hardware interrupt to - // detect there. See FreeRTOSCriticalSection.h for the detection details - // and the __arm__/__ARM_ARCH scoping assumption. - using CriticalSection = dmq::os::FreeRTOSCriticalSection; - using ConditionVariable = dmq::os::FreeRTOSConditionVariable; - template using LockGuard = PortableLockGuard; - template using UniqueLock = std::unique_lock; - #define DMQ_HAS_CV - #define DMQ_HAS_SEMAPHORE // generic dmq::Semaphore (delegate/Semaphore.h) needs a real ConditionVariable - -#elif defined(DMQ_THREAD_THREADX) - // Use the custom ThreadX wrapper - using Mutex = dmq::os::ThreadXMutex; - using RecursiveMutex = dmq::os::ThreadXRecursiveMutex; - // Genuinely ISR-safe (interrupt masking, not a TX_MUTEX) -- see - // ThreadXCriticalSection.h for why a real OS mutex can never be made - // to work here, and for the narrow-use-only warnings that apply to it. - using CriticalSection = dmq::os::ThreadXCriticalSection; - using ConditionVariable = dmq::os::ThreadXConditionVariable; - template using LockGuard = PortableLockGuard; - template using UniqueLock = std::unique_lock; - #define DMQ_HAS_CV - #define DMQ_HAS_SEMAPHORE // generic dmq::Semaphore (delegate/Semaphore.h) needs a real ConditionVariable - -#elif defined(DMQ_THREAD_ZEPHYR) - // Use the custom Zephyr wrapper - using Mutex = dmq::os::ZephyrMutex; - using RecursiveMutex = dmq::os::ZephyrRecursiveMutex; - // ISR-safe (irq_lock()/irq_unlock(key), not a k_mutex) -- see - // ZephyrCriticalSection.h. - using CriticalSection = dmq::os::ZephyrCriticalSection; - // No dmq::ConditionVariable port for Zephyr (no DMQ_HAS_CV), but - // dmq::Semaphore is available via Zephyr's own native k_sem instead of - // the generic condvar+mutex implementation -- see ZephyrSemaphore.h and - // delegate/Semaphore.h. This is what makes DelegateAsyncWait available - // here. - using Semaphore = dmq::os::ZephyrSemaphore; - #define DMQ_HAS_SEMAPHORE - template using LockGuard = PortableLockGuard; - -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - using Mutex = dmq::os::CmsisRtos2Mutex; - using RecursiveMutex = dmq::os::CmsisRtos2RecursiveMutex; - // ISR-safe (__disable_irq()/__enable_irq() via CMSIS-Core, bypassing - // osMutex entirely) -- see CmsisRtos2CriticalSection.h. UNVERIFIED: no - // CMSIS-RTOS2 SDK or Cortex-M hardware/QEMU target is available in this - // development environment to build and run it; review before relying - // on it in production. - using CriticalSection = dmq::os::CmsisRtos2CriticalSection; - // No dmq::ConditionVariable port for CMSIS-RTOS2 (no DMQ_HAS_CV, and no - // native condvar primitive to build one from), but dmq::Semaphore is - // available via osSemaphore directly instead -- see - // CmsisRtos2Semaphore.h and delegate/Semaphore.h. This is what makes - // DelegateAsyncWait available here. - using Semaphore = dmq::os::CmsisRtos2Semaphore; - #define DMQ_HAS_SEMAPHORE - template using LockGuard = PortableLockGuard; - -#elif defined(DMQ_THREAD_NUTTX) - // Use the custom NuttX wrapper (NuttX implements real POSIX - // pthread_mutex_t, unlike the bespoke kernel-object wrappers the other - // RTOS ports need). - using Mutex = dmq::os::NuttXMutex; - using RecursiveMutex = dmq::os::NuttXRecursiveMutex; - // ISR-safe (up_irq_save()/up_irq_restore(), NuttX's own architecture- - // portable interrupt-masking primitive, not a pthread_mutex_t) -- see - // NuttXCriticalSection.h, including its FLAT-vs-PROTECTED/KERNEL-build - // caveat. - using CriticalSection = dmq::os::NuttXCriticalSection; - // No dmq::ConditionVariable port for NuttX (no DMQ_HAS_CV) -- not - // because NuttX lacks pthread_cond_t (it has a real one), but because - // dmq::Semaphore is available via NuttX's own native sem_t instead of - // the generic condvar+mutex implementation -- see NuttXSemaphore.h and - // delegate/Semaphore.h. This is what makes DelegateAsyncWait available - // here. - using Semaphore = dmq::os::NuttXSemaphore; - #define DMQ_HAS_SEMAPHORE - template using LockGuard = PortableLockGuard; - -#else - // Bare metal has no threads, so no locking is required. - // NullMutex satisfies BasicLockable; PortableLockGuard compiles to nothing meaningful. - struct NullMutex { - void lock() {} - void unlock() {} - }; - using Mutex = NullMutex; - using RecursiveMutex = NullMutex; - // Unlike Mutex/RecursiveMutex above, NullMutex would NOT be correct here: - // bare metal still has real hardware ISRs that can preempt the main - // loop, even with no RTOS/threads. dmq::os::BareMetalCriticalSection - // does real interrupt masking (save/disable/restore PRIMASK), the same - // technique BareMetalClock.h already uses. - using CriticalSection = dmq::os::BareMetalCriticalSection; - template using LockGuard = PortableLockGuard; - // No DMQ_HAS_SEMAPHORE — no RTOS means no native semaphore primitive to - // build one from either; Semaphore and DelegateAsyncWait are unavailable - // on bare metal. -#endif -} - -// Detect if exceptions are disabled at the compiler level -#if !defined(__cpp_exceptions) - #ifndef DMQ_ASSERTS - #define DMQ_ASSERTS // Force asserts if exceptions are off - #endif -#endif - -// @TODO: Select the desired software fault handling (see Port.cmake). -#ifdef DMQ_ASSERTS - #include "extras/util/Fault.h" - // Use assert error handling. Change assert to a different error - // handler as required by the target application. - #define BAD_ALLOC() DMQ_ASSERT() -#else - #include "extras/util/Fault.h" - #include - // Use exception error handling - #define BAD_ALLOC() throw std::bad_alloc() -#endif - -// @TODO: Select the desired heap allocation (see Port.cmake). -// If DMQ_ASSERTS defined above, consider defining DMQ_ALLOCATOR to prevent -// std::list usage within delegate library from throwing a std::bad_alloc -// exception. The std_allocator calls assert if out of memory. -// See master CMakeLists.txt for info on enabling the fixed-block allocator. -#ifdef DMQ_ALLOCATOR - // Use stl_allocator fixed-block allocator for dynamic storage allocation - #include "extras/allocator/xstring.h" - #include "extras/allocator/xlist.h" - #include "extras/allocator/xmap.h" - #include "extras/allocator/xset.h" - #include "extras/allocator/xqueue.h" - #include "extras/allocator/xsstream.h" - #include "extras/allocator/stl_allocator.h" - #include "extras/allocator/xnew.h" - #include "extras/allocator/xmake_shared.h" -#else - #include - #include - #include - #include - #include - #include - #include - #include - #include - - // Not using xallocator; define as nothing - #undef XALLOCATOR - #define XALLOCATOR - - namespace dmq { - // Use default std::allocator for dynamic storage allocation - template - using stl_allocator = std::allocator; - - // An alias, like xmap/xset here and xlist under DMQ_ALLOCATOR, so code - // overloaded on std::list (e.g. msg_serialize.h) accepts it in both builds. - template > - using xlist = std::list; - - // stl_allocator is std::allocator here, so these are the standard types - typedef std::ostringstream xostringstream; - typedef std::stringstream xstringstream; - - typedef std::string xstring; - - // Fallback xmake_shared — uses std::make_shared when fixed-block allocator is disabled - template - inline std::shared_ptr xmake_shared(Args&&... args) - { - return std::make_shared(std::forward(args)...); - } - - // Fallback xnew/xdelete — use standard new/delete when fixed-block allocator is disabled - template - inline T* xnew(Args&&... args) { - return new(std::nothrow) T(std::forward(args)...); - } - - template - inline void xdelete(T* p) { - delete p; - } - - // Fallback xmap/xmultimap — use std::map when fixed-block allocator is disabled - template >> - using xmap = std::map, Alloc>; - - template >> - using xmultimap = std::multimap, Alloc>; - - // Fallback xset/xmultiset — use std::set when fixed-block allocator is disabled - template , typename Alloc = stl_allocator> - using xset = std::set; - - template , typename Alloc = stl_allocator> - using xmultiset = std::multiset; - - // Fallback xqueue — use std::queue when fixed-block allocator is disabled - template >> - using xqueue = std::queue; - } -#endif - -// @TODO: Select the desired logging (see Port.cmake). -#ifdef DMQ_LOG - #include - #define LOG_INFO(...) spdlog::info(__VA_ARGS__) - #define LOG_DEBUG(...) spdlog::debug(__VA_ARGS__) - #define LOG_ERROR(...) spdlog::error(__VA_ARGS__) -#else - // No-op macros when logging disabled - #define LOG_INFO(...) do {} while(0) - #define LOG_DEBUG(...) do {} while(0) - #define LOG_ERROR(...) do {} while(0) -#endif - -// @TODO: Select the desired template optimization level. -// Enable DMQ_FORCE_OPTIMIZE_DEBUG in your build system (e.g. CMake) to force -// the compiler to aggressively inline and optimize DelegateMQ templates even -// during unoptimized Debug builds. This significantly reduces code bloat and -// call stack depth for variadic template unpacking without losing the ability -// to step-debug your application code. -// -// NOTE: This feature relies on GCC/Clang-specific pragmas. MSVC's #pragma optimize -// cannot elevate optimizations above the command-line (/Od) baseline and is mostly -// deprecated for x64 targets. Thus, this macro is a silent no-op on MSVC Windows builds. -// For GCC/Clang, this uses -Os (optimize for size) to maximize flash savings. -#ifdef DMQ_FORCE_OPTIMIZE_DEBUG - #if defined(__GNUC__) || defined(__clang__) - #define DMQ_OPTIMIZE_ON \ - _Pragma("GCC push_options") \ - _Pragma("GCC optimize (\"Os\")") - #define DMQ_OPTIMIZE_OFF \ - _Pragma("GCC pop_options") - #else - #define DMQ_OPTIMIZE_ON - #define DMQ_OPTIMIZE_OFF - #endif -#else - #define DMQ_OPTIMIZE_ON - #define DMQ_OPTIMIZE_OFF -#endif - -#endif // _DELEGATE_OPT_H diff --git a/DelegateMQ/delegate/DelegateRemote.h b/DelegateMQ/delegate/DelegateRemote.h deleted file mode 100644 index b892ba7..0000000 --- a/DelegateMQ/delegate/DelegateRemote.h +++ /dev/null @@ -1,1688 +0,0 @@ -#ifndef _DELEGATE_REMOTE_H -#define _DELEGATE_REMOTE_H - -// DelegateRemote.h -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, Aug 2025. - -/// @file -/// @brief Delegate "`Remote`" series of classes used to invoke a function remotely -/// (i.e. different CPU, different process, etc...). -/// -/// @details The classes are not thread safe. Invoking a function remotely requires serializing -/// all target function arguments and sending the argument data to the remote destination. All -/// argument data is serialized into a stream. The receiver calls `Invoke()` with the received -/// serialized stream arguments. -/// -/// An `ISerializer` and `IDispatcher` implementations are required to serialize and dispatch a -/// remote delegate. These interface implementations, relied upon by the remote delegate, might not -/// be thread safe. Therefore, ensure each remote delegate instance is called from a single thread -/// of control. -/// -/// `RetType operator()(Args... args)` - called by the sender to initiate the remote function call. -/// Use `SetErrorHandler()` to catch invoke errors. Clone() may throw `std::bad_alloc` unless -/// `DMQ_ASSERTS`. All other delegate class functions do not throw exceptions. -/// -/// `void Invoke(std::istream& is)` - called by the receiver to invoke the target function. -/// -/// Limitations: -/// -/// * The target function return value is not valid after invoke since the delegate does -/// not wait for the target function to be called. -/// -/// * Cannot use a `void*` as a target function argument. -/// -/// * Cannot use rvalue reference (T&&) as a target function argument. -/// -/// * Cannot insert `DelegateRemoteAsync` into an ordered container. e.g. `std::list` ok, -/// `std::set` not ok. -/// -/// * `std::function` compares the function signature type, not the underlying object instance. -/// See `DelegateFunction<>` class for more info. -/// -/// Code within `` and `` is updated using src_dup.py. Manually update -/// the code within the `DelegateFreeRemote` `common_code` tags, then run the script to -/// propagate to the remaining delegate classes to simplify code maintenance. -/// -/// `python src_dup.py DelegateRemote.h` - -#include "Delegate.h" -#include "UnicastDelegate.h" -#include "ISerializer.h" -#include "IDispatcher.h" -#include "IInvoker.h" -#include -#include "DelegateOpt.h" -#include -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -enum class DelegateError { - SUCCESS = 0, - ERR_STREAM_NOT_GOOD = 1, - ERR_NO_SERIALIZER = 2, - ERR_SERIALIZE = 3, - ERR_DESERIALIZE = 4, - ERR_DESERIALIZE_EXCEPTION = 5, - ERR_NO_DISPATCHER = 6, - ERR_DISPATCH = 7, - ERR_TYPE_MISMATCH = 8, - ERR_TRANSPORT_RECEIVE = 9, // Transport-level receive failure (bad frame, socket error) - ERR_CAPACITY_EXCEEDED = 10 // A fixed-size capacity limit was reached (e.g. MAX_PARTICIPANTS) -}; - -typedef int DelegateErrorAux; - -// Get the type of the Nth position within a template parameter pack -template using ArgTypeOf = -typename std::tuple_element>::type; - -// Get the value of the Nth position within a template parameter pack -template -decltype(auto) ArgValueOf(Args&&... ts) { - return std::get(std::forward_as_tuple(ts...)); -} - -template -class RemoteArg -{ -public: - using NonConstArg = std::remove_const_t; - NonConstArg& Get() { return m_arg; } -private: - NonConstArg m_arg{}; -}; - -template -class RemoteArg -{ -public: - using NonConstArg = std::remove_const_t; - - // Initialize the member pointer to point to the internal storage - RemoteArg() : m_ptr(&m_arg) {} - - // Custom copy/move semantics to ensure m_ptr always points to the *local* m_arg - RemoteArg(const RemoteArg& other) : m_arg(other.m_arg), m_ptr(&m_arg) {} - RemoteArg& operator=(const RemoteArg& other) { - if (this != &other) { - m_arg = other.m_arg; - m_ptr = &m_arg; - } - return *this; - } - - RemoteArg(RemoteArg&& other) noexcept : m_arg(std::move(other.m_arg)), m_ptr(&m_arg) {} - RemoteArg& operator=(RemoteArg&& other) noexcept { - if (this != &other) { - m_arg = std::move(other.m_arg); - m_ptr = &m_arg; - } - return *this; - } - - // Return a REFERENCE to the pointer (L-value), satisfying ISerializer::Read - Arg*& Get() { return m_ptr; } - -private: - NonConstArg m_arg{}; // The actual object storage - Arg* m_ptr; // The persistent pointer variable -}; - -#if 0 // Arg** not supported on remote delegates -template -class RemoteArg -{ -public: - RemoteArg() : m_pArg(&m_arg), m_ppArg(&m_pArg) {} - - // Return reference to the pointer-to-pointer - Arg**& Get() { return m_ppArg; } - -private: - Arg m_arg; - Arg* m_pArg; - Arg** m_ppArg; -}; -#endif - -template -class RemoteArg -{ -public: - using NonConstArg = std::remove_const_t; - NonConstArg& Get() { return m_arg; } -private: - NonConstArg m_arg{}; -}; - -namespace detail { - -/// @brief Fully non-template holder for a `DelegateXRemote<...>` instance's dispatch -/// state — remote id, dispatcher, output stream, last error, last dispatched sequence -/// number, and error-handler delegate. None of this depends on the bound function's -/// signature or target class (the error handler's own signature is fixed, independent -/// of the owning delegate's), so every `DelegateFreeRemote`/`DelegateMemberRemote`/ -/// `DelegateFunctionRemote` instantiation — for every signature and target class in the -/// program — composes this one definition instead of each generating its own copy. -/// @note `m_serializer` deliberately stays outside this class, on each owning delegate: -/// `ISerializer*` is the one piece of remote-dispatch state that -/// genuinely varies by signature. -/// @note `m_error` and `m_lastSeqNum` are per-instance, transient run-time observations -/// (the last error *this* object raised; the last sequence number *this* object's most -/// recent send was assigned) — never copied, assigned, or moved between instances, -/// only ever reset to their defaults on a fresh object. The special members below -/// deliberately leave them alone, mirroring the pre-refactor Assign()/copy-ctor/ -/// move-ctor/move-assign, none of which touched them either. -class RemoteDispatchState { -public: - RemoteDispatchState() = default; - - RemoteDispatchState(const RemoteDispatchState& rhs) - : m_id(rhs.m_id), m_errorHandler(rhs.m_errorHandler), - m_dispatcher(rhs.m_dispatcher), m_stream(rhs.m_stream), - m_sendMutex(rhs.m_sendMutex) { - } - - RemoteDispatchState(RemoteDispatchState&& rhs) noexcept - : m_id(rhs.m_id), m_errorHandler(std::move(rhs.m_errorHandler)), - m_dispatcher(rhs.m_dispatcher), m_stream(rhs.m_stream), - m_sendMutex(rhs.m_sendMutex) { - rhs.m_dispatcher = nullptr; - rhs.m_stream = nullptr; - rhs.m_sendMutex = nullptr; - } - - RemoteDispatchState& operator=(const RemoteDispatchState& rhs) { - if (this != &rhs) { - m_id = rhs.m_id; - m_errorHandler = rhs.m_errorHandler; - m_dispatcher = rhs.m_dispatcher; - m_stream = rhs.m_stream; - m_sendMutex = rhs.m_sendMutex; - } - return *this; - } - - RemoteDispatchState& operator=(RemoteDispatchState&& rhs) noexcept { - if (this != &rhs) { - m_id = rhs.m_id; - m_errorHandler = std::move(rhs.m_errorHandler); - m_dispatcher = rhs.m_dispatcher; - m_stream = rhs.m_stream; - m_sendMutex = rhs.m_sendMutex; - rhs.m_dispatcher = nullptr; - rhs.m_stream = nullptr; - rhs.m_sendMutex = nullptr; - } - return *this; - } - - DelegateRemoteId GetRemoteId() const noexcept { return m_id; } - void SetRemoteId(DelegateRemoteId id) noexcept { m_id = id; } - - IDispatcher* GetDispatcher() const noexcept { return m_dispatcher; } - void SetDispatcher(IDispatcher* dispatcher) noexcept { m_dispatcher = dispatcher; } - - dmq::xostringstream* GetStream() const noexcept { return m_stream; } - void SetStream(dmq::xostringstream* stream) noexcept { m_stream = stream; } - - dmq::Mutex* GetSendMutex() const noexcept { return m_sendMutex; } - void SetSendMutex(dmq::Mutex* mutex) noexcept { m_sendMutex = mutex; } - - uint16_t GetLastSeqNum() const noexcept { return m_lastSeqNum; } - - void SetErrorHandler(const Delegate& errorHandler) { - m_errorHandler = errorHandler; // Copy - } - void SetErrorHandler(Delegate&& errorHandler) { - m_errorHandler = std::move(errorHandler); // Moving the temporary - } - void ClearErrorHandler() { - m_errorHandler.Clear(); - } - - /// @brief Get the last error code. - /// @return The last error detected. - /// @post Error is reset to SUCCESS after call. - DelegateError GetError() noexcept { - DelegateError retVal = m_error; - m_error = DelegateError::SUCCESS; - return retVal; - } - - /// Raise an error and callback the registered error handler. - /// @param[in] error Error code. - /// @param[in] auxCode Optional auxiliary code. - /// @throws std::runtime_error If no error handler is registered. - void RaiseError(DelegateError error, DelegateErrorAux auxCode = 0) { - m_error = error; - if (m_errorHandler) { - m_errorHandler(m_id, error, auxCode); - } - else { -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // No throw -#else - throw std::runtime_error("Delegate remote error " + std::to_string(static_cast(error)) + " id " + std::to_string(m_id)); -#endif - } - } - - /// Raise success and callback the registered error handler. - void RaiseSuccess() { - if (m_errorHandler) - m_errorHandler(m_id, dmq::DelegateError::SUCCESS, 0); - } - - /// @brief Check the stream, dispatch it to the remote, and report success/error - /// through the error handler. - /// @details Everything past the argument serialization step is identical - /// regardless of the delegate's signature or target class, so it lives here once - /// instead of being duplicated in every `DelegateXRemote<...>::operator()`. - /// @param[in] writeFailed `true` if the caller's `ISerializer::Write()` call threw - /// (already reported through `RaiseError(ERR_SERIALIZE)` by the caller). - void SendSerialized(bool writeFailed) { - if (writeFailed) - return; - - if (!m_stream || !m_stream->good()) { - RaiseError(DelegateError::ERR_STREAM_NOT_GOOD); - return; - } - - if (!m_dispatcher) { - RaiseError(DelegateError::ERR_NO_DISPATCHER); - return; - } - - // Dispatch delegate invocation to the remote destination -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - int error = m_dispatcher->Dispatch(*m_stream, m_id, &m_lastSeqNum); - if (error) - RaiseError(DelegateError::ERR_DISPATCH, error); - else - RaiseSuccess(); -#else - try { - int error = m_dispatcher->Dispatch(*m_stream, m_id, &m_lastSeqNum); - if (error) - RaiseError(DelegateError::ERR_DISPATCH, error); - else - RaiseSuccess(); - } - catch (std::exception&) { - RaiseError(DelegateError::ERR_DISPATCH); - } -#endif - } - - bool Equal(const RemoteDispatchState& rhs) const noexcept { - return m_id == rhs.m_id; - } - -private: - DelegateRemoteId m_id = INVALID_REMOTE_ID; - mutable uint16_t m_lastSeqNum = 0; - UnicastDelegate m_errorHandler; - IDispatcher* m_dispatcher = nullptr; - DelegateError m_error = DelegateError::SUCCESS; - dmq::xostringstream* m_stream = nullptr; - dmq::Mutex* m_sendMutex = nullptr; -}; - -/// @brief Holds a remote delegate's send mutex, if it has one, for the whole -/// serialize-and-dispatch step of one call. -class RemoteSendLock { -public: - explicit RemoteSendLock(dmq::Mutex* mutex) noexcept : m_mutex(mutex) { - if (m_mutex) - m_mutex->lock(); - } - ~RemoteSendLock() noexcept { - if (m_mutex) - m_mutex->unlock(); - } - RemoteSendLock(const RemoteSendLock&) = delete; - RemoteSendLock& operator=(const RemoteSendLock&) = delete; - -private: - dmq::Mutex* m_mutex; -}; - -} // namespace detail - -template -class DelegateFreeRemote; // Not defined - -/// @brief `DelegateFreeRemote<>` class asynchronously invokes a free target function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFreeRemote : public DelegateFree, public IRemoteInvoker { -public: - typedef std::integral_constant ArgCnt; - typedef RetType(*FreeFunc)(Args...); - using ClassType = DelegateFreeRemote; - using BaseType = DelegateFree; - - static_assert(!(std::disjunction_v...>), - "std::shared_ptr arguments must be passed by value on remote delegates; reference and pointer forms are not allowed"); - static_assert(!(std::disjunction_v...>), - "Double pointer arguments (Arg**) are not allowed on remote delegates"); - using BaseType::operator=; - - /// @brief Constructor to create a class instance. Typically called by sender. - /// @param[in] id The remote delegate identifier. - DelegateFreeRemote(DelegateRemoteId id) { m_state.SetRemoteId(id); } - - /// @brief Constructor to create a class instance. Typically called by receiver. - /// @param[in] func The target free function to store. - /// @param[in] id The remote delegate identifier. - DelegateFreeRemote(FreeFunc func, DelegateRemoteId id) : - BaseType(func) { - Bind(func, id); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFreeRemote(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFreeRemote(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(std::move(rhs.m_state)), m_serializer(rhs.m_serializer) { - rhs.Clear(); - rhs.m_serializer = nullptr; - } - - DelegateFreeRemote() = default; - - /// @brief Bind a free function to the delegate. - /// @details This method associates a free function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The free function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] id The remote delegate identifier. - void Bind(FreeFunc func, DelegateRemoteId id) { - m_state.SetRemoteId(id); - BaseType::Bind(func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_serializer = rhs.m_serializer; - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = std::move(rhs.m_state); // Use the resource - m_serializer = rhs.m_serializer; - rhs.m_serializer = nullptr; - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function on the remote. Called by the sender. - /// @details Invoke remote delegate function asynchronously and do not wait for the - /// return value. This function is called by the sender. Dispatches the delegate data to - /// the destination remote receiver. `Invoke()` must be called by the destination - /// remote receiver to invoke the target function. Always safe to call. - /// - /// All argument data is serialized into a binary byte stream. The stream of bytes is - /// sent to the receiver. The receivder deserializes the arguments and invokes the remote - /// target function. - /// - /// All user-defined argument data must inherit from ISerializer and implement the - /// `read()` and `write()` functions to serialize each data member. - /// - /// Does not throw exceptions. However, the platform-specific `ISerializer` implementation - /// might. Register for error callbacks using `SetErrorHandler()`. - /// - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - virtual RetType operator()(Args... args) override { - if (m_serializer && m_state.GetStream()) { - // Remote delegates may share one stream (e.g. every delegate made from - // one RemoteChannel); the send mutex keeps their sends from interleaving. - detail::RemoteSendLock sendLock(m_state.GetSendMutex()); - // Only true once the whole send succeeds (write + stream check + dispatch). - // RaiseSuccess() is deferred to that single point so a write/dispatch failure - // is never preceded by a spurious success callback, and a failure is never - // reported more than once for the same call. - bool writeFailed = false; -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // Serialize all target function arguments into a stream - m_serializer->Write(*m_state.GetStream(), std::forward(args)...); -#else - try { - // Serialize all target function arguments into a stream - m_serializer->Write(*m_state.GetStream(), std::forward(args)...); - } - catch (std::exception&) { - writeFailed = true; - m_state.RaiseError(DelegateError::ERR_SERIALIZE); - } -#endif - // Stream-good check, dispatch, and error/success reporting are identical - // regardless of signature or target class - see RemoteDispatchState::SendSerialized(). - m_state.SendSerialized(writeFailed); - } - else { - m_state.RaiseError(DelegateError::ERR_NO_SERIALIZER); - } - - // Do not wait for remote to invoke function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the remote sender. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination receiver. Called by the - /// remote destination. The sender serializes all target function arguments. This - /// function unserializes the argument data and invokes the remote target function. - /// @details Each source sender call to `operator()` generate a call to `Invoke()` - /// on the destination receiver. - /// @param[in] is The delegate argument stream created and sent within - /// `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::istream& is) override { - if (!m_serializer) { - m_state.RaiseError(DelegateError::ERR_NO_SERIALIZER); - return false; - } - - if (!is.good()) { - m_state.RaiseError(DelegateError::ERR_STREAM_NOT_GOOD); - return false; - } - -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - if constexpr (ArgCnt::value == 0) { - BaseType::operator()(); - } - else { - // 1. Create a tuple of RemoteArg to hold the temporary storage - std::tuple...> remoteArgs; - - // 2. Use std::apply to unpack the tuple elements - std::apply([this, &is](auto&... rArgs) { - - // 3. Deserialize: Expand the pack to call Read(is, arg1, arg2...) - // rArgs.Get() returns the reference/pointer to the internal storage - m_serializer->Read(is, rArgs.Get()...); - - if (!is.bad() && !is.fail()) { - // 4. Invoke: Expand the pack to call operator()(arg1, arg2...) - this->BaseType::operator()(rArgs.Get()...); - } - else { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE); - } - - }, remoteArgs); - } -#else - if constexpr (ArgCnt::value == 0) { - // No arguments to deserialize, so nothing here can throw a - // deserialization exception. Let any exception from the target - // function itself propagate uncaught -- it is an application - // fault, not a wire-format/serializer fault. - BaseType::operator()(); - } - else { - // 1. Create a tuple of RemoteArg to hold the temporary storage - std::tuple...> remoteArgs; - - // 2. Use std::apply to unpack the tuple elements - std::apply([this, &is](auto&... rArgs) { - - // 3. Deserialize: Expand the pack to call Read(is, arg1, arg2...) - // rArgs.Get() returns the reference/pointer to the internal storage. - // Only this step is wrapped in try/catch: an exception here reflects - // a corrupt stream or serializer bug. The invocation below is - // deliberately NOT wrapped -- if the bound target function throws, - // that is an application exception and must propagate to the caller, - // not be misreported as ERR_DESERIALIZE_EXCEPTION. - bool deserializeOk = true; - try { - m_serializer->Read(is, rArgs.Get()...); - } - catch (std::exception&) { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE_EXCEPTION); - deserializeOk = false; - } - - if (deserializeOk) { - if (!is.bad() && !is.fail()) { - // 4. Invoke: Expand the pack to call operator()(arg1, arg2...) - this->BaseType::operator()(rArgs.Get()...); - } - else { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE); - } - } - - }, remoteArgs); - } -#endif - - return true; - } - - ///@brief Get the remote identifier. - // @return The remote identifier. - DelegateRemoteId GetRemoteId() noexcept { return m_state.GetRemoteId(); } - - ///@brief Set the remote identifier. - /// @param[in] id The remote identifier. - void SetRemoteId(DelegateRemoteId id) noexcept { m_state.SetRemoteId(id); } - - /// @brief Set the dispatcher instance used to send to remote - /// @param[in] dispatcher A dispatcher instance - void SetDispatcher(IDispatcher* dispatcher) { - m_state.SetDispatcher(dispatcher); - } - - /// @brief Set the serializer instance used to serialize/deserialize - /// function arguments. - /// @param[in] serializer A serializer instance - void SetSerializer(ISerializer* serializer) { - m_serializer = serializer; - } - - /// @brief Set the serialization stream used to store serialized function - /// argument data. - /// @param[in] stream An output stream. - void SetStream(dmq::xostringstream* stream) { - m_state.SetStream(stream); - } - - /// @brief Set the mutex held while serializing into and dispatching the - /// stream. Required when several delegates share one stream across threads. - /// @param[in] mutex The mutex, or nullptr for none. Caller owns it. - void SetSendMutex(dmq::Mutex* mutex) { - m_state.SetSendMutex(mutex); - } - - /// @brief Set the error handler - /// @param[in] errorHandler The delegate error handler called when - /// an error is detected. - void SetErrorHandler(const Delegate& errorHandler) { - m_state.SetErrorHandler(errorHandler); // Copy - } - - /// @brief Set the error handler - /// @param[in] errorHandler The delegate error handler called when - /// an error is detected. - void SetErrorHandler(Delegate&& errorHandler) { - m_state.SetErrorHandler(std::move(errorHandler)); // Moving the temporary - } - - /// @brief Clear the error handler - void ClearErrorHandler() { - m_state.ClearErrorHandler(); - } - - /// @brief Get the last error code - /// @return The last error detected - /// @post Error is reset to SUCCESS after call - DelegateError GetError() { - return m_state.GetError(); - } - - /// @brief Get the sequence number assigned by the dispatcher to the most - /// recent successful dispatch. - /// @return The last dispatched sequence number, or 0 if nothing has been - /// dispatched yet. - uint16_t GetLastSeqNum() const noexcept { return m_state.GetLastSeqNum(); } - -private: - /// Destination remote id, dispatcher, output stream, last error, last sequence - /// number, and error handler. Not templated on Sig/TClass — see - /// `detail::RemoteDispatchState`. - detail::RemoteDispatchState m_state; - - /// A pointer to the function argument serializer. Kept outside `m_state` since, - /// unlike everything else there, its pointee type genuinely varies by signature. - ISerializer* m_serializer = nullptr; - - // -}; - -template -class DelegateMemberRemote; // Not defined - -/// @brief `DelegateMemberRemote<>` class asynchronously invokes a class member target function. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateMemberRemote : public DelegateMember, public IRemoteInvoker { -public: - typedef std::integral_constant ArgCnt; - typedef TClass* ObjectPtr; - typedef std::shared_ptr SharedPtr; - typedef RetType(TClass::* MemberFunc)(Args...); - typedef RetType(TClass::* ConstMemberFunc)(Args...) const; - using ClassType = DelegateMemberRemote; - using BaseType = DelegateMember; - - static_assert(!(std::disjunction_v...>), - "std::shared_ptr arguments must be passed by value on remote delegates; reference and pointer forms are not allowed"); - static_assert(!(std::disjunction_v...>), - "Double pointer arguments (Arg**) are not allowed on remote delegates"); - using BaseType::operator=; - - /// @brief Constructor to create a class instance. Typically called by sender. - /// @param[in] id The remote delegate identifier. - DelegateMemberRemote(DelegateRemoteId id) { m_state.SetRemoteId(id); } - - /// @brief Constructor to create a class instance. Typically called by receiver. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - /// @param[in] id The delegate remote identifier. - DelegateMemberRemote(SharedPtr object, MemberFunc func, DelegateRemoteId id) : BaseType(object, func) { - Bind(object, func, id); - } - - /// @brief Constructor to create a class instance. Typically called by receiver. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - /// @param[in] id The delegate remote identifier. - DelegateMemberRemote(SharedPtr object, ConstMemberFunc func, DelegateRemoteId id) : BaseType(object, func) { - Bind(object, func, id); - } - - /// @brief Constructor to create a class instance. Typically called by receiver. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target member function to store. - /// @param[in] id The delegate remote identifier. - DelegateMemberRemote(ObjectPtr object, MemberFunc func, DelegateRemoteId id) : BaseType(object, func) { - Bind(object, func, id); - } - - /// @brief Constructor to create a class instance. Typically called by receiver. - /// @param[in] object The target object pointer to store. - /// @param[in] func The target const member function to store. - /// @param[in] id The delegate remote identifier. - DelegateMemberRemote(ObjectPtr object, ConstMemberFunc func, DelegateRemoteId id) : BaseType(object, func) { - Bind(object, func, id); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateMemberRemote(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateMemberRemote(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(std::move(rhs.m_state)), m_serializer(rhs.m_serializer) { - rhs.Clear(); - rhs.m_serializer = nullptr; - } - - DelegateMemberRemote() = default; - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] id The delegate remote identifier. - void Bind(SharedPtr object, MemberFunc func, DelegateRemoteId id) { - m_state.SetRemoteId(id); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] id The delegate remote identifier. - void Bind(SharedPtr object, ConstMemberFunc func, DelegateRemoteId id) { - m_state.SetRemoteId(id); - BaseType::Bind(object, func); - } - - /// @brief Bind a member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The function to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] id The delegate remote identifier. - void Bind(ObjectPtr object, MemberFunc func, DelegateRemoteId id) { - m_state.SetRemoteId(id); - BaseType::Bind(object, func); - } - - /// @brief Bind a const member function to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] object The target object instance. - /// @param[in] func The member function to bind to the delegate. This function must - /// match the signature of the delegate. - /// @param[in] id The delegate remote identifier. - void Bind(ObjectPtr object, ConstMemberFunc func, DelegateRemoteId id) { - m_state.SetRemoteId(id); - BaseType::Bind(object, func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_serializer = rhs.m_serializer; - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = std::move(rhs.m_state); // Use the resource - m_serializer = rhs.m_serializer; - rhs.m_serializer = nullptr; - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function on the remote. Called by the sender. - /// @details Invoke remote delegate function asynchronously and do not wait for the - /// return value. This function is called by the sender. Dispatches the delegate data to - /// the destination remote receiver. `Invoke()` must be called by the destination - /// remote receiver to invoke the target function. Always safe to call. - /// - /// All argument data is serialized into a binary byte stream. The stream of bytes is - /// sent to the receiver. The receivder deserializes the arguments and invokes the remote - /// target function. - /// - /// All user-defined argument data must inherit from ISerializer and implement the - /// `read()` and `write()` functions to serialize each data member. - /// - /// Does not throw exceptions. However, the platform-specific `ISerializer` implementation - /// might. Register for error callbacks using `SetErrorHandler()`. - /// - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - virtual RetType operator()(Args... args) override { - if (m_serializer && m_state.GetStream()) { - // Remote delegates may share one stream (e.g. every delegate made from - // one RemoteChannel); the send mutex keeps their sends from interleaving. - detail::RemoteSendLock sendLock(m_state.GetSendMutex()); - // Only true once the whole send succeeds (write + stream check + dispatch). - // RaiseSuccess() is deferred to that single point so a write/dispatch failure - // is never preceded by a spurious success callback, and a failure is never - // reported more than once for the same call. - bool writeFailed = false; -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // Serialize all target function arguments into a stream - m_serializer->Write(*m_state.GetStream(), std::forward(args)...); -#else - try { - // Serialize all target function arguments into a stream - m_serializer->Write(*m_state.GetStream(), std::forward(args)...); - } - catch (std::exception&) { - writeFailed = true; - m_state.RaiseError(DelegateError::ERR_SERIALIZE); - } -#endif - // Stream-good check, dispatch, and error/success reporting are identical - // regardless of signature or target class - see RemoteDispatchState::SendSerialized(). - m_state.SendSerialized(writeFailed); - } - else { - m_state.RaiseError(DelegateError::ERR_NO_SERIALIZER); - } - - // Do not wait for remote to invoke function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the remote sender. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination receiver. Called by the - /// remote destination. The sender serializes all target function arguments. This - /// function unserializes the argument data and invokes the remote target function. - /// @details Each source sender call to `operator()` generate a call to `Invoke()` - /// on the destination receiver. - /// @param[in] is The delegate argument stream created and sent within - /// `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::istream& is) override { - if (!m_serializer) { - m_state.RaiseError(DelegateError::ERR_NO_SERIALIZER); - return false; - } - - if (!is.good()) { - m_state.RaiseError(DelegateError::ERR_STREAM_NOT_GOOD); - return false; - } - -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - if constexpr (ArgCnt::value == 0) { - BaseType::operator()(); - } - else { - // 1. Create a tuple of RemoteArg to hold the temporary storage - std::tuple...> remoteArgs; - - // 2. Use std::apply to unpack the tuple elements - std::apply([this, &is](auto&... rArgs) { - - // 3. Deserialize: Expand the pack to call Read(is, arg1, arg2...) - // rArgs.Get() returns the reference/pointer to the internal storage - m_serializer->Read(is, rArgs.Get()...); - - if (!is.bad() && !is.fail()) { - // 4. Invoke: Expand the pack to call operator()(arg1, arg2...) - this->BaseType::operator()(rArgs.Get()...); - } - else { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE); - } - - }, remoteArgs); - } -#else - if constexpr (ArgCnt::value == 0) { - // No arguments to deserialize, so nothing here can throw a - // deserialization exception. Let any exception from the target - // function itself propagate uncaught -- it is an application - // fault, not a wire-format/serializer fault. - BaseType::operator()(); - } - else { - // 1. Create a tuple of RemoteArg to hold the temporary storage - std::tuple...> remoteArgs; - - // 2. Use std::apply to unpack the tuple elements - std::apply([this, &is](auto&... rArgs) { - - // 3. Deserialize: Expand the pack to call Read(is, arg1, arg2...) - // rArgs.Get() returns the reference/pointer to the internal storage. - // Only this step is wrapped in try/catch: an exception here reflects - // a corrupt stream or serializer bug. The invocation below is - // deliberately NOT wrapped -- if the bound target function throws, - // that is an application exception and must propagate to the caller, - // not be misreported as ERR_DESERIALIZE_EXCEPTION. - bool deserializeOk = true; - try { - m_serializer->Read(is, rArgs.Get()...); - } - catch (std::exception&) { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE_EXCEPTION); - deserializeOk = false; - } - - if (deserializeOk) { - if (!is.bad() && !is.fail()) { - // 4. Invoke: Expand the pack to call operator()(arg1, arg2...) - this->BaseType::operator()(rArgs.Get()...); - } - else { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE); - } - } - - }, remoteArgs); - } -#endif - - return true; - } - - ///@brief Get the remote identifier. - // @return The remote identifier. - DelegateRemoteId GetRemoteId() noexcept { return m_state.GetRemoteId(); } - - ///@brief Set the remote identifier. - /// @param[in] id The remote identifier. - void SetRemoteId(DelegateRemoteId id) noexcept { m_state.SetRemoteId(id); } - - /// @brief Set the dispatcher instance used to send to remote - /// @param[in] dispatcher A dispatcher instance - void SetDispatcher(IDispatcher* dispatcher) { - m_state.SetDispatcher(dispatcher); - } - - /// @brief Set the serializer instance used to serialize/deserialize - /// function arguments. - /// @param[in] serializer A serializer instance - void SetSerializer(ISerializer* serializer) { - m_serializer = serializer; - } - - /// @brief Set the serialization stream used to store serialized function - /// argument data. - /// @param[in] stream An output stream. - void SetStream(dmq::xostringstream* stream) { - m_state.SetStream(stream); - } - - /// @brief Set the mutex held while serializing into and dispatching the - /// stream. Required when several delegates share one stream across threads. - /// @param[in] mutex The mutex, or nullptr for none. Caller owns it. - void SetSendMutex(dmq::Mutex* mutex) { - m_state.SetSendMutex(mutex); - } - - /// @brief Set the error handler - /// @param[in] errorHandler The delegate error handler called when - /// an error is detected. - void SetErrorHandler(const Delegate& errorHandler) { - m_state.SetErrorHandler(errorHandler); // Copy - } - - /// @brief Set the error handler - /// @param[in] errorHandler The delegate error handler called when - /// an error is detected. - void SetErrorHandler(Delegate&& errorHandler) { - m_state.SetErrorHandler(std::move(errorHandler)); // Moving the temporary - } - - /// @brief Clear the error handler - void ClearErrorHandler() { - m_state.ClearErrorHandler(); - } - - /// @brief Get the last error code - /// @return The last error detected - /// @post Error is reset to SUCCESS after call - DelegateError GetError() { - return m_state.GetError(); - } - - /// @brief Get the sequence number assigned by the dispatcher to the most - /// recent successful dispatch. - /// @return The last dispatched sequence number, or 0 if nothing has been - /// dispatched yet. - uint16_t GetLastSeqNum() const noexcept { return m_state.GetLastSeqNum(); } - -private: - /// Destination remote id, dispatcher, output stream, last error, last sequence - /// number, and error handler. Not templated on Sig/TClass — see - /// `detail::RemoteDispatchState`. - detail::RemoteDispatchState m_state; - - /// A pointer to the function argument serializer. Kept outside `m_state` since, - /// unlike everything else there, its pointee type genuinely varies by signature. - ISerializer* m_serializer = nullptr; - - // -}; - -template -class DelegateFunctionRemote; // Not defined - -/// @brief `DelegateFunctionRemote<>` class asynchronously invokes a `std::function` target function. -/// @details Caution when binding to a `std::function` using this class. `std::function` cannot be -/// compared for equality directly in a meaningful way using `operator==`. -/// -/// See `DelegateFunction<>` base class for important usage limitations. -/// -/// @tparam RetType The return type of the bound delegate function. -/// @tparam Args The argument types of the bound delegate function. -template -class DelegateFunctionRemote : public DelegateFunction, public IRemoteInvoker { -public: - typedef std::integral_constant ArgCnt; - using FunctionType = std::function; - using ClassType = DelegateFunctionRemote; - using BaseType = DelegateFunction; - - static_assert(!(std::disjunction_v...>), - "std::shared_ptr arguments must be passed by value on remote delegates; reference and pointer forms are not allowed"); - static_assert(!(std::disjunction_v...>), - "Double pointer arguments (Arg**) are not allowed on remote delegates"); - using BaseType::operator=; - - /// @brief Constructor to create a class instance. Typically called by sender. - /// @param[in] id The remote delegate identifier. - DelegateFunctionRemote(DelegateRemoteId id) { m_state.SetRemoteId(id); } - - /// @brief Constructor to create a class instance. Typically called by receiver. - /// @param[in] func The target `std::function` to store. - /// @param[in] id The unique remote delegate identifier. - DelegateFunctionRemote(FunctionType func, DelegateRemoteId id) : - BaseType(func) { - Bind(func, id); - } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - DelegateFunctionRemote(const ClassType& rhs) : - BaseType(rhs) { - Assign(rhs); - } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - DelegateFunctionRemote(ClassType&& rhs) noexcept : - BaseType(std::move(rhs)), m_state(std::move(rhs.m_state)), m_serializer(rhs.m_serializer) { - rhs.Clear(); - rhs.m_serializer = nullptr; - } - - DelegateFunctionRemote() = default; - - /// @brief Bind a `std::function` to the delegate. - /// @details This method associates a member function (`func`) with the delegate. - /// Once the function is bound, the delegate can be used to invoke the function. - /// @param[in] func The `std::function` to bind to the delegate. This function must match - /// the signature of the delegate. - /// @param[in] id The delegate remote identifier. - void Bind(FunctionType func, DelegateRemoteId id) { - m_state.SetRemoteId(id); - BaseType::Bind(func); - } - - // - - /// @brief Assigns the state of one object to another. - /// @details Copy the state from the `rhs` (right-hand side) object to the - /// current object. - /// @param[in] rhs The object whose state is to be copied. - void Assign(const ClassType& rhs) { - m_state = rhs.m_state; - m_serializer = rhs.m_serializer; - BaseType::Assign(rhs); - } - - /// @brief Creates a copy of the current object. - /// @details Clones the current instance of the class by creating a new object - /// and copying the state of the current object to it. - /// @return A pointer to a new `ClassType` instance or nullptr if allocation fails. - /// @post The caller is responsible for deleting the clone object and checking for - /// nullptr. - virtual ClassType* Clone() const override { - return new(std::nothrow) ClassType(*this); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - ClassType& operator=(const ClassType& rhs) { - if (&rhs != this) { - BaseType::operator=(rhs); - Assign(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - ClassType& operator=(ClassType&& rhs) noexcept { - if (&rhs != this) { - BaseType::operator=(std::move(rhs)); - m_state = std::move(rhs.m_state); // Use the resource - m_serializer = rhs.m_serializer; - rhs.m_serializer = nullptr; - } - return *this; - } - - /// @brief Clear the target function. - virtual void operator=(std::nullptr_t) noexcept override { - return this->Clear(); - } - - /// @brief Compares two delegate objects for equality. - /// @param[in] rhs The `DelegateBase` object to compare with the current object. - /// @return `true` if the two delegate objects are equal, `false` otherwise. - virtual bool Equal(const DelegateBase& rhs) const override { - auto derivedRhs = dynamic_cast(&rhs); - return derivedRhs && - m_state.Equal(derivedRhs->m_state) && - BaseType::Equal(rhs); - } - - /// Compares two delegate objects for equality. - /// @return `true` if the objects are equal, `false` otherwise. - bool operator==(const ClassType& rhs) const noexcept { return Equal(rhs); } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - virtual bool operator==(std::nullptr_t) const noexcept override { - return this->Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - virtual bool operator!=(std::nullptr_t) const noexcept override { - return !this->Empty(); - } - - /// Overload operator== to compare the delegate to nullptr - /// @return `true` if delegate is null. - friend bool operator==(std::nullptr_t, const ClassType& rhs) noexcept { - return rhs.Empty(); - } - - /// Overload operator!= to compare the delegate to nullptr - /// @return `true` if delegate is not null. - friend bool operator!=(std::nullptr_t, const ClassType& rhs) noexcept { - return !rhs.Empty(); - } - - /// @brief Invoke the bound delegate function on the remote. Called by the sender. - /// @details Invoke remote delegate function asynchronously and do not wait for the - /// return value. This function is called by the sender. Dispatches the delegate data to - /// the destination remote receiver. `Invoke()` must be called by the destination - /// remote receiver to invoke the target function. Always safe to call. - /// - /// All argument data is serialized into a binary byte stream. The stream of bytes is - /// sent to the receiver. The receivder deserializes the arguments and invokes the remote - /// target function. - /// - /// All user-defined argument data must inherit from ISerializer and implement the - /// `read()` and `write()` functions to serialize each data member. - /// - /// Does not throw exceptions. However, the platform-specific `ISerializer` implementation - /// might. Register for error callbacks using `SetErrorHandler()`. - /// - /// @param[in] args The function arguments, if any. - /// @return A default return value. The return value is *not* returned from the - /// target function. Do not use the return value. - /// @post Do not use the return value as its not valid. - virtual RetType operator()(Args... args) override { - if (m_serializer && m_state.GetStream()) { - // Remote delegates may share one stream (e.g. every delegate made from - // one RemoteChannel); the send mutex keeps their sends from interleaving. - detail::RemoteSendLock sendLock(m_state.GetSendMutex()); - // Only true once the whole send succeeds (write + stream check + dispatch). - // RaiseSuccess() is deferred to that single point so a write/dispatch failure - // is never preceded by a spurious success callback, and a failure is never - // reported more than once for the same call. - bool writeFailed = false; -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // Serialize all target function arguments into a stream - m_serializer->Write(*m_state.GetStream(), std::forward(args)...); -#else - try { - // Serialize all target function arguments into a stream - m_serializer->Write(*m_state.GetStream(), std::forward(args)...); - } - catch (std::exception&) { - writeFailed = true; - m_state.RaiseError(DelegateError::ERR_SERIALIZE); - } -#endif - // Stream-good check, dispatch, and error/success reporting are identical - // regardless of signature or target class - see RemoteDispatchState::SendSerialized(). - m_state.SendSerialized(writeFailed); - } - else { - m_state.RaiseError(DelegateError::ERR_NO_SERIALIZER); - } - - // Do not wait for remote to invoke function call - return RetType(); - } - - /// @brief Invoke delegate function asynchronously. Do not wait for return value. - /// Called by the remote sender. Always safe to call. - /// @param[in] args The function arguments, if any. - void AsyncInvoke(Args... args) { - operator()(std::forward(args)...); - } - - /// @brief Invoke the delegate function on the destination receiver. Called by the - /// remote destination. The sender serializes all target function arguments. This - /// function unserializes the argument data and invokes the remote target function. - /// @details Each source sender call to `operator()` generate a call to `Invoke()` - /// on the destination receiver. - /// @param[in] is The delegate argument stream created and sent within - /// `operator()(Args... args)`. - /// @return `true` if target function invoked; `false` if error. - virtual bool Invoke(std::istream& is) override { - if (!m_serializer) { - m_state.RaiseError(DelegateError::ERR_NO_SERIALIZER); - return false; - } - - if (!is.good()) { - m_state.RaiseError(DelegateError::ERR_STREAM_NOT_GOOD); - return false; - } - -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - if constexpr (ArgCnt::value == 0) { - BaseType::operator()(); - } - else { - // 1. Create a tuple of RemoteArg to hold the temporary storage - std::tuple...> remoteArgs; - - // 2. Use std::apply to unpack the tuple elements - std::apply([this, &is](auto&... rArgs) { - - // 3. Deserialize: Expand the pack to call Read(is, arg1, arg2...) - // rArgs.Get() returns the reference/pointer to the internal storage - m_serializer->Read(is, rArgs.Get()...); - - if (!is.bad() && !is.fail()) { - // 4. Invoke: Expand the pack to call operator()(arg1, arg2...) - this->BaseType::operator()(rArgs.Get()...); - } - else { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE); - } - - }, remoteArgs); - } -#else - if constexpr (ArgCnt::value == 0) { - // No arguments to deserialize, so nothing here can throw a - // deserialization exception. Let any exception from the target - // function itself propagate uncaught -- it is an application - // fault, not a wire-format/serializer fault. - BaseType::operator()(); - } - else { - // 1. Create a tuple of RemoteArg to hold the temporary storage - std::tuple...> remoteArgs; - - // 2. Use std::apply to unpack the tuple elements - std::apply([this, &is](auto&... rArgs) { - - // 3. Deserialize: Expand the pack to call Read(is, arg1, arg2...) - // rArgs.Get() returns the reference/pointer to the internal storage. - // Only this step is wrapped in try/catch: an exception here reflects - // a corrupt stream or serializer bug. The invocation below is - // deliberately NOT wrapped -- if the bound target function throws, - // that is an application exception and must propagate to the caller, - // not be misreported as ERR_DESERIALIZE_EXCEPTION. - bool deserializeOk = true; - try { - m_serializer->Read(is, rArgs.Get()...); - } - catch (std::exception&) { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE_EXCEPTION); - deserializeOk = false; - } - - if (deserializeOk) { - if (!is.bad() && !is.fail()) { - // 4. Invoke: Expand the pack to call operator()(arg1, arg2...) - this->BaseType::operator()(rArgs.Get()...); - } - else { - this->m_state.RaiseError(DelegateError::ERR_DESERIALIZE); - } - } - - }, remoteArgs); - } -#endif - - return true; - } - - ///@brief Get the remote identifier. - // @return The remote identifier. - DelegateRemoteId GetRemoteId() noexcept { return m_state.GetRemoteId(); } - - ///@brief Set the remote identifier. - /// @param[in] id The remote identifier. - void SetRemoteId(DelegateRemoteId id) noexcept { m_state.SetRemoteId(id); } - - /// @brief Set the dispatcher instance used to send to remote - /// @param[in] dispatcher A dispatcher instance - void SetDispatcher(IDispatcher* dispatcher) { - m_state.SetDispatcher(dispatcher); - } - - /// @brief Set the serializer instance used to serialize/deserialize - /// function arguments. - /// @param[in] serializer A serializer instance - void SetSerializer(ISerializer* serializer) { - m_serializer = serializer; - } - - /// @brief Set the serialization stream used to store serialized function - /// argument data. - /// @param[in] stream An output stream. - void SetStream(dmq::xostringstream* stream) { - m_state.SetStream(stream); - } - - /// @brief Set the mutex held while serializing into and dispatching the - /// stream. Required when several delegates share one stream across threads. - /// @param[in] mutex The mutex, or nullptr for none. Caller owns it. - void SetSendMutex(dmq::Mutex* mutex) { - m_state.SetSendMutex(mutex); - } - - /// @brief Set the error handler - /// @param[in] errorHandler The delegate error handler called when - /// an error is detected. - void SetErrorHandler(const Delegate& errorHandler) { - m_state.SetErrorHandler(errorHandler); // Copy - } - - /// @brief Set the error handler - /// @param[in] errorHandler The delegate error handler called when - /// an error is detected. - void SetErrorHandler(Delegate&& errorHandler) { - m_state.SetErrorHandler(std::move(errorHandler)); // Moving the temporary - } - - /// @brief Clear the error handler - void ClearErrorHandler() { - m_state.ClearErrorHandler(); - } - - /// @brief Get the last error code - /// @return The last error detected - /// @post Error is reset to SUCCESS after call - DelegateError GetError() { - return m_state.GetError(); - } - - /// @brief Get the sequence number assigned by the dispatcher to the most - /// recent successful dispatch. - /// @return The last dispatched sequence number, or 0 if nothing has been - /// dispatched yet. - uint16_t GetLastSeqNum() const noexcept { return m_state.GetLastSeqNum(); } - -private: - /// Destination remote id, dispatcher, output stream, last error, last sequence - /// number, and error handler. Not templated on Sig/TClass — see - /// `detail::RemoteDispatchState`. - detail::RemoteDispatchState m_state; - - /// A pointer to the function argument serializer. Kept outside `m_state` since, - /// unlike everything else there, its pointee type genuinely varies by signature. - ISerializer* m_serializer = nullptr; - - // -}; - -/// @brief Creates an asynchronous delegate that binds to a free function. -/// @tparam RetType The return type of the free function. -/// @tparam Args The types of the function arguments. -/// @param[in] func A pointer to the free function to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateFreeRemote` object bound to the specified free function and id. -template -auto MakeDelegate(RetType(*func)(Args... args), DelegateRemoteId id) { - return DelegateFreeRemote(func, id); -} - -/// @brief Creates an asynchronous delegate that binds to a non-const member function. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateMemberRemote` object bound to the specified non-const member function and id. -template -auto MakeDelegate(TClass* object, RetType(TClass::* func)(Args... args), DelegateRemoteId id) { - return DelegateMemberRemote(object, func, id); -} - -/// @brief Creates an asynchronous delegate that binds to a const member function. -/// @tparam TClass The class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateMemberRemote` object bound to the specified const member function and id. -template -auto MakeDelegate(TClass* object, RetType(TClass::* func)(Args... args) const, DelegateRemoteId id) { - return DelegateMemberRemote(object, func, id); -} - -/// @brief Creates a delegate that binds to a const member function. -/// @tparam TClass The const class type that contains the const member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateMemberRemote` object bound to the specified non-const member function. -template -auto MakeDelegate(const TClass* object, RetType(TClass::* func)(Args... args) const, DelegateRemoteId id) { - return DelegateMemberRemote(object, func, id); -} - -/// @brief Creates an asynchronous delegate that binds to a non-const member function using a shared pointer. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the non-const member function of `TClass` to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateMemberRemote` shared pointer bound to the specified non-const member function and id. -template -auto MakeDelegate(std::shared_ptr object, RetVal(TClass::* func)(Args... args), DelegateRemoteId id) { - return DelegateMemberRemote(object, func, id); -} - -/// @brief Creates an asynchronous delegate that binds to a const member function using a shared pointer. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetVal The return type of the member function. -/// @tparam Args The types of the function arguments. -/// @param[in] object A shared pointer to the instance of `TClass` that will be used for the delegate. -/// @param[in] func A pointer to the const member function of `TClass` to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateMemberRemote` shared pointer bound to the specified const member function and id. -template -auto MakeDelegate(std::shared_ptr object, RetVal(TClass::* func)(Args... args) const, DelegateRemoteId id) { - return DelegateMemberRemote(object, func, id); -} - -/// @brief Creates an asynchronous delegate that binds to a `std::function`. -/// @tparam RetType The return type of the `std::function`. -/// @tparam Args The types of the function arguments. -/// @param[in] func The `std::function` to bind to the delegate. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateFunctionRemote` object bound to the specified `std::function` and id. -template -auto MakeDelegate(std::function func, DelegateRemoteId id) { - return DelegateFunctionRemote(func, id); -} - -/// @brief Creates an asynchronous delegate that binds to a raw lambda or functor. -/// @tparam F The lambda or functor type. -/// @param[in] func The lambda or functor to bind. -/// @param[in] id The delegate remote identifier. -/// @return A `DelegateFunctionRemote` object bound to the specified lambda or functor and id. -template ::value>> -auto MakeDelegate(F&& func, DelegateRemoteId id) { - using Sig = typename trait::function_traits::operator())>::function_type; - return DelegateFunctionRemote(std::forward(func), id); -} - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/DelegateSelect.h b/DelegateMQ/delegate/DelegateSelect.h deleted file mode 100644 index 55b20d4..0000000 --- a/DelegateMQ/delegate/DelegateSelect.h +++ /dev/null @@ -1,182 +0,0 @@ -#ifndef _DELEGATE_SELECT_H -#define _DELEGATE_SELECT_H - -/// @file -/// @brief Option selection: user config, port auto-detection and derived -/// DMQ_* macros. -/// -/// Preprocessor definitions only: no code, no includes beyond the user and -/// default config headers. Library .cpp files include this (not DelegateOpt.h) -/// to decide whether they compile to anything, so an unselected file adds -/// nothing to the build. DelegateOpt.h includes it first. - -// Pull in user config if provided, otherwise use library defaults. -// To provide your own config: -DDMQ_USER_CONFIG="path/to/DelegateMQConfig.h", -// or put a file named DelegateMQConfig.h on the include path and it is picked -// up automatically (define DMQ_NO_USER_CONFIG to ignore it). The config can -// select ports and options (DMQ_THREAD_*, DMQ_ALLOCATOR, ...) as well as tune -// constants, so a build without CMake needs no -D flags at all. -#ifdef DMQ_USER_CONFIG - #include DMQ_USER_CONFIG -#elif !defined(DMQ_NO_USER_CONFIG) && defined(__has_include) - #if __has_include("DelegateMQConfig.h") - #include "DelegateMQConfig.h" - #endif -#endif -#include "DelegateMQConfig_Default.h" - -// --- PLATFORM AUTO-DETECTION --- -// If no threading model is defined, attempt to auto-select a default -#if !defined(DMQ_THREAD_STDLIB) && !defined(DMQ_THREAD_WIN32) && !defined(DMQ_THREAD_POSIX) && \ - !defined(DMQ_THREAD_FREERTOS) && !defined(DMQ_THREAD_THREADX) && \ - !defined(DMQ_THREAD_ZEPHYR) && !defined(DMQ_THREAD_CMSIS_RTOS2) && \ - !defined(DMQ_THREAD_NUTTX) && \ - !defined(DMQ_THREAD_QT) && !defined(DMQ_THREAD_NONE) - - #if defined(_WIN32) || defined(__linux__) || defined(__APPLE__) || defined(__unix__) - #define DMQ_THREAD_STDLIB - #else - #define DMQ_THREAD_NONE - #endif -#endif - -// --- EMBEDDED RTOS THREAD CLASSIFICATION --- -// Named composite macros for two related but distinct "is this DMQ_THREAD_* -// an embedded RTOS port" questions, so downstream code (this file's own -// DataBus default below, extras/util/NetworkConnect.h's host-header default) -// references a name instead of each re-deriving its own copy of the -// DMQ_THREAD_* list. Adding a new DMQ_THREAD_* port means updating these two -// macros -- and Defaults.cmake's DMQ_DATABUS default, which mirrors -// DMQ_THREAD_IS_EMBEDDED_RTOS's membership and says so in its own comment -- -// not every call site that happens to care about the answer. - -// True for every embedded RTOS thread port. Used to decide whether desktop- -// oriented defaults (DataBus auto-enable, below) should apply. -#if defined(DMQ_THREAD_FREERTOS) || defined(DMQ_THREAD_THREADX) || \ - defined(DMQ_THREAD_ZEPHYR) || defined(DMQ_THREAD_CMSIS_RTOS2) || \ - defined(DMQ_THREAD_NUTTX) - #define DMQ_THREAD_IS_EMBEDDED_RTOS -#endif - -// True only for the subset of embedded RTOS thread ports whose simulator/ -// native build bundles its own network stack headers that collide with real -// host BSD/Winsock headers (e.g. Zephyr's redefining -// sockaddr_in et al.). FreeRTOS is deliberately NOT included here: its -// Win32/POSIX simulator ports (databus-freertos, freertos-linux) have no -// native network stack of their own to collide with, and use real host -// sockets on purpose. -#if defined(DMQ_THREAD_THREADX) || defined(DMQ_THREAD_ZEPHYR) || defined(DMQ_THREAD_CMSIS_RTOS2) - #define DMQ_THREAD_HAS_NATIVE_NETWORK_STACK -#endif - -// True when a real thread model is configured (desktop or embedded RTOS), -// as opposed to DMQ_THREAD_NONE or no thread model at all (bare metal, -// single-threaded). Named once here instead of hand-copying this same -// 8-macro list at every call site that needs to know whether Mutex/ -// ConditionVariable/std::thread-equivalent support exists. -#if defined(DMQ_THREAD_STDLIB) || defined(DMQ_THREAD_WIN32) || defined(DMQ_THREAD_QT) || \ - defined(DMQ_THREAD_POSIX) || \ - defined(DMQ_THREAD_FREERTOS) || defined(DMQ_THREAD_THREADX) || \ - defined(DMQ_THREAD_ZEPHYR) || defined(DMQ_THREAD_CMSIS_RTOS2) || \ - defined(DMQ_THREAD_NUTTX) - #define DMQ_HAS_THREADING -#endif - -// dmq::os::StartGate / Thread::SetStartGate() (port/os/common/StartGate.h): -// every thread port. Code also built for bare metal tests this first. -#if defined(DMQ_HAS_THREADING) - #define DMQ_HAS_START_GATE -#endif - -// If no serialization model is defined, attempt to auto-select a default -#if !defined(DMQ_SERIALIZE_SERIALIZE) && !defined(DMQ_SERIALIZE_RAPIDJSON) && \ - !defined(DMQ_SERIALIZE_MSGPACK) && !defined(DMQ_SERIALIZE_CEREAL) && \ - !defined(DMQ_SERIALIZE_BITSERY) && !defined(DMQ_SERIALIZE_NONE) - - #if defined(_WIN32) || defined(__linux__) || defined(__APPLE__) || defined(__unix__) - #define DMQ_SERIALIZE_SERIALIZE - #else - #define DMQ_SERIALIZE_NONE - #endif -#endif - -// If no transport is defined, auto-select one. Matches Defaults.cmake on -// desktop (CMake always passes a transport, so this only applies to builds -// without it). RTOS and bare-metal ports default to no transport, even when -// built as a host simulator, so host socket headers aren't pulled in. -#if !defined(DMQ_TRANSPORT_NONE) && !defined(DMQ_TRANSPORT_ZEROMQ) && \ - !defined(DMQ_TRANSPORT_NNG) && !defined(DMQ_TRANSPORT_MQTT) && \ - !defined(DMQ_TRANSPORT_WIN32_PIPE) && !defined(DMQ_TRANSPORT_WIN32_UDP) && \ - !defined(DMQ_TRANSPORT_WIN32_TCP) && !defined(DMQ_TRANSPORT_LINUX_UDP) && \ - !defined(DMQ_TRANSPORT_LINUX_UDS) && !defined(DMQ_TRANSPORT_LINUX_TCP) && \ - !defined(DMQ_TRANSPORT_SERIAL_PORT) && !defined(DMQ_TRANSPORT_ARM_LWIP_UDP) && \ - !defined(DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP) && !defined(DMQ_TRANSPORT_THREADX_UDP) && \ - !defined(DMQ_TRANSPORT_STM32_UART) && !defined(DMQ_TRANSPORT_ZEPHYR_UDP) - - #if defined(DMQ_THREAD_IS_EMBEDDED_RTOS) || !defined(DMQ_HAS_THREADING) - #define DMQ_TRANSPORT_NONE - #elif defined(_WIN32) - #define DMQ_TRANSPORT_WIN32_UDP - #elif defined(__linux__) - #define DMQ_TRANSPORT_LINUX_UDP - #else - #define DMQ_TRANSPORT_NONE - #endif -#endif - -// --- ONE OF EACH --- -// Two ports of a kind means two places picked one, typically CMake's DMQ_THREAD -// (passed with -D) and a #define in DelegateMQConfig.h. CMake then compiles one -// port's sources while the headers use another, so fail here instead. -#if (defined(DMQ_THREAD_STDLIB) + defined(DMQ_THREAD_WIN32) + defined(DMQ_THREAD_POSIX) + \ - defined(DMQ_THREAD_FREERTOS) + defined(DMQ_THREAD_THREADX) + defined(DMQ_THREAD_ZEPHYR) + \ - defined(DMQ_THREAD_CMSIS_RTOS2) + defined(DMQ_THREAD_NUTTX) + defined(DMQ_THREAD_QT) + \ - defined(DMQ_THREAD_NONE)) > 1 - #error "More than one DMQ_THREAD_* is defined. With CMake, set DMQ_THREAD in CMake only, not in DelegateMQConfig.h." -#endif -#if (defined(DMQ_SERIALIZE_SERIALIZE) + defined(DMQ_SERIALIZE_RAPIDJSON) + \ - defined(DMQ_SERIALIZE_MSGPACK) + defined(DMQ_SERIALIZE_CEREAL) + \ - defined(DMQ_SERIALIZE_BITSERY) + defined(DMQ_SERIALIZE_NONE)) > 1 - #error "More than one DMQ_SERIALIZE_* is defined. With CMake, set DMQ_SERIALIZE in CMake only, not in DelegateMQConfig.h." -#endif -#if (defined(DMQ_TRANSPORT_NONE) + defined(DMQ_TRANSPORT_ZEROMQ) + defined(DMQ_TRANSPORT_NNG) + \ - defined(DMQ_TRANSPORT_MQTT) + defined(DMQ_TRANSPORT_WIN32_PIPE) + defined(DMQ_TRANSPORT_WIN32_UDP) + \ - defined(DMQ_TRANSPORT_WIN32_TCP) + defined(DMQ_TRANSPORT_LINUX_UDP) + defined(DMQ_TRANSPORT_LINUX_UDS) + \ - defined(DMQ_TRANSPORT_LINUX_TCP) + defined(DMQ_TRANSPORT_SERIAL_PORT) + \ - defined(DMQ_TRANSPORT_ARM_LWIP_UDP) + defined(DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP) + \ - defined(DMQ_TRANSPORT_THREADX_UDP) + defined(DMQ_TRANSPORT_STM32_UART) + \ - defined(DMQ_TRANSPORT_ZEPHYR_UDP)) > 1 - #error "More than one DMQ_TRANSPORT_* is defined. With CMake, set DMQ_TRANSPORT in CMake only, not in DelegateMQConfig.h." -#endif - -// Default to DataBus ON on Desktop if not explicitly disabled. -// -// _WIN32/__linux__/__APPLE__/__unix__ reflect the compiler/host doing the -// building, not the actual target: an RTOS simulator sample (e.g. -// zephyr-linux/threadx-linux/freertos-linux) compiles with a host GCC on a -// Unix box despite targeting DMQ_THREAD_ZEPHYR/THREADX/FREERTOS, so this -// used to auto-enable DataBus for those too even without CMake in the -// picture. DataBus's NetworkConnect.h reaches for the host's own BSD -// socket headers unconditionally on Linux/macOS/Windows, which can conflict -// outright with a target's own native network stack headers (e.g. Zephyr's -// redefining sockaddr_in et al.) if the application -// also pulls those in directly (a UDP transport sample, for instance). -// DMQ_THREAD_IS_EMBEDDED_RTOS mirrors Defaults.cmake's equivalent CMake- -// level default, for projects that set these macros by hand instead of -// going through DelegateMQ.cmake. DMQ_THREAD_NONE is excluded as well, as in -// Defaults.cmake: DataBus's ThreadMonitor needs a thread port. -#if !defined(DMQ_DATABUS) && !defined(DMQ_DATABUS_OFF) && \ - !defined(DMQ_THREAD_IS_EMBEDDED_RTOS) && defined(DMQ_HAS_THREADING) - #if defined(_WIN32) || defined(__linux__) || defined(__APPLE__) || defined(__unix__) - #define DMQ_DATABUS - #endif -#endif - -// Default to DataBus Tools ON on Desktop if DataBus is active and not explicitly disabled -#if defined(DMQ_DATABUS) && !defined(DMQ_DATABUS_TOOLS) && !defined(DMQ_DATABUS_TOOLS_OFF) - #if defined(_WIN32) || defined(__linux__) || defined(__APPLE__) || defined(__unix__) - #define DMQ_DATABUS_TOOLS - #endif -#endif - -#endif // _DELEGATE_SELECT_H diff --git a/DelegateMQ/delegate/IDispatcher.h b/DelegateMQ/delegate/IDispatcher.h deleted file mode 100644 index 8029deb..0000000 --- a/DelegateMQ/delegate/IDispatcher.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef _IDISPATCHER_H -#define _IDISPATCHER_H - -/// @file -/// @brief Delegate dispatcher interface class. - -#include -#include "DelegateOpt.h" - -namespace dmq { - -// Remote identifier shared between sender and receiver remotes. -typedef uint16_t DelegateRemoteId; -const uint16_t INVALID_REMOTE_ID = static_cast(-1); -const uint16_t ACK_REMOTE_ID = 0; - -/// @TODO Implement the IDispatcher interface if necessary. -/// @brief Delegate interface class to dispatch serialized function argument data -/// to a remote destination. Implemented by the application if using remote delegates. -/// -/// @details Incoming data from the remote must the `IDispatcher::Dispatch()` to -/// invoke the target function using argument data. The argument data is serialized -/// for transport using a concrete class implementing the `ISerialzer` interface -/// allowing any data argument serialization method is supported. -/// @post The receiver calls `IRemoteInvoker::Invoke()` when the dispatched message -/// is received. -class IDispatcher -{ -public: - virtual ~IDispatcher() = default; - - /// Dispatch a stream of bytes to a remote system. The implementer is responsible - /// for sending the bytes over a communication transport (UDP, TCP, shared memory, - /// serial, ...). - /// @param[in] os An outgoing stream to send to the remote destination. - /// @param[in] id The unique delegate identifier shared between sender and receiver. - virtual int Dispatch(dmq::xostringstream& os, DelegateRemoteId id, uint16_t* outSeqNum = nullptr) = 0; -}; - -} - -#endif \ No newline at end of file diff --git a/DelegateMQ/delegate/IInvoker.h b/DelegateMQ/delegate/IInvoker.h deleted file mode 100644 index ea48368..0000000 --- a/DelegateMQ/delegate/IInvoker.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef _IINVOKER_H -#define _IINVOKER_H - -/// @file -/// @brief Delegate inter-thread invoker base class. - -#include - -namespace dmq { - -class DelegateMsg; - -/// @brief Abstract base class to support asynchronous delegate function invoke -/// on destination thread of control. Used internally by the delegate library, -/// not user application code. -class IThreadInvoker -{ -public: - virtual ~IThreadInvoker() = default; - - /// Called to invoke the bound target function by the destination thread of control. - /// @param[in] msg The incoming delegate message. - /// @return `true` if function was invoked; `false` if failed. - virtual bool Invoke(std::shared_ptr msg) = 0; -}; - -/// @brief Abstract base class to support remote delegate function invoke -/// to a remote system. Used internally by the delegate library, not -/// user application code. -class IRemoteInvoker -{ -public: - virtual ~IRemoteInvoker() = default; - - /// Called to invoke the bound target function by the remote system. - /// @param[in] is The incoming remote message stream. - /// @return `true` if function was invoked; `false` if failed. - virtual bool Invoke(std::istream& is) = 0; -}; - -} - -#endif \ No newline at end of file diff --git a/DelegateMQ/delegate/ISerializer.h b/DelegateMQ/delegate/ISerializer.h deleted file mode 100644 index 5045585..0000000 --- a/DelegateMQ/delegate/ISerializer.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef _ISERIALIZER_H -#define _ISERIALIZER_H - -/// @file ISerializer.h -/// @brief Interface for custom argument serialization/deserialization. -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. - -#include - -namespace dmq { - - template - class ISerializer; // Not defined - - /// @TODO Implement the ISerializer interface if necessary. - /// @brief Interface definition for serializing remote function arguments. - /// - /// @details - /// When using Remote Delegates, the library needs a way to turn arbitrary C++ function arguments - /// into a byte stream (for network transport) and back again. - /// - /// Users must implement this interface for the specific function signatures they intend to call - /// remotely, OR use one of the pre-defined serializers provided in `port/serialize` - /// (e.g., MessagePack, JSON, Cereal). - /// - /// @tparam RetType The return type of the function signature. - /// @tparam Args The variadic argument types of the function signature. - template - class ISerializer - { - public: - virtual ~ISerializer() = default; - - /// @brief Serializes function arguments into the output stream. - /// - /// @details - /// Called by the `DelegateRemote` when the user invokes a remote delegate. - /// The implementation must write every argument in `args` into `os`. - /// - /// @param[out] os The output stream (buffer) to write data to. - /// @param[in] args The actual arguments passed to the delegate invocation. - /// @return Reference to the output stream. - virtual std::ostream& Write(std::ostream& os, const Args&... args) = 0; - - /// @brief Deserializes data from the input stream into function arguments. - /// - /// @details - /// Called by the receiving endpoint before invoking the target function. - /// The implementation must read data from `is` and populate the references in `args`. - /// - /// @note - /// When deserializing pointer arguments like `const T*`, `args` will be a reference - /// to a `const T*` (`const T*&`). Because the object is conceptually const, writing - /// deserialized data directly to `*arg` is ill-formed. As a workaround, implementations - /// must use `const_cast(arg)` to cast away constness and write to the underlying - /// mutable storage provided by the framework, or allocate a new object if preferred. - /// - /// @param[in] is The input stream (buffer) containing received data. - /// @param[out] args References to the arguments where the data should be stored. - /// @return Reference to the input stream. - virtual std::istream& Read(std::istream& is, Args&... args) = 0; - }; -} - -#endif \ No newline at end of file diff --git a/DelegateMQ/delegate/IThread.h b/DelegateMQ/delegate/IThread.h deleted file mode 100644 index fb3069e..0000000 --- a/DelegateMQ/delegate/IThread.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef _ITHREAD_H -#define _ITHREAD_H - -/// @file IThread.h -/// @brief Interface for cross-thread delegate dispatching. -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. - -#include "DelegateMsg.h" - -namespace dmq { - -/// @TODO Implement the IThread interface if necessary. -/// @brief A base class for a delegate enabled execution thread. Implemented by -/// application code if asynchronous delegates are used. -/// -/// @details Each platform specific implementation must inherit from `IThread` -/// and provide an implementation for `DispatchDelegate()`. The `DispatchDelegate()` -/// function is called by the source thread to initiate an asynchronous function call -/// onto the destination thread of control. -class IThread -{ -public: - /// Destructor - virtual ~IThread() = default; - - /// @brief Enqueues a delegate message for execution on this thread. - /// - /// @details - /// This function is called by the *source* thread (the caller). The implementation must - /// thread-safely transfer ownership of the `msg` into the target thread's processing queue. - /// - /// Once the message is received by the target thread's main loop, that loop is responsible - /// for calling `IInvoker::Invoke(msg)` to actually execute the function. - /// - /// @param[in] msg A shared pointer to the delegate message. This pointer must remain valid - /// until the target thread finishes execution. - /// @return true if the message was successfully enqueued, false otherwise. - virtual bool DispatchDelegate(std::shared_ptr msg) = 0; - - /// @brief Returns true if the calling thread is this thread. - /// Used to decide whether to marshal an event or execute inline. - virtual bool IsCurrentThread() = 0; -}; - -/// @brief Registers `thread` as the calling thread's dmq::ThisThread::GetCurrent() -/// for the lifetime of this object, restoring the previous value when destroyed. -/// -/// @details An IThread implementation creates one on its worker thread at the top -/// of its worker loop, so code running there can find the thread it runs on. A -/// custom IThread does the same to be found by GetCurrent(). Does nothing on ports -/// without current-thread storage (GetCurrent() then always returns nullptr). -class CurrentThreadScope -{ -public: - explicit CurrentThreadScope(IThread* thread) noexcept : m_prev(ThisThread::SetCurrent(thread)) {} - ~CurrentThreadScope() { ThisThread::SetCurrent(m_prev); } - - CurrentThreadScope(const CurrentThreadScope&) = delete; - CurrentThreadScope& operator=(const CurrentThreadScope&) = delete; - -private: - IThread* m_prev; -}; - -} - -#endif diff --git a/DelegateMQ/delegate/MulticastDelegate.h b/DelegateMQ/delegate/MulticastDelegate.h deleted file mode 100644 index 2abe74a..0000000 --- a/DelegateMQ/delegate/MulticastDelegate.h +++ /dev/null @@ -1,326 +0,0 @@ -#ifndef _MULTICAST_DELEGATE_H -#define _MULTICAST_DELEGATE_H - -/// @file -/// @brief Delegate container for storing and iterating over a collection of -/// delegate instances. Supports reentrant removal during invocation. -/// Class is not thread-safe. - -#include "Delegate.h" -#include -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -template -class MulticastDelegate; // Not defined - -namespace detail { - -/// @brief Clone `delegate` and append it to `delegates`, fully erased to the -/// non-templated `DelegateBase` at construction. `delegate.Clone()` is called -/// through a `const DelegateBase&`, so its return type here is `DelegateBase*` -/// (not the more-derived leaf type) -- the resulting shared_ptr control block -/// is therefore not templated on RetType/Args, and is shared by every -/// `MulticastDelegate` in the program instead of duplicated per signature. -/// Templated only on nothing at all (a plain function): none of this logic -/// depends on the owning container's signature. -/// @param[in,out] delegates The list to append to. -/// @param[in] delegate The delegate to clone and store. -inline void MulticastPushBack(xlist>& delegates, const DelegateBase& delegate) { - auto delegateClone = delegate.Clone(); - if (!delegateClone) - BAD_ALLOC(); - -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // No exceptions: Direct execution. - // If shared_ptr or vector allocation fails here on embedded, - // standard behavior is usually an abort() or system reset. - std::shared_ptr sharedDelegate(delegateClone, std::default_delete(), ::dmq::stl_allocator()); - delegates.push_back(std::forward>(sharedDelegate)); -#else - // Exceptions enabled: Safe to try-catch. - try { - std::shared_ptr sharedDelegate(delegateClone, std::default_delete(), ::dmq::stl_allocator()); - delegates.push_back(std::forward>(sharedDelegate)); - } - catch (const std::bad_alloc&) { - BAD_ALLOC(); - } -#endif -} - -/// @brief Remove `delegate` from `delegates`, respecting reentrant removal -/// during an active broadcast. -/// @param[in,out] delegates The list to remove from. -/// @param[in] broadcastCount The owning container's current broadcast nesting depth. -/// @param[out] cleanup Set to `true` if a lazy null-removal is needed later. -/// @param[in] delegate The delegate to remove. -inline void MulticastRemove(xlist>& delegates, int broadcastCount, bool& cleanup, const DelegateBase& delegate) { - auto it = std::find_if(delegates.begin(), delegates.end(), - [&delegate](const std::shared_ptr& item) { - // Must check if item is valid before comparing! - return item && (*item == delegate); - }); - - if (it != delegates.end()) { - if (broadcastCount > 0) { - // REENTRANCY DETECTED: - // Do not erase(). Just null out the pointer. - // The iterator in operator() stays valid, but next access sees null. - it->reset(); - cleanup = true; - } - else { - // Safe to erase immediately - delegates.erase(it); - } - } -} - -/// @brief Remove all delegates from `delegates`, respecting reentrant removal. -inline void MulticastClear(xlist>& delegates, int broadcastCount, bool& cleanup) { - if (broadcastCount > 0) { - for (auto& delegate : delegates) { - delegate.reset(); - } - cleanup = true; - } - else { - delegates.clear(); - } -} - -/// @brief Deep-copy every delegate in `src` (cloned, fully erased to -/// `DelegateBase`) into `dest`. -inline void MulticastCopyFrom(xlist>& dest, const xlist>& src) { - for (auto& delegate : src) { - if (!delegate) continue; - auto delegateClone = delegate->Clone(); - if (!delegateClone) - BAD_ALLOC(); - -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // No exceptions: Direct execution. - std::shared_ptr sharedDelegate(delegateClone, std::default_delete(), ::dmq::stl_allocator()); - dest.push_back(sharedDelegate); -#else - // Exceptions enabled: Safe to try-catch. - try { - std::shared_ptr sharedDelegate(delegateClone, std::default_delete(), ::dmq::stl_allocator()); - dest.push_back(sharedDelegate); - } - catch (const std::bad_alloc&) { - BAD_ALLOC(); - } -#endif - } -} - -/// @brief Move every element of `src` onto the end of `dest`, then clear `src`. -/// Used by the reentrant branch of move-assignment, which must keep `dest`'s -/// own list object identity stable (an active broadcast's iterator into it may -/// be live) rather than replacing it outright. -inline void MulticastAppendAndClear(xlist>& dest, xlist>& src) { - for (auto& delegate : src) { - dest.push_back(std::move(delegate)); - } - src.clear(); -} - -/// @brief RAII guard marking an active broadcast. Increments `cnt` on -/// construction, decrements on destruction, and purges lazily-nulled entries -/// from `delegates` once the outermost nested broadcast finishes. Takes plain -/// references to the exact fields it needs rather than a container pointer, -/// so it carries no dependency on RetType/Args at all. -class BroadcastGuard { -public: - BroadcastGuard(int& cnt, xlist>& delegates, bool& cleanup) - : m_cnt(cnt), m_delegates(delegates), m_cleanup(cleanup) { - m_cnt++; // Lock - } - ~BroadcastGuard() { - m_cnt--; // Unlock - if (m_cnt == 0 && m_cleanup) { - // Efficiently remove all null pointers from the list - m_delegates.remove_if([](const std::shared_ptr& item) { - return item == nullptr; - }); - m_cleanup = false; - } - } -private: - int& m_cnt; - xlist>& m_delegates; - bool& m_cleanup; -}; - -} // namespace detail - -/// @brief Not thread-safe multicast delegate container class. The class has a list of -/// `Delegate<>` instances. When invoked, each `Delegate` instance within the invocation -/// list is called. The broadcast iterates over the live list; if a delegate is removed -/// during a broadcast, its current execution finishes safely but it is removed from the list. -/// If a new delegate is added during a broadcast, it may be invoked in the current pass. -/// @note The subscriber list is stored as `shared_ptr` rather than -/// `shared_ptr>` so that `xlist`'s instantiation (and all its -/// member functions) is shared across every `MulticastDelegate` in the program instead -/// of being duplicated once per signature. The bookkeeping operations on that list -/// (`PushBack`/`Remove`/`Clear`/copy/the broadcast-nesting guard) are likewise implemented as -/// plain, non-templated `detail::Multicast*` functions/`detail::BroadcastGuard` above, for the -/// same reason -- their bodies never touch `RetType`/`Args` either. Only `operator()`, which -/// must actually invoke the bound function, needs the concrete `DelegateType` back. -template -class MulticastDelegate -{ -public: - using DelegateType = Delegate; - - MulticastDelegate() = default; - virtual ~MulticastDelegate() { Clear(); } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - MulticastDelegate(const MulticastDelegate& rhs) { detail::MulticastCopyFrom(m_delegates, rhs.m_delegates); } - - /// @brief Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - MulticastDelegate(MulticastDelegate&& rhs) noexcept : m_delegates(std::move(rhs.m_delegates)) { } - - /// Constructor to initialize from a single Delegate (Copy) - MulticastDelegate(const DelegateType& d) { - PushBack(d); - } - - /// Constructor to initialize from a single Delegate (Move) - MulticastDelegate(DelegateType&& d) { - PushBack(d); - } - - /// Invoke all bound target functions. Safe to remove delegates during invocation. - /// A void return value is used since multiple targets invoked. - /// @param[in] args The arguments used when invoking the target functions - void operator()(Args... args) { - // RAII Guard: Increments now, Decrements + Cleans up on return/throw - detail::BroadcastGuard guard(m_broadcastCount, m_delegates, m_cleanup); - - // Iterate safely - for (auto it = m_delegates.begin(); it != m_delegates.end(); ++it) { - std::shared_ptr delegate = *it; // Copy to prevent UAF if removed mid-invocation - if (delegate) { - (*static_cast(delegate.get()))(args...); - } - } - } - - /// Invoke all bound target functions. A void return value is used - /// since multiple targets invoked. - /// @param[in] args The arguments used when invoking the target functions - void Broadcast(Args... args) { - (*this)(args...); - } - - /// Insert a delegate into the container. - /// @param[in] delegate A delegate target to insert - void operator+=(const DelegateType& delegate) { PushBack(delegate); } - - /// Insert a delegate into the container. - /// @param[in] delegate A delegate target to insert - void operator+=(DelegateType&& delegate) { PushBack(delegate); } - - /// Remove a delegate from the container. - /// @param[in] delegate A delegate target to remove - void operator-=(const DelegateType& delegate) { Remove(delegate); } - - /// Remove a delegate from the container. - /// @param[in] delegate A delegate target to remove - void operator-=(DelegateType&& delegate) { Remove(delegate); } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - MulticastDelegate& operator=(const MulticastDelegate& rhs) { - if (&rhs != this) { - Clear(); - detail::MulticastCopyFrom(m_delegates, rhs.m_delegates); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - MulticastDelegate& operator=(MulticastDelegate&& rhs) noexcept { - if (&rhs != this) { - if (m_broadcastCount > 0) { - // Reentrant: a callback is reassigning the container it's currently - // broadcasting from. Clear() only nulls existing entries in this case, - // leaving m_delegates itself intact so the active iterator in operator() - // stays valid. Append rhs's delegates rather than replacing the - // container outright; stale nulls are purged after the broadcast ends. - Clear(); - detail::MulticastAppendAndClear(m_delegates, rhs.m_delegates); - } - else { - Clear(); - m_delegates = std::move(rhs.m_delegates); - } - } - return *this; - } - - /// @brief Clear the all target functions. - virtual void operator=(std::nullptr_t) noexcept { Clear(); } - - /// Insert a delegate into the container. - /// @param[in] delegate A delegate target to insert - void PushBack(const DelegateType& delegate) { - detail::MulticastPushBack(m_delegates, delegate); - } - - /// Remove a delegate into the container. - /// @param[in] delegate The delegate target to remove. - void Remove(const DelegateType& delegate) { - detail::MulticastRemove(m_delegates, m_broadcastCount, m_cleanup, delegate); - } - - /// Any registered delegates? - /// @return `true` if delegate container is empty. - bool Empty() const { return m_delegates.empty(); } - - /// Removal all registered delegates. - void Clear() { - detail::MulticastClear(m_delegates, m_broadcastCount, m_cleanup); - } - - /// Get the number of delegates stored. - /// @return The number of delegates stored. - std::size_t Size() const { return m_delegates.size(); } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the container is not empty, `false` if the container is empty. - explicit operator bool() const { return !Empty(); } - -protected: - /// List of registered delegates. Stored as `DelegateBase` (not `DelegateType`) so this - /// `xlist` instantiation, and every member function on it, is shared across all - /// `MulticastDelegate` signatures instead of being duplicated per signature. - xlist> m_delegates; - - /// Count of active nested broadcasts - int m_broadcastCount = 0; - - /// Flag for handling lazy delete - bool m_cleanup = false; -}; - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/MulticastDelegateSafe.h b/DelegateMQ/delegate/MulticastDelegateSafe.h deleted file mode 100644 index 3643b0b..0000000 --- a/DelegateMQ/delegate/MulticastDelegateSafe.h +++ /dev/null @@ -1,248 +0,0 @@ -#ifndef _MULTICAST_DELEGATE_SAFE_H -#define _MULTICAST_DELEGATE_SAFE_H - -/// @file -/// @brief Delegate container for storing and iterating over a collection of -/// delegate instances. Class is thread-safe. -/// -/// @note Invocation snapshots the delegates and calls them after releasing the -/// lock, so a delegate removed on one thread may still be called once by an -/// invocation already in progress on another. Removal does not make the target -/// safe to destroy by itself; see the note in Signal.h. - -#include "MulticastDelegate.h" -#include -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -template -class MulticastDelegateSafe; // Not defined - -namespace detail { - -/// @brief Lock-protected wrapper around `MulticastPushBack` (MulticastDelegate.h). -/// Non-templated: none of this depends on the owning container's signature. -inline void MulticastSafePushBack(xlist>& delegates, RecursiveMutex& lock, const DelegateBase& delegate) { - const dmq::LockGuard g(lock); - MulticastPushBack(delegates, delegate); -} - -/// @brief Lock-protected wrapper around `MulticastRemove`. -inline void MulticastSafeRemove(xlist>& delegates, int broadcastCount, bool& cleanup, RecursiveMutex& lock, const DelegateBase& delegate) { - const dmq::LockGuard g(lock); - MulticastRemove(delegates, broadcastCount, cleanup, delegate); -} - -/// @brief Lock-protected wrapper around `MulticastClear`. -inline void MulticastSafeClear(xlist>& delegates, int broadcastCount, bool& cleanup, RecursiveMutex& lock) { - const dmq::LockGuard g(lock); - MulticastClear(delegates, broadcastCount, cleanup); -} - -/// @brief Lock-protected emptiness check. -inline bool MulticastSafeEmpty(const xlist>& delegates, RecursiveMutex& lock) { - const dmq::LockGuard g(lock); - return delegates.empty(); -} - -/// @brief Lock-protected size check. -inline size_t MulticastSafeSize(const xlist>& delegates, RecursiveMutex& lock) { - const dmq::LockGuard g(lock); - return delegates.size(); -} - -/// @brief Snapshot the current delegate list under lock, into `smallBuf` (up to -/// `smallCap` entries) or `largeBuf` if there are more than `smallCap`. Returns -/// the number of delegates snapshotted. The lock is released before returning, -/// so the caller can invoke each delegate without holding it (see the comment -/// on `MulticastDelegateSafe::operator()` for why). Non-templated: entirely -/// independent of the owning container's signature. -inline size_t MulticastSafeSnapshot(xlist>& delegates, RecursiveMutex& lock, - std::shared_ptr* smallBuf, size_t smallCap, xlist>& largeBuf) { - const dmq::LockGuard g(lock); - size_t count = delegates.size(); - if (count <= smallCap) { - std::copy(delegates.begin(), delegates.end(), smallBuf); - } else { - largeBuf = delegates; - } - return count; -} - -} // namespace detail - -/// @brief Thread-safe multicast delegate container class. -template -class MulticastDelegateSafe : public MulticastDelegate -{ -public: - using DelegateType = Delegate; - using BaseType = MulticastDelegate; - - MulticastDelegateSafe() = default; - virtual ~MulticastDelegateSafe() = default; - - MulticastDelegateSafe(const MulticastDelegateSafe& rhs) : BaseType() { - dmq::ScopedLock lock(m_lock, rhs.m_lock); - BaseType::operator=(rhs); - } - - MulticastDelegateSafe(MulticastDelegateSafe&& rhs) : BaseType() { - dmq::ScopedLock lock(m_lock, rhs.m_lock); - BaseType::operator=(std::move(rhs)); - } - - /// Constructor to initialize from a single Delegate (Copy) - MulticastDelegateSafe(const DelegateType& d) { - this->PushBack(d); - } - - /// Constructor to initialize from a single Delegate (Move) - MulticastDelegateSafe(DelegateType&& d) { - this->PushBack(std::move(d)); - } - - /// Invoke the bound target function for all stored delegate instances. - /// A void return value is used since multiple targets invoked. - /// @param[in] args The arguments used when invoking the target functions - void operator()(Args... args) { - // To prevent deadlocks, the mutex must be released before invoking the - // delegate. Circular lock dependencies can occur if the delegate target - // function itself attempts to acquire a lock that is held by the - // thread invoking the delegate. - // Use a small-buffer optimization to avoid heap allocation in the common case. - // Buffers hold `DelegateBase` (not `DelegateType`) so this `xlist` instantiation - // is shared across every `MulticastDelegateSafe` signature; only the final - // invoke below needs the concrete `DelegateType` back. The snapshot-under-lock - // logic itself lives in `detail::MulticastSafeSnapshot` for the same reason. - std::array, SIGNAL_SBO_COUNT> small_buf; - xlist> large_buf; - size_t count = detail::MulticastSafeSnapshot(this->m_delegates, m_lock, small_buf.data(), SIGNAL_SBO_COUNT, large_buf); - - if (count <= SIGNAL_SBO_COUNT) { - for (size_t i = 0; i < count; ++i) { - if (small_buf[i]) - (*static_cast(small_buf[i].get()))(args...); - small_buf[i].reset(); // Clear to release shared_ptr immediately - } - } else { - for (auto& d : large_buf) { - if (d) - (*static_cast(d.get()))(args...); - } - } - } - - /// Invoke all bound target functions. A void return value is used - /// since multiple targets invoked. - /// @param[in] args The arguments used when invoking the target functions - void Broadcast(Args... args) { - operator()(args...); - } - - /// Insert a delegate into the container. - /// @param[in] delegate A delegate target to insert - void operator+=(const Delegate& delegate) { - const dmq::LockGuard lock(m_lock); - BaseType::operator +=(delegate); - } - - /// Insert a delegate into the container. - /// @param[in] delegate A delegate target to insert - void operator+=(Delegate&& delegate) { - const dmq::LockGuard lock(m_lock); - BaseType::operator +=(delegate); - } - - /// Remove a delegate from the container. - /// @param[in] delegate A delegate target to remove - void operator-=(const Delegate& delegate) { - const dmq::LockGuard lock(m_lock); - BaseType::operator -=(delegate); - } - - /// Remove a delegate from the container. - /// @param[in] delegate A delegate target to remove - void operator-=(Delegate&& delegate) { - const dmq::LockGuard lock(m_lock); - BaseType::operator -=(delegate); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - MulticastDelegateSafe& operator=(const MulticastDelegateSafe& rhs) { - if (this != &rhs) { - // Lock both instances safely to prevent modification of source during copy - dmq::ScopedLock lock(m_lock, rhs.m_lock); - BaseType::operator=(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - MulticastDelegateSafe& operator=(MulticastDelegateSafe&& rhs) noexcept { - if (this != &rhs) { - dmq::ScopedLock lock(m_lock, rhs.m_lock); - BaseType::operator=(std::move(rhs)); - } - return *this; - } - - /// @brief Clear the all target functions. - virtual void operator=(std::nullptr_t) noexcept { - const dmq::LockGuard lock(m_lock); - BaseType::Clear(); - } - - /// Insert a delegate into the container. - /// @param[in] delegate A delegate target to insert - void PushBack(const DelegateType& delegate) { - detail::MulticastSafePushBack(this->m_delegates, m_lock, delegate); - } - - /// Remove a delegate into the container. - /// @param[in] delegate The delegate target to remove. - void Remove(const DelegateType& delegate) { - detail::MulticastSafeRemove(this->m_delegates, this->m_broadcastCount, this->m_cleanup, m_lock, delegate); - } - - /// Any registered delegates? - /// @return `true` if delegate container is empty. - bool Empty() const { - return detail::MulticastSafeEmpty(this->m_delegates, m_lock); - } - - /// Removal all registered delegates. - void Clear() { - detail::MulticastSafeClear(this->m_delegates, this->m_broadcastCount, this->m_cleanup, m_lock); - } - - /// Get the number of delegates stored. - /// @return The number of delegates stored. - std::size_t Size() const { - return detail::MulticastSafeSize(this->m_delegates, m_lock); - } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the container is not empty, `false` if the container is empty. - explicit operator bool() const { - const dmq::LockGuard lock(m_lock); - return BaseType::operator bool(); - } - -private: - /// Lock to make the class thread-safe - mutable RecursiveMutex m_lock; -}; - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/Semaphore.h b/DelegateMQ/delegate/Semaphore.h deleted file mode 100644 index ee1c4a9..0000000 --- a/DelegateMQ/delegate/Semaphore.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef _DELEGATE_SEMAPHORE_H -#define _DELEGATE_SEMAPHORE_H - -/// @file -/// @brief Delegate library semaphore wrapper class. -/// -/// dmq::Semaphore is available (DMQ_HAS_SEMAPHORE) on every port except -/// bare metal. On stdlib/Win32/Qt, FreeRTOS, and ThreadX (DMQ_HAS_CV -- -/// these have a real dmq::ConditionVariable) it's the generic class -/// defined below, built from dmq::ConditionVariable + dmq::Mutex. On -/// Zephyr and CMSIS-RTOS2 (no ConditionVariable port) DelegateOpt.h -/// already resolves dmq::Semaphore to a port-native implementation -/// instead (ZephyrSemaphore / CmsisRtos2Semaphore) -- nothing more to -/// define here for those two. - -#include "DelegateOpt.h" - -#ifdef DMQ_HAS_SEMAPHORE - -// Fix compiler error on Windows -#undef max - -#ifdef DMQ_HAS_CV - -namespace dmq { - -/// @brief A semaphore wrapper class. -class Semaphore -{ -public: - Semaphore() = default; - ~Semaphore() = default; - - /// Called to wait on a semaphore to be signaled. - /// @param[in] timeout - semaphore timeout - /// @return Return true if semaphore signaled, false if timeout occurred. - bool Wait(Duration timeout) - { - dmq::UniqueLock lk(m_lock); - if (timeout == Duration::max()) - { - m_sema.wait(lk, [this] { return m_signaled; }); - } - else - { - if (!m_sema.wait_for(lk, timeout, [this] { return m_signaled; })) - { - return false; // Timeout occurred - } - } - - if (m_signaled) - { - m_signaled = false; - return true; - } - else - { - return false; - } - } - - /// Called to signal a semaphore. - void Signal() - { - { - dmq::UniqueLock lk(m_lock); - m_signaled = true; - } - m_sema.notify_one(); - } - -private: - // Prevent copying objects - Semaphore(const Semaphore&) = delete; - Semaphore& operator=(const Semaphore&) = delete; - - dmq::ConditionVariable m_sema; - dmq::Mutex m_lock; - bool m_signaled = false; -}; - -} - -#endif // DMQ_HAS_CV - -#endif // DMQ_HAS_SEMAPHORE - -#endif diff --git a/DelegateMQ/delegate/Signal.h b/DelegateMQ/delegate/Signal.h deleted file mode 100644 index 09b6fab..0000000 --- a/DelegateMQ/delegate/Signal.h +++ /dev/null @@ -1,395 +0,0 @@ -#ifndef SIGNAL_H -#define SIGNAL_H - -/// @file Signal.h -/// @brief Thread-safe Signal/slot with RAII connection handles; no allocation requirement. -/// -/// @details `Signal` is a thread-safe multicast delegate container that returns RAII -/// `ScopedConnection` handles from `Connect()`. Key properties: -/// -/// * **No allocation requirement** — Signal may live on the stack, as a class member, or on -/// the heap without restriction. -/// * **Thread-safe** — concurrent Connect/Disconnect/operator() calls are all safe. -/// * **Lifetime-safe disconnect** — calling `Disconnect()` (or letting a `ScopedConnection` -/// go out of scope) after the Signal is destroyed is always a safe no-op. -/// -/// **A slot can still run after `Disconnect()` returns.** Disconnect removes the slot from -/// the list, but it does not wait for a call that has already started: `operator()` takes -/// a snapshot of the slots under the lock and invokes them after releasing it (so a slot may -/// itself Connect/Disconnect/emit without deadlocking). If thread A is emitting while -/// thread B disconnects, A can still invoke the slot once, after B's `Disconnect()` has -/// returned. Separately, for an asynchronous delegate (`MakeDelegate(..., thread)`), a -/// message already queued on the target thread still runs after the disconnect. -/// -/// So when Signal is used across threads, disconnecting is not by itself enough to make -/// the slot's target safe to destroy. The owner must also guard its own lifetime, for -/// example: route the slot through a shared flag/mutex it closes before destruction (the -/// slot checks it under the lock and returns if closed), and for async delegates drain or -/// exit the target thread (`ExitThread()`) before destroying what its messages target. -/// Single-threaded use (connect, emit and disconnect on one thread) needs none of this. -/// -/// Internally, Signal stores its subscriber list in a heap-allocated `State` block. Each -/// `Connection` holds two `shared_ptr` context fields (state and delegate copy) plus -/// a raw `DisconnectImpl` function pointer. The destructor marks the block dead under the -/// mutex, so any concurrent disconnect that races with destruction simply sees the dead flag -/// and returns without touching the list. - -#include "DelegateOpt.h" -#include "Delegate.h" -#include -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -template -class UnicastDelegate; - -template -class Signal; - -// --------------------------------------------------------------------------- -// detail::Connection (implementation detail — use ScopedConnection) -// --------------------------------------------------------------------------- -namespace detail { - -/// @brief Move-only subscription token. Internal implementation detail of Signal. -/// Users should store `ScopedConnection`, not `Connection` directly. -/// -/// Stores two type-erased `shared_ptr` contexts (signal state and delegate copy) -/// plus a raw `DisconnectFn` function pointer. No `std::function` heap allocation. -class Connection { -public: - using DisconnectFn = void(*)(const std::shared_ptr&, const std::shared_ptr&); - - Connection() = default; - - Connection(std::shared_ptr ctx1, std::shared_ptr ctx2, DisconnectFn fn) noexcept - : m_ctx1(std::move(ctx1)) - , m_ctx2(std::move(ctx2)) - , m_disconnect_fn(fn) - , m_connected(true) {} - - Connection(const Connection&) = delete; - Connection& operator=(const Connection&) = delete; - - Connection(Connection&& other) noexcept - : m_ctx1(std::move(other.m_ctx1)) - , m_ctx2(std::move(other.m_ctx2)) - , m_disconnect_fn(other.m_disconnect_fn) - , m_connected(other.m_connected) { - other.m_connected = false; - other.m_disconnect_fn = nullptr; - } - - Connection& operator=(Connection&& other) noexcept { - if (this != &other) { - Disconnect(); - m_ctx1 = std::move(other.m_ctx1); - m_ctx2 = std::move(other.m_ctx2); - m_disconnect_fn = other.m_disconnect_fn; - m_connected = other.m_connected; - other.m_connected = false; - other.m_disconnect_fn = nullptr; - } - return *this; - } - - ~Connection() {} - - bool IsConnected() const { return m_connected; } - - void Disconnect() { - if (!m_connected) return; - if (m_disconnect_fn) - m_disconnect_fn(m_ctx1, m_ctx2); - m_ctx1.reset(); - m_ctx2.reset(); - m_disconnect_fn = nullptr; - m_connected = false; - } - -private: - std::shared_ptr m_ctx1; - std::shared_ptr m_ctx2; - DisconnectFn m_disconnect_fn = nullptr; - bool m_connected = false; - XALLOCATOR -}; - -} // namespace detail - -// --------------------------------------------------------------------------- -// ScopedConnection -// --------------------------------------------------------------------------- - -/// @brief RAII handle to a single Signal subscription. Disconnects automatically -/// on destruction. The only connection type users need to store. -/// -/// @note Disconnecting does not wait for a call already in progress on another -/// thread, or for an async delegate message already queued; see the Signal.h file -/// comment before destroying a slot's target right after disconnecting. -/// -/// @code -/// dmq::ScopedConnection conn = mySignal.Connect(MakeDelegate(...)); -/// // conn goes out of scope -> automatically disconnected -/// @endcode -class ScopedConnection { -public: - ScopedConnection() = default; - explicit ScopedConnection(detail::Connection&& conn) : m_connection(std::move(conn)) {} - ~ScopedConnection() { m_connection.Disconnect(); } - - ScopedConnection(ScopedConnection&& other) noexcept - : m_connection(std::move(other.m_connection)) {} - - ScopedConnection& operator=(ScopedConnection&& other) noexcept { - if (this != &other) { - m_connection.Disconnect(); - m_connection = std::move(other.m_connection); - } - return *this; - } - - ScopedConnection(const ScopedConnection&) = delete; - ScopedConnection& operator=(const ScopedConnection&) = delete; - - void Disconnect() { m_connection.Disconnect(); } - bool IsConnected() const { return m_connection.IsConnected(); } - -private: - detail::Connection m_connection; - XALLOCATOR -}; - -// --------------------------------------------------------------------------- -// detail::Signal* helpers (implementation detail of Signal, defined here so -// they can construct/return ScopedConnection) -// --------------------------------------------------------------------------- -namespace detail { - -/// @brief Non-templated: the mutex + alive-flag + delegate list shared by every -/// `Signal` in the program. Hoisted out of `Signal` (where it lived as -/// a nested `State` struct) because nesting inside the class template caused a -/// separate (byte-identical) type -- and critically a separate `xmake_shared` -/// allocation control block -- to be generated per signature, even though none -/// of its members depend on RetType/Args. -struct SignalState { - mutable RecursiveMutex mtx; - bool alive = true; - xlist> delegates; - XALLOCATOR -}; - -/// @brief Non-templated: a snapshot of a signal's subscriber list at a point in -/// time, captured under lock so `operator()` can invoke without holding it. -struct SignalSnapshot { - std::array, SIGNAL_SBO_COUNT> small_buf; - xlist> large_buf; - size_t count = 0; -}; - -/// @brief Identity-based disconnect: removes `copyVoid` (the exact shared_ptr -/// instance stored at Connect() time) from `stateVoid`'s delegate list, if the -/// state is still alive. Non-templated: this never needed the concrete -/// `DelegateType` to begin with, but as a member of `Signal` it used to be -/// emitted once per signature anyway. -inline void SignalDisconnectImpl(const std::shared_ptr& stateVoid, const std::shared_ptr& copyVoid) { - auto* state = static_cast(stateVoid.get()); - auto copy = std::static_pointer_cast(copyVoid); - dmq::LockGuard lock(state->mtx); - if (state->alive) - state->delegates.remove(copy); -} - -/// @brief Clone `delegate` and append it to `state`'s list under lock, returning -/// a connection handle wired to `SignalDisconnectImpl`. `delegate` is taken as -/// `const DelegateBase&` (rather than the more-derived `Delegate&`) so -/// `delegate.Clone()`'s return type here is `DelegateBase*` -- the resulting -/// shared_ptr control block is therefore not templated on RetType/Args, and is -/// shared by every `Signal` in the program instead of duplicated per -/// signature (mirrors the fix already applied to `MulticastDelegate::PushBack`). -inline ScopedConnection SignalConnect(std::shared_ptr& state, RecursiveMutex& mutex, const DelegateBase& delegate) { - auto copy = std::shared_ptr(delegate.Clone(), std::default_delete(), ::dmq::stl_allocator()); - if (!copy) - BAD_ALLOC(); - - dmq::LockGuard lock(mutex); - dmq::LockGuard stateLock(state->mtx); - state->delegates.push_back(copy); - - return ScopedConnection(Connection( - std::static_pointer_cast(state), - std::static_pointer_cast(copy), - &SignalDisconnectImpl - )); -} - -/// @brief Capture a snapshot of `state`'s current delegate list under lock. -inline SignalSnapshot SignalGetSnapshot(const std::shared_ptr& state, RecursiveMutex& mutex) { - dmq::LockGuard lock(mutex); - dmq::LockGuard stateLock(state->mtx); - - SignalSnapshot s; - s.count = state->delegates.size(); - if (s.count <= SIGNAL_SBO_COUNT) { - size_t i = 0; - for (auto& d : state->delegates) { -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" -#endif - s.small_buf[i++] = d; -#if defined(__clang__) -#pragma clang diagnostic pop -#endif - } - } else { - s.large_buf = state->delegates; - } - return s; -} - -/// @brief Disconnect all subscribers: swap in a fresh `SignalState`, mark the -/// old one dead+cleared under its own lock. Used by `Signal::Clear()`. -inline void SignalClear(std::shared_ptr& state, RecursiveMutex& mutex) { - std::shared_ptr oldState; - { - dmq::LockGuard lock(mutex); - oldState = state; - state = xmake_shared(); - } - { - dmq::LockGuard lock(oldState->mtx); - oldState->alive = false; - oldState->delegates.clear(); - } -} - -/// @brief Mark `state` dead and clear its list under lock. Used by `~Signal()` -/// -- unlike `SignalClear`, does not swap in a replacement state, since the -/// owning Signal is being destroyed rather than reset for reuse. -inline void SignalMarkDead(std::shared_ptr& state, RecursiveMutex& mutex) { - dmq::LockGuard lock(mutex); - dmq::LockGuard stateLock(state->mtx); - state->alive = false; - state->delegates.clear(); -} - -/// @brief Lock-protected subscriber count. -inline size_t SignalSize(const std::shared_ptr& state, RecursiveMutex& mutex) { - dmq::LockGuard lock(mutex); - dmq::LockGuard stateLock(state->mtx); - return state->delegates.size(); -} - -} // namespace detail - -// --------------------------------------------------------------------------- -// Signal -// --------------------------------------------------------------------------- - -/// @brief Thread-safe multicast delegate returning RAII connection handles. -/// @details May be instantiated on the stack, as a class member, or on the heap. -/// `Signal` is the single signal type in the library. -template -class Signal -{ -public: - using DelegateType = Delegate; - - /// @brief Snapshot of the subscriber list at a point in time. Alias for the - /// non-templated `detail::SignalSnapshot` -- kept as a nested name here since - /// external code (e.g. `extras/util/Timer.cpp`) names it as `Signal::Snapshot`. - using Snapshot = detail::SignalSnapshot; - - Signal() = default; - - ~Signal() { - // Mark the shared state dead under the lock. Any concurrent Disconnect() - // that races with this will either complete its removal first (holding the - // lock) or see alive=false and skip removal. Either way, no UAF. - detail::SignalMarkDead(m_state, m_mutex); - } - - Signal(const Signal&) = delete; - Signal& operator=(const Signal&) = delete; - Signal(Signal&&) = delete; - Signal& operator=(Signal&&) = delete; - - /// @brief Subscribe a delegate and return a RAII connection handle. - /// @details The returned `ScopedConnection` automatically disconnects on - /// scope exit. Safe to call regardless of how the Signal was allocated. - /// @return A `ScopedConnection`. Let it go out of scope to auto-disconnect, - /// or call `Disconnect()` manually. - [[nodiscard]] ScopedConnection Connect(const DelegateType& delegate) { - return detail::SignalConnect(m_state, m_mutex, delegate); - } - - /// @brief Subscribe a UnicastDelegate and return a RAII connection handle. - [[nodiscard]] ScopedConnection Connect(const UnicastDelegate& delegate) { - if (delegate.GetDelegate()) - return Connect(*delegate.GetDelegate()); - return {}; - } - - /// @brief Invoke all connected delegates. - void operator()(Args... args) { - auto snapshot = GetSnapshot(); - InvokeSnapshot(snapshot, std::forward(args)...); - } - - /// @brief Capture a snapshot of all current subscribers. - /// @details The snapshot holds shared_ptrs to the delegates, ensuring they - /// stay alive even if the Signal is destroyed. - Snapshot GetSnapshot() const { - return detail::SignalGetSnapshot(m_state, m_mutex); - } - - /// @brief Invoke a previously captured snapshot of delegates. - static void InvokeSnapshot(const Snapshot& s, Args... args) { - if (s.count <= SIGNAL_SBO_COUNT) { - for (size_t i = 0; i < s.count; ++i) { -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" -#endif - if (s.small_buf[i]) - (*static_cast(s.small_buf[i].get()))(args...); -#if defined(__clang__) -#pragma clang diagnostic pop -#endif - } - } else { - for (auto& d : s.large_buf) { - if (d) - (*static_cast(d.get()))(args...); - } - } - } - - /// @brief Number of currently connected subscribers. - std::size_t Size() const { - return detail::SignalSize(m_state, m_mutex); - } - - bool Empty() const { return Size() == 0; } - - /// @brief Disconnect all subscribers. - void Clear() { - detail::SignalClear(m_state, m_mutex); - } - - XALLOCATOR - -private: - mutable RecursiveMutex m_mutex; - std::shared_ptr m_state = xmake_shared(); -}; - -} // namespace dmq - -DMQ_OPTIMIZE_OFF - -#endif // SIGNAL_H diff --git a/DelegateMQ/delegate/UnicastDelegate.h b/DelegateMQ/delegate/UnicastDelegate.h deleted file mode 100644 index 2f5a4dd..0000000 --- a/DelegateMQ/delegate/UnicastDelegate.h +++ /dev/null @@ -1,155 +0,0 @@ -#ifndef _UNICAST_DELEGATE_H -#define _UNICAST_DELEGATE_H - -/// @file -/// @brief Delegate container for storing an invoking a single delegate instance. -/// Class is not thread-safe. - -#include "Delegate.h" -#include - -DMQ_OPTIMIZE_ON - -namespace dmq { - -template -class UnicastDelegate; // Not defined - -namespace detail { - -/// @brief Clone `delegate` and wrap it in a shared_ptr, fully erased to the -/// non-templated `DelegateBase` at construction. `delegate.Clone()` is called -/// through a `const DelegateBase&`, so its return type here is `DelegateBase*` -/// -- the resulting shared_ptr control block is therefore not templated on -/// RetType/Args, and is shared by every `UnicastDelegate` in the program -/// instead of duplicated per signature. Non-templated: none of this logic -/// depends on the owning container's signature. -inline std::shared_ptr UnicastClone(const DelegateBase& delegate) { - auto delegateClone = delegate.Clone(); - if (!delegateClone) - BAD_ALLOC(); - return std::shared_ptr(delegateClone, std::default_delete(), ::dmq::stl_allocator()); -} - -} // namespace detail - -/// @brief A non-thread-safe delegate container storing one delegate. Void and -/// non-void return values supported. -template -class UnicastDelegate -{ -public: - using DelegateType = Delegate; - - UnicastDelegate() = default; - virtual ~UnicastDelegate() { Clear(); } - - /// @brief Copy constructor that creates a copy of the given instance. - /// @details This constructor initializes a new object as a copy of the - /// provided `rhs` (right-hand side) object. The `rhs` object is used to - /// set the state of the new instance. - /// @param[in] rhs The object to copy from. - UnicastDelegate(const UnicastDelegate& rhs) { - if (rhs.m_delegate) - m_delegate = detail::UnicastClone(*rhs.m_delegate); - } - - /// Move constructor that transfers ownership of resources. - /// @param[in] rhs The object to move from. - UnicastDelegate(UnicastDelegate&& rhs) noexcept : m_delegate(std::move(rhs.m_delegate)) { } - - /// Constructor to initialize from a Delegate (Copy) - UnicastDelegate(const DelegateType& d) { - *this = d; - } - - /// Constructor to initialize from a Delegate (Move) - UnicastDelegate(DelegateType&& d) { - *this = std::move(d); - } - - - /// Invoke the bound target. - /// @param[in] args The arguments used when invoking the target function - /// @return The target function return value. - RetType operator()(Args... args) const { - if (m_delegate) - return (*static_cast(m_delegate.get()))(args...); // Invoke delegate callback - else - return RetType(); - } - - /// Invoke the bound target functions. - /// @param[in] args The arguments used when invoking the target function - void Broadcast(Args... args) const { - (*this)(args...); - } - - /// Assign a delegate to the container. - /// @param[in] rhs A delegate target to assign - void operator=(const DelegateType& rhs) { - m_delegate = detail::UnicastClone(rhs); - } - - /// Assign a delegate to the container. - /// @param[in] rhs A delegate target to assign - void operator=(DelegateType&& rhs) { - // Clone() even on rvalue: no move API exists across the polymorphic delegate hierarchy. - m_delegate = detail::UnicastClone(rhs); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - UnicastDelegate& operator=(const UnicastDelegate& rhs) { - if (this != &rhs) { - m_delegate = rhs.m_delegate ? detail::UnicastClone(*rhs.m_delegate) : nullptr; - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - UnicastDelegate& operator=(UnicastDelegate&& rhs) noexcept { - if (this != &rhs) { - m_delegate = std::move(rhs.m_delegate); - } - return *this; - } - - /// @brief Clear the all target functions. - virtual void operator=(std::nullptr_t) noexcept { Clear(); } - - /// Any registered delegates? - /// @return `true` if delegate container is empty. - bool Empty() const { return !m_delegate; } - - /// Remove the registered delegate - void Clear() { m_delegate = nullptr; } - - /// Get the number of delegates stored. - /// @return The number of delegates stored. - std::size_t Size() const { return m_delegate == nullptr ? 0 : 1; } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the container is not empty, `false` if the container is empty. - explicit operator bool() const { return !Empty(); } - - /// @brief Get the underlying delegate. - /// @return The underlying delegate pointer, or nullptr if empty. - const DelegateType* GetDelegate() const { return static_cast(m_delegate.get()); } - -protected: - /// Registered delegate. Stored as `DelegateBase` (not `DelegateType`) so the - /// shared_ptr control block is shared across every `UnicastDelegate` - /// signature instead of duplicated per signature. Only `operator()`/ - /// `GetDelegate()`, which must return the concrete `DelegateType`, cast back. - std::shared_ptr m_delegate = nullptr; -}; - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/UnicastDelegateSafe.h b/DelegateMQ/delegate/UnicastDelegateSafe.h deleted file mode 100644 index 21d96b5..0000000 --- a/DelegateMQ/delegate/UnicastDelegateSafe.h +++ /dev/null @@ -1,169 +0,0 @@ -#ifndef _UNICAST_DELEGATE_SAFE_H -#define _UNICAST_DELEGATE_SAFE_H - -/// @file -/// @brief Delegate container for storing an invoking a single delegate instance. -/// Class is thread-safe. -/// -/// @note Invocation copies the delegate out under the lock and calls it after -/// releasing it, so a delegate cleared or replaced on one thread may still be -/// called once by an invocation already in progress on another. See the note in -/// Signal.h before destroying the target right after clearing. - -#include "UnicastDelegate.h" - -DMQ_OPTIMIZE_ON - -namespace dmq { - -template -class UnicastDelegateSafe; // Not defined - -namespace detail { - -/// @brief Copy the delegate pointer out under lock, then release. Non-templated: -/// entirely independent of the owning container's signature. The caller invokes -/// against the returned copy without holding the lock, avoiding circular lock -/// dependencies if the target function itself tries to acquire it. -inline std::shared_ptr UnicastSafeGet(const std::shared_ptr& delegate, RecursiveMutex& lock) { - const dmq::LockGuard g(lock); - return delegate; -} - -} // namespace detail - -/// @brief A thread-safe delegate container storing one delegate. Void and -/// non-void return values supported. -template -class UnicastDelegateSafe : public UnicastDelegate -{ -public: - using DelegateType = Delegate; - using BaseType = UnicastDelegate; - - UnicastDelegateSafe() = default; - virtual ~UnicastDelegateSafe() = default; - - UnicastDelegateSafe(const UnicastDelegateSafe& rhs) : BaseType() { - dmq::LockGuard lock(rhs.m_lock); - BaseType::operator=(rhs); - } - - UnicastDelegateSafe(UnicastDelegateSafe&& rhs) : BaseType() { - dmq::LockGuard lock(rhs.m_lock); - BaseType::operator=(std::move(rhs)); - } - - /// Constructor to initialize from a Delegate (Copy) - UnicastDelegateSafe(const DelegateType& d) { - dmq::LockGuard lock(m_lock); - BaseType::operator=(d); - } - - /// Constructor to initialize from a Delegate (Move) - UnicastDelegateSafe(DelegateType&& d) { - dmq::LockGuard lock(m_lock); - BaseType::operator=(std::move(d)); - } - - /// Invoke the bound target. - /// @param[in] args The arguments used when invoking the target function - /// @return The target function return value. - RetType operator()(Args... args) const { - // Lock only to fetch the delegate pointer. Release lock before - // invoking the delegate to prevent circular lock dependencies - // and deadlocks. - auto delegate = detail::UnicastSafeGet(this->m_delegate, m_lock); - - if (delegate) - return (*static_cast(delegate.get()))(args...); - return RetType(); - } - - /// Invoke the bound target functions. - /// @param[in] args The arguments used when invoking the target function - void Broadcast(Args... args) const { - operator()(args...); - } - - /// Assign a delegate to the container. - /// @param[in] rhs A delegate target to assign - void operator=(const DelegateType& rhs) { - const dmq::LockGuard lock(m_lock); - BaseType::operator=(rhs); - } - - /// Assign a delegate to the container. - /// @param[in] rhs A delegate target to assign - void operator=(DelegateType&& rhs) { - const dmq::LockGuard lock(m_lock); - BaseType::operator=(rhs); - } - - /// @brief Assignment operator that assigns the state of one object to another. - /// @param[in] rhs The object whose state is to be assigned to the current object. - /// @return A reference to the current object. - UnicastDelegateSafe& operator=(const UnicastDelegateSafe& rhs) { - if (this != &rhs) { - dmq::ScopedLock lock(m_lock, rhs.m_lock); - BaseType::operator=(rhs); - } - return *this; - } - - /// @brief Move assignment operator that transfers ownership of resources. - /// @param[in] rhs The object to move from. - /// @return A reference to the current object. - UnicastDelegateSafe& operator=(UnicastDelegateSafe&& rhs) noexcept { - if (this != &rhs) { - dmq::ScopedLock lock(m_lock, rhs.m_lock); - BaseType::operator=(std::move(rhs)); - } - return *this; - } - - /// @brief Clear the all target functions. - virtual void operator=(std::nullptr_t) noexcept { - const dmq::LockGuard lock(m_lock); - BaseType::Clear(); - } - - /// Any registered delegates? - /// @return `true` if delegate container is empty. - bool Empty() const { - const dmq::LockGuard lock(m_lock); - return BaseType::Empty(); - } - - /// Remove the registered delegate - void Clear() { - const dmq::LockGuard lock(m_lock); - BaseType::Clear(); - } - - /// Get the number of delegates stored. - /// @return The number of delegates stored. - std::size_t Size() const { - const dmq::LockGuard lock(m_lock); - return BaseType::Size(); - } - - /// @brief Implicit conversion operator to `bool`. - /// @return `true` if the container is not empty, `false` if the container is empty. - explicit operator bool() const { - const dmq::LockGuard lock(m_lock); - return BaseType::operator bool(); - } - -private: - /// Lock to make the class thread-safe. - /// Must be recursive to allow the callback to modify this delegate. - /// Must be mutable to allow locking in const methods. - mutable RecursiveMutex m_lock; -}; - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/make_tuple_heap.h b/DelegateMQ/delegate/make_tuple_heap.h deleted file mode 100644 index 81a109f..0000000 --- a/DelegateMQ/delegate/make_tuple_heap.h +++ /dev/null @@ -1,244 +0,0 @@ -#ifndef _MAKE_TUPLE_HEAP_H -#define _MAKE_TUPLE_HEAP_H - -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, Aug 2020. - -/// @file -/// @brief Helpers for storing the arguments of a non-blocking async call. -/// -/// @details `DelegateAsyncMsg` (`DelegateAsync.h`) builds its `std::tuple` of -/// arguments with `store_async_arg()`, one argument at a time, for transport through a -/// thread message queue. By-value arguments are stored in the tuple directly; for -/// pointer, pointer-to-pointer and reference arguments, `heap_copy_arg()` makes a heap -/// copy of the data, freed by a `heap_arg_deleter` once the call is done. -/// -/// The destination thread uses `std::apply()` to invoke the target function using -/// the tuple of arguments. - -#include -#include -#include -#include "DelegateOpt.h" -DMQ_OPTIMIZE_ON - -namespace dmq -{ -template -struct is_shared_ptr : std::false_type {}; - -template -struct is_shared_ptr> : std::true_type {}; - -template -struct is_shared_ptr&> : std::true_type {}; - -template -struct is_shared_ptr&> : std::true_type {}; - -template -struct is_shared_ptr*> : std::true_type {}; - -template -struct is_shared_ptr*> : std::true_type {}; - -template -struct is_unique_ptr : std::false_type {}; - -template -struct is_unique_ptr> : std::true_type {}; - -/// @brief Base class for all deleter's -class heap_arg_deleter_base -{ -public: - virtual ~heap_arg_deleter_base() = default; - - XALLOCATOR -}; - -/// @brief Forward declaration for heap argument deleter -template -class heap_arg_deleter; - -/// @brief Frees heap memory for pointer heap argument -template -class heap_arg_deleter : public heap_arg_deleter_base -{ -public: - heap_arg_deleter(T* arg) : m_arg(arg) { } - virtual ~heap_arg_deleter() { - xdelete(m_arg); - } -private: - T* m_arg; -}; - -/// @brief Frees heap memory for pointer to pointer heap argument -template -class heap_arg_deleter : public heap_arg_deleter_base -{ -public: - // Capture the original inner pointer at construction so the destructor always - // frees the xnew'd copy, regardless of whether the target function overwrites - // *arg (e.g. an outgoing-argument pattern like (*s) = new T). - heap_arg_deleter(T** arg) : m_arg(arg), m_inner(arg ? *arg : nullptr) {} - virtual ~heap_arg_deleter() { - if (m_arg && *m_arg != m_inner) { - xdelete(*m_arg); // free the newly assigned pointer if overwritten by target function - } - xdelete(m_inner); // free the original xnew'd inner copy (may be nullptr) - xdelete(m_arg); // free the outer pointer storage - } -private: - T** m_arg; - T* m_inner; // original value of *arg at dispatch time -}; - -// The three heap_copy_arg() overloads below make the heap copy for a pointer, -// pointer-to-pointer or reference argument and register a deleter for it in -// `heapArgs`; the deleter frees the copy when the message is destroyed. They are -// overloads (not one function with if constexpr) so the same overload is chosen for -// every argument type as when they were `tuple_append()`. -// -// Failure handling: BAD_ALLOC() never returns (DMQ_ASSERTS calls the noreturn -// FaultHandler, otherwise it throws std::bad_alloc), so code after it doesn't run. -// If heapArgs.push_back() throws, the local `deleter` going out of scope frees the copy. - -/// @brief Heap-copy a pointer-to-pointer argument: the pointee and the pointer. -/// @return The heap copy (a `nullptr` inner pointer if `arg` or `*arg` is null). -template -Arg** heap_copy_arg(xlist>& heapArgs, Arg** arg) -{ - Arg** heap_arg = nullptr; - Arg** del_arg = nullptr; - - if (arg != nullptr && *arg != nullptr) { - // Allocate memory for heap_arg and copy the value - heap_arg = xnew(); - if (!heap_arg) { - BAD_ALLOC(); - } else { - *heap_arg = xnew(**arg); - if (!*heap_arg) { - xdelete(heap_arg); - BAD_ALLOC(); - } else { - del_arg = heap_arg; - } - } - } - else { - // If arg is nullptr or *arg is nullptr, create heap_arg as nullptr - heap_arg = xnew(nullptr); - if (!heap_arg) { - BAD_ALLOC(); - } else { - del_arg = heap_arg; - } - } - - auto deleter = xmake_shared>(del_arg); - if (!deleter) { - if (del_arg) { - if (*del_arg) xdelete(*del_arg); - xdelete(del_arg); - } - BAD_ALLOC(); - } - heapArgs.push_back(deleter); - return heap_arg; -} - -/// @brief Heap-copy a pointer argument's pointee. -/// @return The heap copy, or `nullptr` if `arg` is null. -template -Arg* heap_copy_arg(xlist>& heapArgs, Arg* arg) -{ - Arg* heap_arg = nullptr; - Arg* del_arg = nullptr; - if (arg != nullptr) { - heap_arg = xnew(*arg); - if (!heap_arg) { - BAD_ALLOC(); - } else { - del_arg = heap_arg; - } - } - auto deleter = xmake_shared>(del_arg); - if (!deleter) { - if (del_arg) { - xdelete(del_arg); - } - BAD_ALLOC(); - } - heapArgs.push_back(deleter); - return heap_arg; -} - -/// @brief Heap-copy a reference argument. -/// @return A reference to the heap copy. -template -Arg& heap_copy_arg(xlist>& heapArgs, Arg& arg) -{ - Arg* heap_arg = xnew(arg); - Arg* del_arg = nullptr; - if (!heap_arg) { - BAD_ALLOC(); - } else { - del_arg = heap_arg; - } - auto deleter = xmake_shared>(del_arg); - if (!deleter) { - if (del_arg) { - xdelete(del_arg); - } - BAD_ALLOC(); - } - heapArgs.push_back(deleter); - return *heap_arg; -} - -/// @brief Store one argument of a non-blocking async call. Chooses by `Param`, the -/// bound function's declared parameter type, not by how the argument arrives. -/// @details -/// - By-value parameter: returned as-is (moved). The message's `std::tuple` -/// element holds its own copy, so a heap copy would only be copied again. -/// - Reference or pointer parameter: the caller's data is copied to the heap (freed -/// through `heapArgs` once the call is done) and a reference/pointer to that copy is -/// returned, using the `heap_copy_arg()` overloads above. -/// -/// This replaced `make_tuple_heap()`, which heap-copied every argument, by-value ones -/// too. An earlier attempt to skip the copy for values added an `Arg&&` overload of -/// `tuple_append()` (now `heap_copy_arg()`), i.e. chose by the argument's value -/// category. It silently stopped applying when `make_tuple_heap()` began passing its -/// arguments on as lvalues, and was later removed. Deciding from `Param` with -/// `if constexpr` doesn't depend on overload resolution. -/// @tparam Param The declared parameter type of the bound function. -/// @param heapArgs The list of deleters for heap-allocated arguments. -/// @param arg The argument, forwarded as `Param`. -/// @return The value (by-value `Param`), or a reference/pointer to the heap copy. -template -decltype(auto) store_async_arg(xlist>& heapArgs, A&& arg) -{ - static_assert(!std::is_same, void*>::value, "void* argument not allowed"); - if constexpr (std::is_reference_v) { - // Pass as an lvalue so heap_copy_arg()'s Arg& overload makes the heap copy; - // it returns a reference to that copy. - auto& lv = arg; - return heap_copy_arg(heapArgs, lv); - } else if constexpr (std::is_pointer_v) { - // Pointer and pointer-to-pointer: heap copy of the pointee, as before. - auto& lv = arg; - Param heapPtr = heap_copy_arg(heapArgs, lv); - return heapPtr; - } else { - return std::forward(arg); - } -} - -} - -DMQ_OPTIMIZE_OFF - -#endif diff --git a/DelegateMQ/delegate/src_dup.py b/DelegateMQ/delegate/src_dup.py deleted file mode 100644 index 31063e1..0000000 --- a/DelegateMQ/delegate/src_dup.py +++ /dev/null @@ -1,76 +0,0 @@ -# Script to keep common sections of the repetitive code and data -# synchronized within the same file. The code between the first -# pare of a tags within a source code file is automatically duplicated -# to all other tag locations. For instance, change MyClass1::Func() and -# classes below will be updated to match. -# -# -# class MyClass1 { -# public: -# // -# void Func() {} -# // -# } -# -# class MyClass2 { -# public: -# // -# void Func() {} -# // -# } -# -# Tags: -# -# -# Run: -# python src_dup.py -# -# python src_dup.py DelegateAsync.h -# python src_dup.py DelegateAsyncWait.h - -import re -import sys - -def copy_common_code(input_code, tag): - # Regular expression to match content within tag - common_pattern = re.compile(tag, re.DOTALL) - - # Find all the content inside the tag - common_code_match = re.search(common_pattern, input_code) - - if common_code_match: - common_code = common_code_match.group(0) - - # Replace the tags content - output_code = re.sub(common_pattern, f"{common_code}", input_code) - - return output_code - else: - return input_code - -def process_file(file_name): - try: - # Open the file and read the content - with open(file_name, 'r') as file: - input_code = file.read() - - # Process the code and get the modified version - modified_code = copy_common_code(input_code, r'// (.*?)// ') - - # Output the modified code - with open(file_name, 'w') as output_file: - output_file.write(modified_code) - - print(f"Modified code has been written to {file_name}") - - except FileNotFoundError: - print(f"Error: The file '{file_name}' was not found.") - except ValueError as e: - print(e) - -if __name__ == "__main__": - if len(sys.argv) != 2: - print("Usage: python script.py ") - else: - input_file_name = sys.argv[1] - process_file(input_file_name) diff --git a/DelegateMQ/extras/allocator/Allocator.cpp b/DelegateMQ/extras/allocator/Allocator.cpp deleted file mode 100644 index 5ed885d..0000000 --- a/DelegateMQ/extras/allocator/Allocator.cpp +++ /dev/null @@ -1,185 +0,0 @@ -// Compiles to nothing unless DMQ_ALLOCATOR is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_ALLOCATOR) - -#include "Allocator.h" -#include "delegate/DelegateOpt.h" -#include - -namespace dmq { - -//------------------------------------------------------------------------------ -// Constructor -//------------------------------------------------------------------------------ -Allocator::Allocator(size_t size, uint32_t objects, char* memory, const char* name) : - m_blockSize(size < sizeof(long*) ? sizeof(long*):size), - m_objectSize(size), - m_maxObjects(objects), - m_pHead(NULL), - m_poolIndex(0), - m_blockCnt(0), - m_blocksInUse(0), - m_allocations(0), - m_deallocations(0), - m_name(name) -{ - // If using a fixed memory pool - if (m_maxObjects) - { - // If caller provided an external memory pool - if (memory) - { - m_pPool = memory; - m_allocatorMode = STATIC_POOL; - } - else - { - m_pPool = (char*)new char[m_blockSize * m_maxObjects]; - m_allocatorMode = HEAP_POOL; - } - } - else - { - m_pPool = NULL; - m_allocatorMode = HEAP_BLOCKS; - } -} - -//------------------------------------------------------------------------------ -// Destructor -//------------------------------------------------------------------------------ -Allocator::~Allocator() -{ - // If using pool then destroy it, otherwise traverse free-list and - // destroy each individual block - if (m_allocatorMode == HEAP_POOL) - delete [] m_pPool; - else if (m_allocatorMode == HEAP_BLOCKS) - { - while(m_pHead) - delete [] (char*)Pop(); - } -} - -//------------------------------------------------------------------------------ -// Allocate -//------------------------------------------------------------------------------ -void* Allocator::Allocate([[maybe_unused]] size_t size) -{ - DMQ_ASSERT_TRUE(size <= m_objectSize); - - // If can't obtain existing block then get a new one - void* pBlock = Pop(); - if (!pBlock) - { - // If using a pool method then get block from pool, - // otherwise using dynamic so get block from heap - if (m_maxObjects) - { - // If we have not exceeded the pool maximum - if(m_poolIndex < m_maxObjects) - { - pBlock = (void*)(m_pPool + (m_poolIndex++ * m_blockSize)); - } - else - { - // Get the pointer to the new handler - std::new_handler handler = std::set_new_handler(0); - std::set_new_handler(handler); - - while (!pBlock) - { - if (handler) - { - (*handler)(); - pBlock = Pop(); - } - else - { - BAD_ALLOC(); - } - } - } - } - else - { - m_blockCnt++; - pBlock = (void*)new char[m_blockSize]; - } - } - - if (pBlock) - { - m_blocksInUse++; - m_allocations++; - } - - return pBlock; -} - -//------------------------------------------------------------------------------ -// Deallocate -//------------------------------------------------------------------------------ -void Allocator::Deallocate(void* pBlock) -{ - // delete of a null pointer may call operator delete(NULL) (DECLARE_ALLOCATOR) - if (!pBlock) - return; - -#ifdef DMQ_ALLOCATOR_SAFEGUARDS - if (m_allocatorMode == STATIC_POOL || m_allocatorMode == HEAP_POOL) - { - // Check that pBlock is within the pool range - char* pCharBlock = (char*)pBlock; - DMQ_ASSERT_TRUE(pCharBlock >= m_pPool && pCharBlock < (m_pPool + (m_blockSize * m_maxObjects))); - - // Check that pBlock is aligned on a block boundary - DMQ_ASSERT_TRUE(((size_t)(pCharBlock - m_pPool) % m_blockSize) == 0); - } -#endif - - Push(pBlock); - m_blocksInUse--; - m_deallocations++; -} - -//------------------------------------------------------------------------------ -// AccountAlloc -//------------------------------------------------------------------------------ -void Allocator::AccountAlloc(bool newBlock) -{ - if (newBlock) m_blockCnt++; - m_blocksInUse++; - m_allocations++; -} - -//------------------------------------------------------------------------------ -// Push -//------------------------------------------------------------------------------ -void Allocator::Push(void* pMemory) -{ - Block* pBlock = (Block*)pMemory; - pBlock->pNext = m_pHead; - m_pHead = pBlock; -} - -//------------------------------------------------------------------------------ -// Pop -//------------------------------------------------------------------------------ -void* Allocator::Pop() -{ - Block* pBlock = NULL; - - if (m_pHead) - { - pBlock = m_pHead; - m_pHead = m_pHead->pNext; - } - - return (void*)pBlock; -} - -} // namespace dmq - -#endif // DMQ_ALLOCATOR diff --git a/DelegateMQ/extras/allocator/Allocator.h b/DelegateMQ/extras/allocator/Allocator.h deleted file mode 100644 index 50e0ad5..0000000 --- a/DelegateMQ/extras/allocator/Allocator.h +++ /dev/null @@ -1,134 +0,0 @@ -#ifndef __ALLOCATOR_H -#define __ALLOCATOR_H - -#include "../../delegate/DelegateOpt.h" -#include -#include -#include - -namespace dmq { - -/// @see https://github.com/endurodave/Allocator -/// David Lafreniere -class Allocator -{ -public: - /// Constructor - /// @param[in] size - size of the fixed blocks - /// @param[in] objects - maximum number of object. If 0, new blocks are - /// created off the heap as necessary. - /// @param[in] memory - pointer to a block of static memory for allocator or NULL - /// to obtain memory from global heap. If not NULL, the objects argument - /// defines the size of the memory block (size x objects = memory size in bytes). - /// @param[in] name - optional allocator name string. - Allocator(size_t size, uint32_t objects=0, char* memory = NULL, const char* name=NULL); - - /// Destructor - ~Allocator(); - - /// Get a pointer to a memory block. - /// @param[in] size - size of the block to allocate - /// @return Returns pointer to the block. Otherwise NULL if unsuccessful. - void* Allocate(size_t size); - - /// Return a pointer to the memory pool. - /// @param[in] pBlock - block of memory deallocate (i.e push onto free-list) - void Deallocate(void* pBlock); - - /// Update allocation stats when xmalloc bypasses Allocate() to avoid holding - /// the global lock during heap allocation. Must be called under the global lock. - /// @param[in] newBlock - true if a fresh block was obtained from the heap. - void AccountAlloc(bool newBlock); - - /// Push a memory block onto head of free-list. - /// @param[in] pMemory - block of memory to push onto free-list - void Push(void* pMemory); - - /// Pop a memory block from head of free-list. - /// @return Returns pointer to the block. Otherwise NULL if unsuccessful. - void* Pop(); - - /// Get the allocator name string. - /// @return A pointer to the allocator name or NULL if none was assigned. - const char* GetName() { return m_name; } - - /// Gets the fixed block memory size, in bytes, handled by the allocator. - /// @return The fixed block size in bytes. - size_t GetBlockSize() const { return m_blockSize; } - - /// Gets the maximum number of blocks created by the allocator. - /// @return The number of fixed memory blocks created. - uint32_t GetBlockCount() { return m_blockCnt; } - - /// Gets the number of blocks in use. - /// @return The number of fixed memory blocks in use. - uint32_t GetBlocksInUse() { return m_blocksInUse; } - - /// Gets the total number of allocations for this allocator instance. - /// @return The total number of allocations. - uint32_t GetAllocations() { return m_allocations; } - - /// Gets the total number of deallocations for this allocator instance. - /// @return The total number of deallocations. - uint32_t GetDeallocations() { return m_deallocations; } - -private: - struct Block - { - Block* pNext; - }; - - enum AllocatorMode { HEAP_BLOCKS, HEAP_POOL, STATIC_POOL }; - - const size_t m_blockSize; - const size_t m_objectSize; - const uint32_t m_maxObjects; - AllocatorMode m_allocatorMode; - Block* m_pHead; - char* m_pPool; - uint32_t m_poolIndex; - uint32_t m_blockCnt; - uint32_t m_blocksInUse; - uint32_t m_allocations; - uint32_t m_deallocations; - const char* m_name; -}; - -// Template class to create external memory pool -template -class AllocatorPool : public Allocator -{ -public: - AllocatorPool() : Allocator(sizeof(T), Objects, m_memory) - { - } -private: - alignas(std::max_align_t) char m_memory[sizeof(T) * Objects]; -}; - -} // namespace dmq - -// macro to provide header file interface -#define DECLARE_ALLOCATOR \ - public: \ - void* operator new(size_t size) { \ - dmq::LockGuard lock(_allocatorMutex); \ - return _allocator.Allocate(size); \ - } \ - void operator delete(void* pObject) { \ - dmq::LockGuard lock(_allocatorMutex); \ - _allocator.Deallocate(pObject); \ - } \ - private: \ - static dmq::Allocator _allocator; \ - static dmq::Mutex _allocatorMutex; - -// macro to provide source file interface -#define IMPLEMENT_ALLOCATOR(class, objects, memory) \ - dmq::Allocator class::_allocator(sizeof(class), objects, memory, #class); \ - dmq::Mutex class::_allocatorMutex; - -#endif - - - diff --git a/DelegateMQ/extras/allocator/README.md b/DelegateMQ/extras/allocator/README.md deleted file mode 100644 index 3f9aa09..0000000 --- a/DelegateMQ/extras/allocator/README.md +++ /dev/null @@ -1,64 +0,0 @@ -# Allocator Suite - -A robust, fixed-block memory allocator suite for C++ applications, designed for performance and deterministic behavior in resource-constrained or real-time systems. - -## Features - -- **Fixed-Block Allocation**: Prevents heap fragmentation by using pre-allocated pools of equal-sized blocks. -- **C++ Class Integration**: `DECLARE_ALLOCATOR` and `IMPLEMENT_ALLOCATOR` macros provide easy integration with custom classes. -- **XALLOCATOR Macro**: Overloads `operator new` and `operator delete` for seamless use. -- **STL Compatibility**: `stl_allocator` allows STL containers (`std::vector`, `std::list`, `std::map`, etc.) to use the fixed-block pool. -- **Smart Pointer Support**: `xmake_shared` creates `std::shared_ptr` with both the object and control block allocated from the pool. -- **C API**: `xmalloc`, `xfree`, and `xrealloc` functions for C-style memory management. - -## Components - -- **Allocator**: The core engine for fixed-block management. -- **AllocatorPool**: A template-based pool for specific types. -- **stl_allocator**: STL-compliant allocator wrapper. -- **xmake_shared**: Helper for pool-allocated shared pointers. -- **xnew / xdelete**: Helper templates for placement new/destroy in the pool. - -## Basic Usage - -### Using XALLOCATOR in a class - -```cpp -class MyClass { - XALLOCATOR -public: - int data; -}; - -// Now 'new MyClass' uses the fixed-block allocator -MyClass* obj = new MyClass(); -delete obj; -``` - -### Using STL containers - -```cpp -#include "xlist.h" - -// xlist is a typedef for std::list using stl_allocator -xlist myList; -myList.push_back(10); -``` - -### Using xmake_shared - -```cpp -auto sp = xmake_shared(args...); -``` - -## Memory Alignment - -The `xallocator` implementation ensures that all allocated blocks are correctly aligned for the target architecture: - -- **Power-of-Two Rounding**: All requested block sizes are rounded up to the next power of two (8, 16, 32, 64, etc.). This inherently satisfies the natural alignment requirements of all standard C++ types (`int`, `double`, `long long`, etc.) and modern SIMD/AVX vector instructions. -- **Header Alignment**: A `BLOCK_HEADER_SIZE` (16 bytes on 64-bit, 8 bytes on 32-bit) is added to each block to store metadata. Both the raw block and the user's data pointer remain aligned on 8 or 16-byte boundaries. -- **Efficiency vs. Safety**: This strategy prioritizes "automatic" alignment and safety over maximum memory density. While it may result in some internal fragmentation, it ensures that memory is always safe for any data type without manual alignment configuration. - -## Integration with DelegateMQ - -To enable the allocator suite within DelegateMQ, define `DMQ_ALLOCATOR` in your build configuration. This will cause DelegateMQ's internal containers and remote delegate marshalling to use the fixed-block pools instead of the standard heap. diff --git a/DelegateMQ/extras/allocator/stl_allocator.h b/DelegateMQ/extras/allocator/stl_allocator.h deleted file mode 100644 index 6d72cfd..0000000 --- a/DelegateMQ/extras/allocator/stl_allocator.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef _STL_ALLOCATOR_H -#define _STL_ALLOCATOR_H - -// @see https://github.com/endurodave/stl_allocator -// David Lafreniere - -#include "xallocator.h" -#include "delegate/DelegateOpt.h" -#include // For std::allocator and std::allocator_traits -#include // For std::forward - -namespace dmq { - -// Forward declaration for stl_allocator -template -class stl_allocator; - -// Specialization for `void`, but we no longer need to define `pointer` and `const_pointer` -template <> -class stl_allocator -{ -public: - typedef void value_type; - - template - struct rebind { typedef stl_allocator other; }; -}; - -// Define the custom stl_allocator inheriting from std::allocator -template -class stl_allocator : public std::allocator -{ -public: - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef T* pointer; - typedef const T* const_pointer; - typedef T& reference; - typedef const T& const_reference; - typedef T value_type; - - // Default constructor - stl_allocator() {} - - // Copy constructor - template - stl_allocator(const stl_allocator&) {} - - // Rebind struct - template - struct rebind { typedef stl_allocator other; }; - - // Override allocate method to use custom allocation function - pointer allocate(size_type n, typename std::allocator_traits>::const_pointer /*hint*/ = 0) - { - void* p = xmalloc(n * sizeof(T)); - if (!p) BAD_ALLOC(); - return static_cast(p); - } - - // Override deallocate method to use custom deallocation function - void deallocate(pointer p, size_type /*n*/) - { - xfree(p); - } - - // You can inherit other methods like construct and destroy from std::allocator -}; - -// Comparison operators for compatibility -template -inline bool operator==(const stl_allocator&, const stl_allocator&) { return true; } - -template -inline bool operator!=(const stl_allocator&, const stl_allocator&) { return false; } - -} // namespace dmq - -#endif diff --git a/DelegateMQ/extras/allocator/xallocator.cpp b/DelegateMQ/extras/allocator/xallocator.cpp deleted file mode 100644 index 8a27668..0000000 --- a/DelegateMQ/extras/allocator/xallocator.cpp +++ /dev/null @@ -1,493 +0,0 @@ -// Compiles to nothing unless DMQ_ALLOCATOR is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_ALLOCATOR) - -#include "Allocator.h" -#include "xallocator.h" -#include "delegate/DelegateOpt.h" -#include -#include -#include -#include - - -#ifndef CHAR_BIT -#define CHAR_BIT 8 -#endif - -namespace dmq { - -// @TODO: Comment out to disable alignment check if desired after porting -//#define CHECK_ALIGNMENT - -// Logic: -// 1. We store a 'BlockHeader' at the start of the raw block. -// 2. The user's memory immediately follows this header. -// 3. To support types like 'long double' or SSE/AVX vectors, the user's memory -// must often be aligned to 16 bytes (on 64-bit) or 8 bytes (on 32-bit). -// -// Calculation: -// - Safeguards ON: BLOCK_HEADER_SIZE is fixed at 16 bytes to provide a -// robust guard area and maintain 16-byte alignment for the user. -// - Safeguards OFF: -// - 64-bit System: Ptrs are 8 bytes. Next aligned boundary is 16. Set to 16. -// - 32-bit System: Ptrs are 4 bytes. Next aligned boundary is 8. Set to 8. -// Single source of truth lives in xallocator.h; typed aliases for internal use. -static const size_t BLOCK_HEADER_SIZE = XALLOC_BLOCK_HEADER_SIZE; -static const size_t BLOCK_FOOTER_SIZE = XALLOC_BLOCK_FOOTER_SIZE; - -struct BlockHeader { - Allocator* allocator; -#ifdef DMQ_ALLOCATOR_SAFEGUARDS - uint32_t magic; - uint32_t canary; -#endif -}; - -// Define STATIC_POOLS to switch from heap blocks mode to static pools mode -//#define STATIC_POOLS -#ifdef STATIC_POOLS - // Update this section as necessary if you want to use static memory pools. - // See also xalloc_init() and xalloc_destroy() for additional updates required. - #define MAX_ALLOCATORS 10 - #define MAX_BLOCKS 32 - - // Create static storage for each static allocator instance - static alignas(std::max_align_t) char _allocator8 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator16 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator32 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator64 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator128 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator256 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator512 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator1024 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator2048 [sizeof(AllocatorPool)]; - static alignas(std::max_align_t) char _allocator4096 [sizeof(AllocatorPool)]; - - // Array of pointers to all allocator instances - static Allocator* _allocators[MAX_ALLOCATORS]; - -#else - #define MAX_ALLOCATORS DMQ_XALLOCATOR_MAX_ALLOCATORS - static Allocator* _allocators[MAX_ALLOCATORS]; -#endif // STATIC_POOLS - -// For C++ applications, must define AUTOMATIC_XALLOCATOR_INIT_DESTROY to -// correctly ensure allocators are initialized before any static user C++ -// construtor/destructor executes which might call into the xallocator API. -// This feature costs 1-byte of RAM per C++ translation unit. This feature -// can be disabled only under the following circumstances: -// -// 1) The xallocator is only used within C files. -// 2) STATIC_POOLS is undefined and the application never exits main (e.g. -// an embedded system). -// -// In either of the two cases above, call xalloc_init() in main at startup, -// and xalloc_destroy() before main exits. In all other situations -// XallocInitDestroy must be used to call xalloc_init() and xalloc_destroy(). -#ifdef AUTOMATIC_XALLOCATOR_INIT_DESTROY -std::atomic XallocInitDestroy::refCount(0); -XallocInitDestroy::XallocInitDestroy() -{ - // Track how many static instances of XallocInitDestroy are created - if (refCount++ == 0) - ::xalloc_init(); -} - -XallocInitDestroy::~XallocInitDestroy() -{ - // Last static instance to have destructor called? - if (--refCount == 0) - ::xalloc_destroy(); -} -#endif // AUTOMATIC_XALLOCATOR_INIT_DESTROY - -/// Returns the next higher powers of two. For instance, pass in 12 and -/// the value returned would be 16. -/// @param[in] k - numeric value to compute the next higher power of two. -/// @return The next higher power of two based on the input k. -template -T nexthigher(T k) -{ - k--; - for (size_t i=1; i> i); - return k+1; -} - -static dmq::Mutex& get_mutex() -{ - // Intentional immortal singleton: heap-allocate and never delete. - // A Meyers static would be destroyed during the static shutdown sequence; - // any static destructor that runs afterward and calls xalloc_* would then - // use-after-free the mutex. The heap pointer is never freed — the OS - // reclaims it at process exit, after all destructors have run. - static dmq::Mutex* _mutex = new dmq::Mutex(); - return *_mutex; -} - -#ifdef CHECK_ALIGNMENT -static void check_alignment(void* ptr) -{ - // Convert pointer to integer to perform bitwise check - uintptr_t address = reinterpret_cast(ptr); - - // Check if the address is a multiple of the pointer size. - // On 32-bit systems, we often only get 4-byte alignment from the heap. - // On 64-bit systems, we expect 8 or 16-byte alignment. - if ((address & (sizeof(void*) - 1)) != 0) - { - DMQ_ASSERT(); - } -} -#endif - -/// Stored a pointer to the allocator instance within the block region. -/// a pointer to the client's area within the block. -/// @param[in] block - a pointer to the raw memory block. -/// @param[in] allocator - the allocator instance. -/// @param[in] size - the client requested size of the memory block. -/// @return A pointer to the client's address within the raw memory block. -static inline void *set_block_allocator(void* block, Allocator* allocator) -{ - BlockHeader* pHeader = static_cast(block); - pHeader->allocator = allocator; -#ifdef DMQ_ALLOCATOR_SAFEGUARDS - pHeader->magic = XALLOC_MAGIC; - pHeader->canary = XALLOC_CANARY; - size_t userSize = allocator->GetBlockSize() - BLOCK_HEADER_SIZE - BLOCK_FOOTER_SIZE; - uint32_t* pFooter = (uint32_t*)((char*)block + BLOCK_HEADER_SIZE + userSize); - *pFooter = XALLOC_CANARY; -#endif - // Advance by BLOCK_HEADER_SIZE bytes (cast to char* first to do byte math) - return (char*)block + BLOCK_HEADER_SIZE; -} - -/// Gets the size of the memory block stored within the block. -/// @param[in] block - a pointer to the client's memory block. -/// @return The original allocator instance stored in the memory block. -static inline Allocator* get_block_allocator(void* block) -{ - BlockHeader* pHeader = (BlockHeader*)((char*)block - BLOCK_HEADER_SIZE); -#ifdef DMQ_ALLOCATOR_SAFEGUARDS - DMQ_ASSERT_TRUE(pHeader->magic != XALLOC_FREED); - DMQ_ASSERT_TRUE(pHeader->magic == XALLOC_MAGIC); - DMQ_ASSERT_TRUE(pHeader->canary == XALLOC_CANARY); - size_t userSize = pHeader->allocator->GetBlockSize() - BLOCK_HEADER_SIZE - BLOCK_FOOTER_SIZE; - uint32_t* pFooter = (uint32_t*)((char*)pHeader + BLOCK_HEADER_SIZE + userSize); - DMQ_ASSERT_TRUE(*pFooter == XALLOC_CANARY); -#endif - return pHeader->allocator; -} - -/// Returns the raw memory block pointer given a client memory pointer. -/// @param[in] block - a pointer to the client memory block. -/// @return A pointer to the original raw memory block address. -static inline void *get_block_ptr(void* block) -{ - return (char*)block - BLOCK_HEADER_SIZE; -} - -/// Returns an allocator instance matching the size provided -/// @param[in] size - allocator block size -/// @return Allocator instance handling requested block size or NULL -/// if no allocator exists. -static inline Allocator* find_allocator(size_t size) -{ - for (int i=0; iGetBlockSize() == size) - return _allocators[i]; - } - - return NULL; -} - -/// Insert an allocator into the first empty slot. Caller must hold get_mutex(). -/// @param[in] allocator - allocator instance to insert -/// @return true if inserted, false if the array is full -static inline bool insert_allocator(Allocator* allocator) -{ - for (int i = 0; i < MAX_ALLOCATORS; i++) - { - if (_allocators[i] == 0) - { - _allocators[i] = allocator; - return true; - } - } - return false; -} - -} // namespace dmq - -/// This function must be called exactly one time *before* any other xallocator -/// API is called. XallocInitDestroy constructor calls this function automatically. -extern "C" void xalloc_init() -{ -#ifdef STATIC_POOLS - dmq::get_mutex().lock(); - - // For STATIC_POOLS mode, the allocators must be initialized before any other - // static user class constructor is run. Therefore, use placement new to initialize - // each allocator into the previously reserved static memory locations. - new (&dmq::_allocator8) dmq::AllocatorPool(); - new (&dmq::_allocator16) dmq::AllocatorPool(); - new (&dmq::_allocator32) dmq::AllocatorPool(); - new (&dmq::_allocator64) dmq::AllocatorPool(); - new (&dmq::_allocator128) dmq::AllocatorPool(); - new (&dmq::_allocator256) dmq::AllocatorPool(); - new (&dmq::_allocator512) dmq::AllocatorPool(); - new (&dmq::_allocator1024) dmq::AllocatorPool(); - new (&dmq::_allocator2048) dmq::AllocatorPool(); - new (&dmq::_allocator4096) dmq::AllocatorPool(); - - // Populate allocator array with all instances - dmq::_allocators[0] = (dmq::Allocator*)&dmq::_allocator8; - dmq::_allocators[1] = (dmq::Allocator*)&dmq::_allocator16; - dmq::_allocators[2] = (dmq::Allocator*)&dmq::_allocator32; - dmq::_allocators[3] = (dmq::Allocator*)&dmq::_allocator64; - dmq::_allocators[4] = (dmq::Allocator*)&dmq::_allocator128; - dmq::_allocators[5] = (dmq::Allocator*)&dmq::_allocator256; - dmq::_allocators[6] = (dmq::Allocator*)&dmq::_allocator512; - dmq::_allocators[7] = (dmq::Allocator*)&dmq::_allocator1024; - dmq::_allocators[8] = (dmq::Allocator*)&dmq::_allocator2048; - dmq::_allocators[9] = (dmq::Allocator*)&dmq::_allocator4096; - - dmq::get_mutex().unlock(); -#endif -} - -/// Called one time when the application exits to cleanup any allocated memory. -/// ~XallocInitDestroy destructor calls this function automatically. -extern "C" void xalloc_destroy() -{ - dmq::get_mutex().lock(); - -#ifdef STATIC_POOLS - for (int i=0; i~Allocator(); - dmq::_allocators[i] = 0; - } -#else - for (int i=0; i(-1) >> 1) + 1; - if (size > maxBlockSize - dmq::BLOCK_HEADER_SIZE - dmq::BLOCK_FOOTER_SIZE) - return NULL; - - // Based on the size, find the next higher powers of two value. - size_t blockSize = size + dmq::BLOCK_HEADER_SIZE + dmq::BLOCK_FOOTER_SIZE; - blockSize = dmq::nexthigher(blockSize); - - dmq::get_mutex().lock(); - dmq::Allocator* allocator = dmq::find_allocator(blockSize); - dmq::get_mutex().unlock(); - -#ifdef STATIC_POOLS - DMQ_ASSERT_TRUE(allocator != NULL); -#else - // If there is not an allocator already created to handle this block size - if (allocator == NULL) - { - // Note: Creating the Allocator object is done OUTSIDE the lock to avoid - // AB/BA deadlocks with the system standard library locks. - // nothrow: an exception must not leave this extern "C" function - allocator = new (std::nothrow) dmq::Allocator(blockSize, 0, 0, "xallocator"); - if (allocator == NULL) - return NULL; - - // Re-check and insert atomically under the same lock — eliminates the TOCTOU - // window where two concurrent threads could each insert an Allocator for - // the same block size, yielding duplicate entries and a use-after-free at shutdown. - dmq::get_mutex().lock(); - dmq::Allocator* existing = dmq::find_allocator(blockSize); - if (!existing) - { - if (!dmq::insert_allocator(allocator)) - { - dmq::get_mutex().unlock(); - delete allocator; - DMQ_ASSERT(); - } - existing = allocator; - } - dmq::get_mutex().unlock(); - - if (existing != allocator) - delete allocator; - allocator = existing; - } -#endif - - return allocator; -} - -/// Allocates a memory block of the requested size. The blocks are created from -/// the fixed block allocators. -/// @param[in] size - the client requested size of the block. -/// @return A pointer to the client's memory block. -extern "C" void *xmalloc(size_t size) -{ - // 1. Get the bucket (surgical global locking inside). NULL: size too large. - dmq::Allocator* allocator = xallocator_get_allocator(size); - if (allocator == NULL) - return NULL; - size_t blockSize = allocator->GetBlockSize(); - - void* blockMemoryPtr = NULL; - -#ifdef STATIC_POOLS - // STATIC_POOLS: Allocate() handles pool slot distribution, exhaustion detection, - // and stat tracking. Must be called under the lock. - dmq::get_mutex().lock(); - blockMemoryPtr = allocator->Allocate(blockSize); - dmq::get_mutex().unlock(); -#else - // 2. Fast Path: pop a recycled block from the free-list under the lock. - dmq::get_mutex().lock(); - blockMemoryPtr = allocator->Pop(); - if (blockMemoryPtr != NULL) - allocator->AccountAlloc(false); - dmq::get_mutex().unlock(); - - if (blockMemoryPtr == NULL) - { - // 3. Slow Path: fetch from heap OUTSIDE the lock to prevent AB/BA deadlocks - // with standard library internal locks (e.g., MSVC _Lockit in debug builds). - // nothrow: an exception must not leave this extern "C" function (see - // CLAUDE.md). Callers (XALLOCATOR, stl_allocator) report NULL with BAD_ALLOC(). - blockMemoryPtr = (void*)new (std::nothrow) char[blockSize]; - if (blockMemoryPtr != NULL) - { - dmq::get_mutex().lock(); - allocator->AccountAlloc(true); - dmq::get_mutex().unlock(); - } - } -#endif - - if (blockMemoryPtr == NULL) - return NULL; - - // Set the block Allocator* within the raw memory block region - void* userPtr = dmq::set_block_allocator(blockMemoryPtr, allocator); - -#ifdef CHECK_ALIGNMENT - // Verify memory alignment before returning to the user - dmq::check_alignment(blockMemoryPtr); - dmq::check_alignment(userPtr); -#endif - - return userPtr; -} - -/// Frees a memory block previously allocated with xalloc. The blocks are returned -/// to the fixed block allocator that originally created it. -/// @param[in] ptr - a pointer to a block created with xalloc. -extern "C" void xfree(void* ptr) -{ - if (ptr == 0) - return; - - // Extract the original allocator instance from the caller's block pointer - dmq::Allocator* allocator = dmq::get_block_allocator(ptr); - - // Convert the client pointer into the original raw block pointer - void* blockPtr = dmq::get_block_ptr(ptr); - -#ifdef DMQ_ALLOCATOR_SAFEGUARDS - dmq::BlockHeader* pHeader = (dmq::BlockHeader*)blockPtr; - pHeader->magic = XALLOC_FREED; -#endif - - dmq::get_mutex().lock(); - allocator->Deallocate(blockPtr); - dmq::get_mutex().unlock(); -} - -/// Reallocates a memory block previously allocated with xalloc. -/// @param[in] ptr - a pointer to a block created with xalloc. -/// @param[in] size - the client requested block size to create. -extern "C" void *xrealloc(void *oldMem, size_t size) -{ - if (oldMem == 0) - return xmalloc(size); - - if (size == 0) - { - xfree(oldMem); - return 0; - } - else - { - // Create a new memory block - void* newMem = xmalloc(size); - if (newMem != 0) - { - // Get the original allocator instance from the old memory block - dmq::Allocator* oldAllocator = dmq::get_block_allocator(oldMem); - size_t oldSize = oldAllocator->GetBlockSize() - dmq::BLOCK_HEADER_SIZE - dmq::BLOCK_FOOTER_SIZE; - - // Copy the bytes from the old memory block into the new (as much as will fit) - memcpy(newMem, oldMem, (oldSize < size) ? oldSize : size); - - // Free the old memory block - xfree(oldMem); - - // Return the client pointer to the new memory block - return newMem; - } - return 0; - } -} - -/// Output xallocator usage statistics -extern "C" void xalloc_stats() -{ - dmq::get_mutex().lock(); - - for (int i=0; iGetName() != NULL) - std::cout << dmq::_allocators[i]->GetName(); - std::cout << " Block Size: " << dmq::_allocators[i]->GetBlockSize(); - std::cout << " Block Count: " << dmq::_allocators[i]->GetBlockCount(); - std::cout << " Blocks In Use: " << dmq::_allocators[i]->GetBlocksInUse(); - std::cout << std::endl; - } - - dmq::get_mutex().unlock(); -} - -#endif // DMQ_ALLOCATOR diff --git a/DelegateMQ/extras/allocator/xallocator.h b/DelegateMQ/extras/allocator/xallocator.h deleted file mode 100644 index 495e3c6..0000000 --- a/DelegateMQ/extras/allocator/xallocator.h +++ /dev/null @@ -1,153 +0,0 @@ -#ifndef _XALLOCATOR_H -#define _XALLOCATOR_H - -#include -#include -#include - -// @see https://github.com/endurodave/xallocator -// David Lafreniere - -#ifdef __cplusplus -// Define AUTOMATIC_XALLOCATOR_INIT_DESTROY to automatically call xalloc_init() and -// xalloc_destroy() when using xallocator in C++ projects. On embedded systems that -// never exit, you can save 1-byte of RAM storage per translation unit by undefining -// AUTOMATIC_XALLOCATOR_INIT_DESTROY and calling xalloc_init() manually before the OS -// starts. -#define AUTOMATIC_XALLOCATOR_INIT_DESTROY -#ifdef AUTOMATIC_XALLOCATOR_INIT_DESTROY -/// If a C++ translation unit, create a static instance of XallocInitDestroy. Any C++ -/// file including xallocator.h will have the xallocDestroy instance declared first -/// within the translation unit and thus will be constructed first. Destruction -/// will occur in the reverse order so xallocInitDestroy is called last. This way, -/// any static user objects relying on xallocator will be destroyed first before -/// xalloc_destroy() is called. -/// Embedded systems that never exit can remove the XallocInitDestroy class entirely. -namespace dmq { -class XallocInitDestroy -{ -public: - XallocInitDestroy(); - ~XallocInitDestroy(); -private: - static std::atomic refCount; -}; -} // namespace dmq -static dmq::XallocInitDestroy xallocInitDestroy; -#endif // AUTOMATIC_XALLOCATOR_INIT_DESTROY -#endif // __cplusplus - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef DMQ_ALLOCATOR_SAFEGUARDS -#define XALLOC_BLOCK_HEADER_SIZE 16 -#define XALLOC_BLOCK_FOOTER_SIZE 4 -#define XALLOC_MAGIC 0x414C4C4F // "ALLO" -#define XALLOC_FREED 0xDEADBEEF -#define XALLOC_CANARY 0xAA55AA55 -#else -#define XALLOC_BLOCK_HEADER_SIZE (sizeof(void*) > 4 ? 16 : 8) -#define XALLOC_BLOCK_FOOTER_SIZE 0 -#endif - -/// Forward declaration of Allocator class -#ifdef __cplusplus -namespace dmq { - class Allocator; -} -#endif - -/// This function must be called exactly one time before the operating system -/// threading starts. If using xallocator exclusively in C files within your application -/// code, you must call this function before the OS starts. If using C++, client code -/// does not call xalloc_init. Let XallocInitDestroy() call xalloc_init automatically. -/// Embedded systems that never exit can call xalloc_init() manually at startup -/// and eliminate XallocInitDestroy usage. When the system is still single threaded at -/// startup, the xallocator API does not need mutex protection. -void xalloc_init(); - -/// This function must be called once when the application exits. Never call xalloc_destroy() -/// manually except if using xallocator in a C-only application. If using xallocator -/// exclusively in C files within your application code, you must call this function before -/// the program exits. If using C++, ~XallocInitDestroy() must call xalloc_destroy automatically. -/// Embedded systems that never exit need not call this function at all. -void xalloc_destroy(); - -/// Get an Allocator instance based upon the client's requested block size. -/// @param[in] size - the client's requested block size. -/// @return An Allocator instance that handles blocks of the requested size. -#ifdef __cplusplus -dmq::Allocator* xallocator_get_allocator(size_t size); -#endif - -/// Allocate a block of memory -/// @param[in] size - the size of the block to allocate. -void *xmalloc(size_t size); - -/// Frees a previously xalloc allocated block -/// @param[in] ptr - a pointer to a previously allocated memory using xalloc. -void xfree(void* ptr); - -/// Reallocates an existing xalloc block to a new size -/// @param[in] ptr - a pointer to a previously allocated memory using xalloc. -/// @param[in] size - the size of the new block -void *xrealloc(void *ptr, size_t size); - -/// Output allocator statistics to the standard output -void xalloc_stats(); - -#ifdef DMQ_ALLOCATOR - // Macro to overload new/delete with xalloc/xfree. Add macro to any class to enable - // fixed-block memory allocation. Add to a base class provides fixed-block memory - // for the base and all derived classes. - // - // While std::make_shared is usually recommended for standard C++, in a fixed-block - // memory architecture, explicit 'new' is required to trigger the overloaded operator. - // - // Example: - // class MyMsg { - // XALLOCATOR - // }; - // - // // BAD: Allocates global memory (Bypasses XALLOCATOR) - // auto msg = std::make_shared(); - // - // // GOOD: Allocates fixed-block memory (Uses XALLOCATOR) - // std::shared_ptr msg(new MyMsg()); - #include "delegate/DelegateOpt.h" - #define XALLOCATOR \ - public: \ - void* operator new(size_t size) { \ - void* p = xmalloc(size); \ - if (!p) BAD_ALLOC(); \ - return p; \ - } \ - void* operator new(size_t /*size*/, void* mem) { \ - return mem; \ - } \ - void* operator new(size_t size, const std::nothrow_t& /*nt*/) { \ - return xmalloc(size); \ - } \ - void* operator new[](size_t size) { \ - void* p = xmalloc(size); \ - if (!p) BAD_ALLOC(); \ - return p; \ - } \ - void operator delete(void* pObject) { \ - xfree(pObject); \ - } \ - void operator delete(void* pObject, const std::nothrow_t& /*nt*/) { \ - xfree(pObject); \ - } \ - void operator delete[](void* pData) { \ - xfree(pData); \ - } -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/DelegateMQ/extras/allocator/xlist.h b/DelegateMQ/extras/allocator/xlist.h deleted file mode 100644 index 04e11de..0000000 --- a/DelegateMQ/extras/allocator/xlist.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef _XLIST_H -#define _XLIST_H - -#include "stl_allocator.h" -#include - -namespace dmq { - // xlist uses a fix-block memory allocator - template > - using xlist = std::list; -} - -#if 0 // Deprecated -template > - class xlist - : public std::list<_Ty, _Ax> - { - }; -#endif - -#endif - diff --git a/DelegateMQ/extras/allocator/xmake_shared.h b/DelegateMQ/extras/allocator/xmake_shared.h deleted file mode 100644 index 9c5ce8f..0000000 --- a/DelegateMQ/extras/allocator/xmake_shared.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef _XMAKE_SHARED_H -#define _XMAKE_SHARED_H - -#include "stl_allocator.h" -#include -#include - -/// @brief Create a shared_ptr with both the object and control block allocated -/// from the fixed-block pool. -namespace dmq { - template - inline std::shared_ptr xmake_shared(Args&&... args) - { - return std::allocate_shared(stl_allocator(), std::forward(args)...); - } -} - -#endif // _XMAKE_SHARED_H diff --git a/DelegateMQ/extras/allocator/xmap.h b/DelegateMQ/extras/allocator/xmap.h deleted file mode 100644 index 7d99d32..0000000 --- a/DelegateMQ/extras/allocator/xmap.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef _XMAP_H -#define _XMAP_H - -#include "stl_allocator.h" -#include - -namespace dmq { - -// xmap uses a fix-block memory allocator -template >> -using xmap = std::map, Alloc>; - -template >> -using xmultimap = std::multimap, Alloc>; - -} // namespace dmq - -#if 0 // Deprecated -template, - class _Alloc = stl_allocator > > - class xmap - : public std::map<_Kty, _Ty, _Pr, _Alloc> - { - }; - -template, - class _Alloc = stl_allocator > > - class xmultimap - : public std::multimap<_Kty, _Ty, _Pr, _Alloc> - { - }; -#endif - -#endif - diff --git a/DelegateMQ/extras/allocator/xnew.h b/DelegateMQ/extras/allocator/xnew.h deleted file mode 100644 index 883c8a2..0000000 --- a/DelegateMQ/extras/allocator/xnew.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef _XNEW_H -#define _XNEW_H - -// @see https://github.com/DelegateMQ/DelegateMQ -// David Lafreniere, 2026. - -/// @file xnew.h -/// @brief Fixed-block pool equivalents of operator new / delete. -/// -/// @details -/// xnew(args...) allocates from the xallocator fixed-block pool and -/// constructs T in-place via placement new. xdelete(p) calls the -/// destructor then returns the memory to the pool via xfree(). -/// -/// These are the pool-aware counterparts of new(std::nothrow) / delete -/// for types that do not carry the XALLOCATOR macro (e.g. user argument -/// types copied for async delegates, see store_async_arg()). - -#include "xallocator.h" - -namespace dmq { - /// @brief Allocate and construct T in the fixed-block pool. - /// @return Pointer to the constructed object, or nullptr if xmalloc fails. - template - inline T* xnew(Args&&... args) - { - void* mem = xmalloc(sizeof(T)); - if (!mem) return nullptr; - -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // Exceptions unavailable/disabled: T's constructor is assumed not to throw. - return ::new(mem) T(std::forward(args)...); -#else - try { - return ::new(mem) T(std::forward(args)...); - } - catch (...) { - // Return the block to the pool before propagating -- otherwise a - // throwing T constructor permanently leaks a fixed-block-pool slot. - xfree(mem); - throw; - } -#endif - } - - /// @brief Destroy T and return its memory to the fixed-block pool. - template - inline void xdelete(T* p) - { - if (p) - { - p->~T(); - xfree(const_cast(static_cast(p))); - } - } -} - -#endif // _XNEW_H diff --git a/DelegateMQ/extras/allocator/xqueue.h b/DelegateMQ/extras/allocator/xqueue.h deleted file mode 100644 index 9936194..0000000 --- a/DelegateMQ/extras/allocator/xqueue.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef _XQUEUE_H -#define _XQUEUE_H - -#include "stl_allocator.h" -#include -#include - -namespace dmq { - -// xqueue uses a fix-block memory allocator -template > -using xqueue = std::queue>; - -} // namespace dmq - -#if 0 // Deprecated -template > > - class xqueue - : public std::queue<_Tp, _Sequence> - { - }; -#endif - -#endif - diff --git a/DelegateMQ/extras/allocator/xset.h b/DelegateMQ/extras/allocator/xset.h deleted file mode 100644 index dd42340..0000000 --- a/DelegateMQ/extras/allocator/xset.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef _XSET_H -#define _XSET_H - -#include "stl_allocator.h" -#include - -namespace dmq { - -// xset uses a fix-block memory allocator -template , typename Alloc = stl_allocator> -using xset = std::set; - -template , typename Alloc = stl_allocator> -using xmultiset = std::multiset; - -} // namespace dmq - -#if 0 // Deprecated -template, - class _Alloc = stl_allocator<_Kty> > - class xset - : public std::set<_Kty, _Pr, _Alloc> - { - }; - -/// @see xset -template, - class _Alloc = stl_allocator<_Kty> > - class xmultiset - : public std::multiset<_Kty, _Pr, _Alloc> - { - }; -#endif - -#endif diff --git a/DelegateMQ/extras/allocator/xsstream.h b/DelegateMQ/extras/allocator/xsstream.h deleted file mode 100644 index 83467a7..0000000 --- a/DelegateMQ/extras/allocator/xsstream.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef _XSSTREAM_H -#define _XSSTREAM_H - -#include "stl_allocator.h" -#include - -// std::string::traits_type, not std::char_traits: GCC with libc++ 17+ -// warns on naming std::char_traits (its primary template is deprecated). -namespace dmq { - typedef std::basic_stringstream > xstringstream; - typedef std::basic_ostringstream > xostringstream; -} -// xwstringstream/xwostringstream are unused by DelegateMQ. Uncomment if wide string support is needed by the application. -// typedef std::basic_stringstream > xwstringstream; -// typedef std::basic_ostringstream > xwostringstream; - - -#endif - diff --git a/DelegateMQ/extras/allocator/xstring.h b/DelegateMQ/extras/allocator/xstring.h deleted file mode 100644 index 31b7e36..0000000 --- a/DelegateMQ/extras/allocator/xstring.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef _XSTRING_H -#define _XSTRING_H - -#include "stl_allocator.h" -#include - -// std::string::traits_type, not std::char_traits: GCC with libc++ 17+ -// warns on naming std::char_traits (its primary template is deprecated). -namespace dmq { - typedef std::basic_string > xstring; -} -// xwstring is unused by DelegateMQ. Uncomment if wide string support is needed by the application. -// typedef std::basic_string > xwstring; - -#endif - diff --git a/DelegateMQ/extras/databus/DataBus.h b/DelegateMQ/extras/databus/DataBus.h deleted file mode 100644 index 93a8227..0000000 --- a/DelegateMQ/extras/databus/DataBus.h +++ /dev/null @@ -1,903 +0,0 @@ -#ifndef DMQ_DATABUS_H -#define DMQ_DATABUS_H - -/// @file -/// @brief Publish/subscribe message bus built on top of DelegateMQ's Signal -/// and remote delegate infrastructure. Routes typed topics to local -/// subscribers and, via Participant, to remote nodes. -/// -/// @details -/// `DataBus` is a process-wide singleton: components publish and subscribe by -/// topic string rather than holding direct references to each other. A topic's -/// C++ type is fixed by its first use and enforced afterward (see -/// `DataBus::SubscribeError`'s `ERR_TYPE_MISMATCH`). -/// -/// @code -/// auto conn = dmq::databus::DataBus::Subscribe( -/// "sensor/temperature", -/// [](const TemperatureMsg& msg) { /* handle it */ }); -/// -/// dmq::databus::DataBus::Publish("sensor/temperature", msg); -/// @endcode -/// -/// To span multiple processes/machines, see `NetworkNode` (this directory) -/// or manually wire a `Participant` — either way, see `docs/DATABUS.md` for -/// the full guide and `extras/databus/README.md` for a quickstart. - -#include "delegate/Signal.h" -#include "delegate/DelegateRemote.h" -#include "delegate/DelegateAsync.h" -#include "delegate/IThread.h" -#include "delegate/DelegateOpt.h" -#include "Participant.h" -#include "DataBusQos.h" -#include "SpyPacket.h" -#include "extras/util/Fault.h" -#include "extras/util/NetworkConnect.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::databus { - -namespace detail { - // Helper class to implement QoS rate limiting without lambda captures. - template - class RateLimiter { - XALLOCATOR - public: - RateLimiter(dmq::UnicastDelegate func, uint32_t minSepRep) - : m_func(std::move(func)), m_minSepRep(minSepRep), m_lastDeliveryRep(0) {} - - void Invoke(const T& data) { - auto nowRep = static_cast(std::chrono::duration_cast(dmq::Clock::now().time_since_epoch()).count()); - auto lastRep = m_lastDeliveryRep.load(std::memory_order_relaxed); - if (nowRep - lastRep >= m_minSepRep) { - m_lastDeliveryRep.store(nowRep, std::memory_order_relaxed); - m_func(data); - } - } - - private: - dmq::UnicastDelegate m_func; - uint32_t m_minSepRep; - std::atomic m_lastDeliveryRep; - }; - - // Helper class to implement QoS filtering without heavy lambda captures. - template - class Filter { - XALLOCATOR - public: - Filter(dmq::UnicastDelegate func, dmq::UnicastDelegate predicate) - : m_func(std::move(func)), m_predicate(std::move(predicate)) {} - - void Invoke(const T& data) { - if (m_predicate(data)) { - m_func(data); - } - } - - private: - dmq::UnicastDelegate m_func; - dmq::UnicastDelegate m_predicate; - }; - - // Holds an async subscriber's delegate for the life of its subscription. - // - // An async subscription is connected as a DelegateMemberAsync holding a - // shared_ptr to this holder. Every publish clones that delegate to queue the - // call; the clone copies only the shared_ptr. The subscriber used to be - // wrapped in a std::function (DelegateFunctionAsync) instead, and each clone - // then copied the std::function. libstdc++ (and libc++) keep a callable - // inline only if it's trivially copyable, which UnicastDelegate isn't, so on - // GCC/Clang toolchains every publish to an async subscriber made a global - // heap allocation outside DMQ_ALLOCATOR. MSVC kept it inline, which hid it. - // - // The holder is allocated once per subscription (xmake_shared). Every clone - // runs on the subscriber's own thread, so calls through it are sequential. - template - class AsyncSubscriber { - XALLOCATOR - public: - explicit AsyncSubscriber(dmq::UnicastDelegate func) - : m_func(std::move(func)) {} - - void Invoke(const Arg& data) { m_func(data); } - - private: - dmq::UnicastDelegate m_func; - }; - - // Build the async delegate for a subscriber on `thread` (see AsyncSubscriber). - template - dmq::DelegateMemberAsync, void(const Arg&)> - MakeAsyncSubscriber(dmq::UnicastDelegate func, dmq::IThread& thread) { - auto holder = dmq::xmake_shared>(std::move(func)); - return dmq::DelegateMemberAsync, void(const Arg&)>( - holder, &AsyncSubscriber::Invoke, thread); - } - -} - -// The DataBus is a central registry for topic-based communication. -// It allows components to publish and subscribe to data topics identified by strings. -// -// LIFETIME NOTE: This class assumes that any external ISerializer or ITransport objects -// passed to it (e.g., via AddParticipant or RegisterSerializer) will outlive -// the DataBus instance or its Reset() calls. -class DataBus { -public: - /// @brief Subscribe to a topic, with optional thread dispatch and QoS. - /// @tparam T Message type published to this topic. Must match the type - /// used by every other Publish/Subscribe/RegisterSerializer - /// call on the same topic string, or DataBus::SubscribeError - /// reports ERR_TYPE_MISMATCH. - /// @tparam F Callable type — a lambda, function pointer, member delegate, - /// or UnicastDelegate. Deduced from `func`. - /// @param topic Topic string to subscribe to. - /// @param func Called with each delivered T. Accepts any callable matching - /// void(const T&). - /// @param thread Optional. If non-null, `func` is dispatched asynchronously - /// on this thread instead of firing synchronously on the - /// publisher's thread. - /// @param qos Optional quality-of-service settings (e.g. last-value - /// cache, rate limiting). Defaults to no special behavior. - /// @return A ScopedConnection owning the subscription. [[nodiscard]] — - /// letting it go out of scope immediately unsubscribes with no - /// callbacks ever firing. Store it in a member variable or - /// container for as long as the subscription should stay active. - /// @note Signal connection is established before LVC delivery to ensure - /// no messages are missed. - /// @note Unsubscribing does not wait for a delivery already in progress on - /// a publisher's thread, and a message already queued on `thread` still - /// runs. If `func` captures an object, guard its lifetime before destroying - /// it right after unsubscribing (see the note in Signal.h). - template - [[nodiscard]] static dmq::ScopedConnection Subscribe(const dmq::xstring& topic, F&& func, dmq::IThread* thread = nullptr, QoS qos = {}) { - dmq::UnicastDelegate typedFunc; - if constexpr (std::is_base_of_v, std::decay_t>) - typedFunc = std::forward(func); // pre-formed delegate — direct assignment, no std::function - else - typedFunc = dmq::DelegateFunction(std::forward(func)); // bridge callable → const T& signature - return GetInstance().InternalSubscribe(topic, std::move(typedFunc), thread, qos); - } - - /// @brief Subscribe to a topic, but only receive deliveries for which - /// `predicate` returns true — messages that fail the predicate are - /// dropped before reaching `func`, without disconnecting the subscription. - /// @tparam T Message type published to this topic. Must match the - /// type used by every other Publish/Subscribe/ - /// RegisterSerializer call on the same topic string, or - /// DataBus::SubscribeError reports ERR_TYPE_MISMATCH. - /// @tparam F Callable type for `func` — a lambda, function pointer, - /// member delegate, or UnicastDelegate. - /// Deduced from `func`. - /// @tparam P Callable type for `predicate` — a lambda, function - /// pointer, member delegate, or - /// UnicastDelegate. Deduced from - /// `predicate`. - /// @param topic Topic string to subscribe to. - /// @param func Called with each delivered T for which `predicate` - /// returned true. Accepts any callable matching - /// void(const T&). - /// @param predicate Evaluated for every delivery on this topic, before - /// `func`. Accepts any callable matching - /// bool(const T&); returning false silently skips that - /// delivery. - /// @param thread Optional. `predicate` and `func` are evaluated - /// together as one unit: with no `thread`, both run - /// synchronously on the publisher's thread; with a - /// `thread`, both are dispatched there together instead. - /// @param qos Optional quality-of-service settings (e.g. last-value - /// cache, rate limiting). Defaults to no special - /// behavior. - /// @return A ScopedConnection owning the subscription. [[nodiscard]] — - /// letting it go out of scope immediately unsubscribes with no - /// callbacks ever firing. Store it in a member variable or - /// container for as long as the subscription should stay active. - template - [[nodiscard]] static dmq::ScopedConnection SubscribeFilter(const dmq::xstring& topic, F&& func, P&& predicate, dmq::IThread* thread = nullptr, QoS qos = {}) { - dmq::UnicastDelegate funcUD; - if constexpr (std::is_base_of_v, std::decay_t>) - funcUD = std::forward(func); - else - funcUD = dmq::DelegateFunction(std::forward(func)); - - dmq::UnicastDelegate predUD; - if constexpr (std::is_base_of_v, std::decay_t

>) - predUD = std::forward

(predicate); - else - predUD = dmq::DelegateFunction(std::forward

\n", pArg->out);
-      }else if( pArg->cMode==MODE_Count ){
-        char zBuf[200];
-        sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n",
-                         nRow, nRow!=1 ? "s" : "");
-        printf("%s", zBuf);
-      }
-    }
-  }
-}
-
-#ifndef SQLITE_OMIT_VIRTUALTABLE
-/*
-** This function is called to process SQL if the previous shell command
-** was ".expert". It passes the SQL in the second argument directly to
-** the sqlite3expert object.
-**
-** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
-** code. In this case, (*pzErr) may be set to point to a buffer containing
-** an English language error message. It is the responsibility of the
-** caller to eventually free this buffer using sqlite3_free().
-*/
-static int expertHandleSQL(
-  ShellState *pState,
-  const char *zSql,
-  char **pzErr
-){
-  assert( pState->expert.pExpert );
-  assert( pzErr==0 || *pzErr==0 );
-  return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
-}
-
-/*
-** This function is called either to silently clean up the object
-** created by the ".expert" command (if bCancel==1), or to generate a
-** report from it and then clean it up (if bCancel==0).
-**
-** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
-** code. In this case, (*pzErr) may be set to point to a buffer containing
-** an English language error message. It is the responsibility of the
-** caller to eventually free this buffer using sqlite3_free().
-*/
-static int expertFinish(
-  ShellState *pState,
-  int bCancel,
-  char **pzErr
-){
-  int rc = SQLITE_OK;
-  sqlite3expert *p = pState->expert.pExpert;
-  FILE *out = pState->out;
-  assert( p );
-  assert( bCancel || pzErr==0 || *pzErr==0 );
-  if( bCancel==0 ){
-    int bVerbose = pState->expert.bVerbose;
-
-    rc = sqlite3_expert_analyze(p, pzErr);
-    if( rc==SQLITE_OK ){
-      int nQuery = sqlite3_expert_count(p);
-      int i;
-
-      if( bVerbose ){
-        const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
-        sqlite3_fputs("-- Candidates -----------------------------\n", out);
-        sqlite3_fprintf(out, "%s\n", zCand);
-      }
-      for(i=0; iexpert.pExpert = 0;
-  return rc;
-}
-
-/*
-** Implementation of ".expert" dot command.
-*/
-static int expertDotCommand(
-  ShellState *pState,             /* Current shell tool state */
-  char **azArg,                   /* Array of arguments passed to dot command */
-  int nArg                        /* Number of entries in azArg[] */
-){
-  int rc = SQLITE_OK;
-  char *zErr = 0;
-  int i;
-  int iSample = 0;
-
-  assert( pState->expert.pExpert==0 );
-  memset(&pState->expert, 0, sizeof(ExpertInfo));
-
-  for(i=1; rc==SQLITE_OK && i=2 && 0==cli_strncmp(z, "-verbose", n) ){
-      pState->expert.bVerbose = 1;
-    }
-    else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){
-      if( i==(nArg-1) ){
-        sqlite3_fprintf(stderr, "option requires an argument: %s\n", z);
-        rc = SQLITE_ERROR;
-      }else{
-        iSample = (int)integerValue(azArg[++i]);
-        if( iSample<0 || iSample>100 ){
-          sqlite3_fprintf(stderr,"value out of range: %s\n", azArg[i]);
-          rc = SQLITE_ERROR;
-        }
-      }
-    }
-    else{
-      sqlite3_fprintf(stderr,"unknown option: %s\n", z);
-      rc = SQLITE_ERROR;
-    }
-  }
-
-  if( rc==SQLITE_OK ){
-    pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
-    if( pState->expert.pExpert==0 ){
-      sqlite3_fprintf(stderr,
-          "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory");
-      rc = SQLITE_ERROR;
-    }else{
-      sqlite3_expert_config(
-          pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
-      );
-    }
-  }
-  sqlite3_free(zErr);
-
-  return rc;
-}
-#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
-
-/*
-** Execute a statement or set of statements.  Print
-** any result rows/columns depending on the current mode
-** set via the supplied callback.
-**
-** This is very similar to SQLite's built-in sqlite3_exec()
-** function except it takes a slightly different callback
-** and callback data argument.
-*/
-static int shell_exec(
-  ShellState *pArg,                         /* Pointer to ShellState */
-  const char *zSql,                         /* SQL to be evaluated */
-  char **pzErrMsg                           /* Error msg written here */
-){
-  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
-  int rc = SQLITE_OK;             /* Return Code */
-  int rc2;
-  const char *zLeftover;          /* Tail of unprocessed SQL */
-  sqlite3 *db = pArg->db;
-
-  if( pzErrMsg ){
-    *pzErrMsg = NULL;
-  }
-
-#ifndef SQLITE_OMIT_VIRTUALTABLE
-  if( pArg->expert.pExpert ){
-    rc = expertHandleSQL(pArg, zSql, pzErrMsg);
-    return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
-  }
-#endif
-
-  while( zSql[0] && (SQLITE_OK == rc) ){
-    static const char *zStmtSql;
-    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
-    if( SQLITE_OK != rc ){
-      if( pzErrMsg ){
-        *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql);
-      }
-    }else{
-      if( !pStmt ){
-        /* this happens for a comment or white-space */
-        zSql = zLeftover;
-        while( IsSpace(zSql[0]) ) zSql++;
-        continue;
-      }
-      zStmtSql = sqlite3_sql(pStmt);
-      if( zStmtSql==0 ) zStmtSql = "";
-      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
-
-      /* save off the prepared statement handle and reset row count */
-      if( pArg ){
-        pArg->pStmt = pStmt;
-        pArg->cnt = 0;
-      }
-
-      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
-      if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
-        sqlite3_stmt *pExplain;
-        int triggerEQP = 0;
-        disable_debug_trace_modes();
-        sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
-        if( pArg->autoEQP>=AUTOEQP_trigger ){
-          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
-        }
-        pExplain = pStmt;
-        sqlite3_reset(pExplain);
-        rc = sqlite3_stmt_explain(pExplain, 2);
-        if( rc==SQLITE_OK ){
-          bind_prepared_stmt(pArg, pExplain);
-          while( sqlite3_step(pExplain)==SQLITE_ROW ){
-            const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
-            int iEqpId = sqlite3_column_int(pExplain, 0);
-            int iParentId = sqlite3_column_int(pExplain, 1);
-            if( zEQPLine==0 ) zEQPLine = "";
-            if( zEQPLine[0]=='-' ) eqp_render(pArg, 0);
-            eqp_append(pArg, iEqpId, iParentId, zEQPLine);
-          }
-          eqp_render(pArg, 0);
-        }
-        if( pArg->autoEQP>=AUTOEQP_full ){
-          /* Also do an EXPLAIN for ".eqp full" mode */
-          sqlite3_reset(pExplain);
-          rc = sqlite3_stmt_explain(pExplain, 1);
-          if( rc==SQLITE_OK ){
-            pArg->cMode = MODE_Explain;
-            assert( sqlite3_stmt_isexplain(pExplain)==1 );
-            bind_prepared_stmt(pArg, pExplain);
-            explain_data_prepare(pArg, pExplain);
-            exec_prepared_stmt(pArg, pExplain);
-            explain_data_delete(pArg);
-          }
-        }
-        if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
-          sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
-        }
-        sqlite3_reset(pStmt);
-        sqlite3_stmt_explain(pStmt, 0);
-        restore_debug_trace_modes();
-      }
-
-      if( pArg ){
-        int bIsExplain = (sqlite3_stmt_isexplain(pStmt)==1);
-        pArg->cMode = pArg->mode;
-        if( pArg->autoExplain ){
-          if( bIsExplain ){
-            pArg->cMode = MODE_Explain;
-          }
-          if( sqlite3_stmt_isexplain(pStmt)==2 ){
-            pArg->cMode = MODE_EQP;
-          }
-        }
-
-        /* If the shell is currently in ".explain" mode, gather the extra
-        ** data required to add indents to the output.*/
-        if( pArg->cMode==MODE_Explain && bIsExplain ){
-          explain_data_prepare(pArg, pStmt);
-        }
-      }
-
-      bind_prepared_stmt(pArg, pStmt);
-      exec_prepared_stmt(pArg, pStmt);
-      explain_data_delete(pArg);
-      eqp_render(pArg, 0);
-
-      /* print usage stats if stats on */
-      if( pArg && pArg->statsOn ){
-        display_stats(db, pArg, 0);
-      }
-
-      /* print loop-counters if required */
-      if( pArg && pArg->scanstatsOn ){
-        display_scanstats(db, pArg);
-      }
-
-      /* Finalize the statement just executed. If this fails, save a
-      ** copy of the error message. Otherwise, set zSql to point to the
-      ** next statement to execute. */
-      rc2 = sqlite3_finalize(pStmt);
-      if( rc!=SQLITE_NOMEM ) rc = rc2;
-      if( rc==SQLITE_OK ){
-        zSql = zLeftover;
-        while( IsSpace(zSql[0]) ) zSql++;
-      }else if( pzErrMsg ){
-        *pzErrMsg = save_err_msg(db, "stepping", rc, 0);
-      }
-
-      /* clear saved stmt handle */
-      if( pArg ){
-        pArg->pStmt = NULL;
-      }
-    }
-  } /* end while */
-
-  return rc;
-}
-
-/*
-** Release memory previously allocated by tableColumnList().
-*/
-static void freeColumnList(char **azCol){
-  int i;
-  for(i=1; azCol[i]; i++){
-    sqlite3_free(azCol[i]);
-  }
-  /* azCol[0] is a static string */
-  sqlite3_free(azCol);
-}
-
-/*
-** Return a list of pointers to strings which are the names of all
-** columns in table zTab.   The memory to hold the names is dynamically
-** allocated and must be released by the caller using a subsequent call
-** to freeColumnList().
-**
-** The azCol[0] entry is usually NULL.  However, if zTab contains a rowid
-** value that needs to be preserved, then azCol[0] is filled in with the
-** name of the rowid column.
-**
-** The first regular column in the table is azCol[1].  The list is terminated
-** by an entry with azCol[i]==0.
-*/
-static char **tableColumnList(ShellState *p, const char *zTab){
-  char **azCol = 0;
-  sqlite3_stmt *pStmt;
-  char *zSql;
-  int nCol = 0;
-  int nAlloc = 0;
-  int nPK = 0;       /* Number of PRIMARY KEY columns seen */
-  int isIPK = 0;     /* True if one PRIMARY KEY column of type INTEGER */
-  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
-  int rc;
-
-  zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
-  shell_check_oom(zSql);
-  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
-  sqlite3_free(zSql);
-  if( rc ) return 0;
-  while( sqlite3_step(pStmt)==SQLITE_ROW ){
-    if( nCol>=nAlloc-2 ){
-      nAlloc = nAlloc*2 + nCol + 10;
-      azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
-      shell_check_oom(azCol);
-    }
-    azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
-    shell_check_oom(azCol[nCol]);
-    if( sqlite3_column_int(pStmt, 5) ){
-      nPK++;
-      if( nPK==1
-       && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
-                          "INTEGER")==0
-      ){
-        isIPK = 1;
-      }else{
-        isIPK = 0;
-      }
-    }
-  }
-  sqlite3_finalize(pStmt);
-  if( azCol==0 ) return 0;
-  azCol[0] = 0;
-  azCol[nCol+1] = 0;
-
-  /* The decision of whether or not a rowid really needs to be preserved
-  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
-  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
-  ** rowids on tables where the rowid is inaccessible because there are other
-  ** columns in the table named "rowid", "_rowid_", and "oid".
-  */
-  if( preserveRowid && isIPK ){
-    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
-    ** might be an alias for the ROWID.  But it might also be a WITHOUT ROWID
-    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
-    ** ROWID aliases.  To distinguish these cases, check to see if
-    ** there is a "pk" entry in "PRAGMA index_list".  There will be
-    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
-    */
-    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
-                           " WHERE origin='pk'", zTab);
-    shell_check_oom(zSql);
-    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
-    sqlite3_free(zSql);
-    if( rc ){
-      freeColumnList(azCol);
-      return 0;
-    }
-    rc = sqlite3_step(pStmt);
-    sqlite3_finalize(pStmt);
-    preserveRowid = rc==SQLITE_ROW;
-  }
-  if( preserveRowid ){
-    /* Only preserve the rowid if we can find a name to use for the
-    ** rowid */
-    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
-    int i, j;
-    for(j=0; j<3; j++){
-      for(i=1; i<=nCol; i++){
-        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
-      }
-      if( i>nCol ){
-        /* At this point, we know that azRowid[j] is not the name of any
-        ** ordinary column in the table.  Verify that azRowid[j] is a valid
-        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
-        ** tables will fail this last check */
-        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
-        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
-        break;
-      }
-    }
-  }
-  return azCol;
-}
-
-/*
-** Toggle the reverse_unordered_selects setting.
-*/
-static void toggleSelectOrder(sqlite3 *db){
-  sqlite3_stmt *pStmt = 0;
-  int iSetting = 0;
-  char zStmt[100];
-  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
-  if( sqlite3_step(pStmt)==SQLITE_ROW ){
-    iSetting = sqlite3_column_int(pStmt, 0);
-  }
-  sqlite3_finalize(pStmt);
-  sqlite3_snprintf(sizeof(zStmt), zStmt,
-       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
-  sqlite3_exec(db, zStmt, 0, 0, 0);
-}
-
-/*
-** This is a different callback routine used for dumping the database.
-** Each row received by this callback consists of a table name,
-** the table type ("index" or "table") and SQL to create the table.
-** This routine should print text sufficient to recreate the table.
-*/
-static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
-  int rc;
-  const char *zTable;
-  const char *zType;
-  const char *zSql;
-  ShellState *p = (ShellState *)pArg;
-  int dataOnly;
-  int noSys;
-
-  UNUSED_PARAMETER(azNotUsed);
-  if( nArg!=3 || azArg==0 ) return 0;
-  zTable = azArg[0];
-  zType = azArg[1];
-  zSql = azArg[2];
-  if( zTable==0 ) return 0;
-  if( zType==0 ) return 0;
-  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
-  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
-
-  if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
-    /* no-op */
-  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
-    if( !dataOnly ) sqlite3_fputs("ANALYZE sqlite_schema;\n", p->out);
-  }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){
-    return 0;
-  }else if( dataOnly ){
-    /* no-op */
-  }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
-    char *zIns;
-    if( !p->writableSchema ){
-      sqlite3_fputs("PRAGMA writable_schema=ON;\n", p->out);
-      p->writableSchema = 1;
-    }
-    zIns = sqlite3_mprintf(
-       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
-       "VALUES('table','%q','%q',0,'%q');",
-       zTable, zTable, zSql);
-    shell_check_oom(zIns);
-    sqlite3_fprintf(p->out, "%s\n", zIns);
-    sqlite3_free(zIns);
-    return 0;
-  }else{
-    printSchemaLine(p->out, zSql, ";\n");
-  }
-
-  if( cli_strcmp(zType, "table")==0 ){
-    ShellText sSelect;
-    ShellText sTable;
-    char **azCol;
-    int i;
-    char *savedDestTable;
-    int savedMode;
-
-    azCol = tableColumnList(p, zTable);
-    if( azCol==0 ){
-      p->nErr++;
-      return 0;
-    }
-
-    /* Always quote the table name, even if it appears to be pure ascii,
-    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
-    initText(&sTable);
-    appendText(&sTable, zTable, quoteChar(zTable));
-    /* If preserving the rowid, add a column list after the table name.
-    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
-    ** instead of the usual "INSERT INTO tab VALUES(...)".
-    */
-    if( azCol[0] ){
-      appendText(&sTable, "(", 0);
-      appendText(&sTable, azCol[0], 0);
-      for(i=1; azCol[i]; i++){
-        appendText(&sTable, ",", 0);
-        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
-      }
-      appendText(&sTable, ")", 0);
-    }
-
-    /* Build an appropriate SELECT statement */
-    initText(&sSelect);
-    appendText(&sSelect, "SELECT ", 0);
-    if( azCol[0] ){
-      appendText(&sSelect, azCol[0], 0);
-      appendText(&sSelect, ",", 0);
-    }
-    for(i=1; azCol[i]; i++){
-      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
-      if( azCol[i+1] ){
-        appendText(&sSelect, ",", 0);
-      }
-    }
-    freeColumnList(azCol);
-    appendText(&sSelect, " FROM ", 0);
-    appendText(&sSelect, zTable, quoteChar(zTable));
-
-    savedDestTable = p->zDestTable;
-    savedMode = p->mode;
-    p->zDestTable = sTable.z;
-    p->mode = p->cMode = MODE_Insert;
-    rc = shell_exec(p, sSelect.z, 0);
-    if( (rc&0xff)==SQLITE_CORRUPT ){
-      sqlite3_fputs("/****** CORRUPTION ERROR *******/\n", p->out);
-      toggleSelectOrder(p->db);
-      shell_exec(p, sSelect.z, 0);
-      toggleSelectOrder(p->db);
-    }
-    p->zDestTable = savedDestTable;
-    p->mode = savedMode;
-    freeText(&sTable);
-    freeText(&sSelect);
-    if( rc ) p->nErr++;
-  }
-  return 0;
-}
-
-/*
-** Run zQuery.  Use dump_callback() as the callback routine so that
-** the contents of the query are output as SQL statements.
-**
-** If we get a SQLITE_CORRUPT error, rerun the query after appending
-** "ORDER BY rowid DESC" to the end.
-*/
-static int run_schema_dump_query(
-  ShellState *p,
-  const char *zQuery
-){
-  int rc;
-  char *zErr = 0;
-  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
-  if( rc==SQLITE_CORRUPT ){
-    char *zQ2;
-    int len = strlen30(zQuery);
-    sqlite3_fputs("/****** CORRUPTION ERROR *******/\n", p->out);
-    if( zErr ){
-      sqlite3_fprintf(p->out, "/****** %s ******/\n", zErr);
-      sqlite3_free(zErr);
-      zErr = 0;
-    }
-    zQ2 = malloc( len+100 );
-    if( zQ2==0 ) return rc;
-    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
-    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
-    if( rc ){
-      sqlite3_fprintf(p->out, "/****** ERROR: %s ******/\n", zErr);
-    }else{
-      rc = SQLITE_CORRUPT;
-    }
-    sqlite3_free(zErr);
-    free(zQ2);
-  }
-  return rc;
-}
-
-/*
-** Text of help messages.
-**
-** The help text for each individual command begins with a line that starts
-** with ".".  Subsequent lines are supplemental information.
-**
-** There must be two or more spaces between the end of the command and the
-** start of the description of what that command does.
-*/
-static const char *(azHelp[]) = {
-#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \
-  && !defined(SQLITE_SHELL_FIDDLE)
-  ".archive ...             Manage SQL archives",
-  "   Each command must have exactly one of the following options:",
-  "     -c, --create               Create a new archive",
-  "     -u, --update               Add or update files with changed mtime",
-  "     -i, --insert               Like -u but always add even if unchanged",
-  "     -r, --remove               Remove files from archive",
-  "     -t, --list                 List contents of archive",
-  "     -x, --extract              Extract files from archive",
-  "   Optional arguments:",
-  "     -v, --verbose              Print each filename as it is processed",
-  "     -f FILE, --file FILE       Use archive FILE (default is current db)",
-  "     -a FILE, --append FILE     Open FILE using the apndvfs VFS",
-  "     -C DIR, --directory DIR    Read/extract files from directory DIR",
-  "     -g, --glob                 Use glob matching for names in archive",
-  "     -n, --dryrun               Show the SQL that would have occurred",
-  "   Examples:",
-  "     .ar -cf ARCHIVE foo bar  # Create ARCHIVE from files foo and bar",
-  "     .ar -tf ARCHIVE          # List members of ARCHIVE",
-  "     .ar -xvf ARCHIVE         # Verbosely extract files from ARCHIVE",
-  "   See also:",
-  "      http://sqlite.org/cli.html#sqlite_archive_support",
-#endif
-#ifndef SQLITE_OMIT_AUTHORIZATION
-  ".auth ON|OFF             Show authorizer callbacks",
-#endif
-#ifndef SQLITE_SHELL_FIDDLE
-  ".backup ?DB? FILE        Backup DB (default \"main\") to FILE",
-  "   Options:",
-  "       --append            Use the appendvfs",
-  "       --async             Write to FILE without journal and fsync()",
-#endif
-  ".bail on|off             Stop after hitting an error.  Default OFF",
-#ifndef SQLITE_SHELL_FIDDLE
-  ".cd DIRECTORY            Change the working directory to DIRECTORY",
-#endif
-  ".changes on|off          Show number of rows changed by SQL",
-#ifndef SQLITE_SHELL_FIDDLE
-  ".check GLOB              Fail if output since .testcase does not match",
-  ".clone NEWDB             Clone data into NEWDB from the existing database",
-#endif
-  ".connection [close] [#]  Open or close an auxiliary database connection",
-  ".crlf ?on|off?           Whether or not to use \\r\\n line endings",
-  ".databases               List names and files of attached databases",
-  ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
-#if SQLITE_SHELL_HAVE_RECOVER
-  ".dbinfo ?DB?             Show status information about the database",
-#endif
-  ".dump ?OBJECTS?          Render database content as SQL",
-  "   Options:",
-  "     --data-only            Output only INSERT statements",
-  "     --newlines             Allow unescaped newline characters in output",
-  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
-  "     --preserve-rowids      Include ROWID values in the output",
-  "   OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump",
-  "   Additional LIKE patterns can be given in subsequent arguments",
-  ".echo on|off             Turn command echo on or off",
-  ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
-  "   Other Modes:",
-#ifdef SQLITE_DEBUG
-  "      test                  Show raw EXPLAIN QUERY PLAN output",
-  "      trace                 Like \"full\" but enable \"PRAGMA vdbe_trace\"",
-#endif
-  "      trigger               Like \"full\" but also show trigger bytecode",
-#ifndef SQLITE_SHELL_FIDDLE
-  ".excel                   Display the output of next command in spreadsheet",
-  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
-#endif
-#ifndef SQLITE_SHELL_FIDDLE
-  ".exit ?CODE?             Exit this program with return-code CODE",
-#endif
-  ".expert                  EXPERIMENTAL. Suggest indexes for queries",
-  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
-  ".filectrl CMD ...        Run various sqlite3_file_control() operations",
-  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
-  "   --help                  Show CMD details",
-  ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
-  ".headers on|off          Turn display of headers on or off",
-  ".help ?-all? ?PATTERN?   Show help text for PATTERN",
-#ifndef SQLITE_SHELL_FIDDLE
-  ".import FILE TABLE       Import data from FILE into TABLE",
-  "   Options:",
-  "     --ascii               Use \\037 and \\036 as column and row separators",
-  "     --csv                 Use , and \\n as column and row separators",
-  "     --skip N              Skip the first N rows of input",
-  "     --schema S            Target table to be S.TABLE",
-  "     -v                    \"Verbose\" - increase auxiliary output",
-  "   Notes:",
-  "     *  If TABLE does not exist, it is created.  The first row of input",
-  "        determines the column names.",
-  "     *  If neither --csv or --ascii are used, the input mode is derived",
-  "        from the \".mode\" output mode",
-  "     *  If FILE begins with \"|\" then it is a command that generates the",
-  "        input text.",
-#endif
-#ifndef SQLITE_OMIT_TEST_CONTROL
-  ",imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
-#endif
-  ".indexes ?TABLE?         Show names of indexes",
-  "                           If TABLE is specified, only show indexes for",
-  "                           tables matching TABLE using the LIKE operator.",
-  ".intck ?STEPS_PER_UNLOCK?  Run an incremental integrity check on the db",
-#ifdef SQLITE_ENABLE_IOTRACE
-  ",iotrace FILE            Enable I/O diagnostic logging to FILE",
-#endif
-  ".limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT",
-  ".lint OPTIONS            Report potential schema issues.",
-  "     Options:",
-  "        fkey-indexes     Find missing foreign key indexes",
-#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE)
-  ".load FILE ?ENTRY?       Load an extension library",
-#endif
-#if !defined(SQLITE_SHELL_FIDDLE)
-  ".log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout",
-#else
-  ".log on|off              Turn logging on or off.",
-#endif
-  ".mode MODE ?OPTIONS?     Set output mode",
-  "   MODE is one of:",
-  "     ascii       Columns/rows delimited by 0x1F and 0x1E",
-  "     box         Tables using unicode box-drawing characters",
-  "     csv         Comma-separated values",
-  "     column      Output in columns.  (See .width)",
-  "     html        HTML  code",
-  "     insert      SQL insert statements for TABLE",
-  "     json        Results in a JSON array",
-  "     line        One value per line",
-  "     list        Values delimited by \"|\"",
-  "     markdown    Markdown table format",
-  "     qbox        Shorthand for \"box --wrap 60 --quote\"",
-  "     quote       Escape answers as for SQL",
-  "     table       ASCII-art table",
-  "     tabs        Tab-separated values",
-  "     tcl         TCL list elements",
-  "   OPTIONS: (for columnar modes or insert mode):",
-  "     --wrap N       Wrap output lines to no longer than N characters",
-  "     --wordwrap B   Wrap or not at word boundaries per B (on/off)",
-  "     --ww           Shorthand for \"--wordwrap 1\"",
-  "     --quote        Quote output text as SQL literals",
-  "     --noquote      Do not quote output text",
-  "     TABLE          The name of SQL table used for \"insert\" mode",
-#ifndef SQLITE_SHELL_FIDDLE
-  ".nonce STRING            Suspend safe mode for one command if nonce matches",
-#endif
-  ".nullvalue STRING        Use STRING in place of NULL values",
-#ifndef SQLITE_SHELL_FIDDLE
-  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
-  "     If FILE begins with '|' then open as a pipe",
-  "       --bom    Put a UTF8 byte-order mark at the beginning",
-  "       -e       Send output to the system text editor",
-  "       --plain  Use text/plain output instead of HTML for -w option",
-  "       -w       Send output as HTML to a web browser (same as \".www\")",
-  "       -x       Send output as CSV to a spreadsheet (same as \".excel\")",
-  /* Note that .open is (partially) available in WASM builds but is
-  ** currently only intended to be used by the fiddle tool, not
-  ** end users, so is "undocumented." */
-  ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
-  "     Options:",
-  "        --append        Use appendvfs to append database to the end of FILE",
-#endif
-#ifndef SQLITE_OMIT_DESERIALIZE
-  "        --deserialize   Load into memory using sqlite3_deserialize()",
-  "        --hexdb         Load the output of \"dbtotxt\" as an in-memory db",
-  "        --maxsize N     Maximum size for --hexdb or --deserialized database",
-#endif
-  "        --new           Initialize FILE to an empty database",
-  "        --nofollow      Do not follow symbolic links",
-  "        --readonly      Open FILE readonly",
-  "        --zip           FILE is a ZIP archive",
-#ifndef SQLITE_SHELL_FIDDLE
-  ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
-  "   If FILE begins with '|' then open it as a pipe.",
-  "   Options:",
-  "     --bom                 Prefix output with a UTF8 byte-order mark",
-  "     -e                    Send output to the system text editor",
-  "     --plain               Use text/plain for -w option",
-  "     -w                    Send output to a web browser",
-  "     -x                    Send output as CSV to a spreadsheet",
-#endif
-  ".parameter CMD ...       Manage SQL parameter bindings",
-  "   clear                   Erase all bindings",
-  "   init                    Initialize the TEMP table that holds bindings",
-  "   list                    List the current parameter bindings",
-  "   set PARAMETER VALUE     Given SQL parameter PARAMETER a value of VALUE",
-  "                           PARAMETER should start with one of: $ : @ ?",
-  "   unset PARAMETER         Remove PARAMETER from the binding table",
-  ".print STRING...         Print literal STRING",
-#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
-  ".progress N              Invoke progress handler after every N opcodes",
-  "   --limit N                 Interrupt after N progress callbacks",
-  "   --once                    Do no more than one progress interrupt",
-  "   --quiet|-q                No output except at interrupts",
-  "   --reset                   Reset the count for each input and interrupt",
-#endif
-  ".prompt MAIN CONTINUE    Replace the standard prompts",
-#ifndef SQLITE_SHELL_FIDDLE
-  ".quit                    Stop interpreting input stream, exit if primary.",
-  ".read FILE               Read input from FILE or command output",
-  "    If FILE begins with \"|\", it is a command that generates the input.",
-#endif
-#if SQLITE_SHELL_HAVE_RECOVER
-  ".recover                 Recover as much data as possible from corrupt db.",
-  "   --ignore-freelist        Ignore pages that appear to be on db freelist",
-  "   --lost-and-found TABLE   Alternative name for the lost-and-found table",
-  "   --no-rowids              Do not attempt to recover rowid values",
-  "                            that are not also INTEGER PRIMARY KEYs",
-#endif
-#ifndef SQLITE_SHELL_FIDDLE
-  ".restore ?DB? FILE       Restore content of DB (default \"main\") from FILE",
-  ".save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)",
-#endif
-  ".scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off",
-  ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
-  "   Options:",
-  "      --indent             Try to pretty-print the schema",
-  "      --nosys              Omit objects whose names start with \"sqlite_\"",
-  ",selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
-  "    Options:",
-  "       --init               Create a new SELFTEST table",
-  "       -v                   Verbose output",
-  ".separator COL ?ROW?     Change the column and row separators",
-#if defined(SQLITE_ENABLE_SESSION)
-  ".session ?NAME? CMD ...  Create or control sessions",
-  "   Subcommands:",
-  "     attach TABLE             Attach TABLE",
-  "     changeset FILE           Write a changeset into FILE",
-  "     close                    Close one session",
-  "     enable ?BOOLEAN?         Set or query the enable bit",
-  "     filter GLOB...           Reject tables matching GLOBs",
-  "     indirect ?BOOLEAN?       Mark or query the indirect status",
-  "     isempty                  Query whether the session is empty",
-  "     list                     List currently open session names",
-  "     open DB NAME             Open a new session on DB",
-  "     patchset FILE            Write a patchset into FILE",
-  "   If ?NAME? is omitted, the first defined session is used.",
-#endif
-  ".sha3sum ...             Compute a SHA3 hash of database content",
-  "    Options:",
-  "      --schema              Also hash the sqlite_schema table",
-  "      --sha3-224            Use the sha3-224 algorithm",
-  "      --sha3-256            Use the sha3-256 algorithm (default)",
-  "      --sha3-384            Use the sha3-384 algorithm",
-  "      --sha3-512            Use the sha3-512 algorithm",
-  "    Any other argument is a LIKE pattern for tables to hash",
-#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
-  ".shell CMD ARGS...       Run CMD ARGS... in a system shell",
-#endif
-  ".show                    Show the current values for various settings",
-  ".stats ?ARG?             Show stats or turn stats on or off",
-  "   off                      Turn off automatic stat display",
-  "   on                       Turn on automatic stat display",
-  "   stmt                     Show statement stats",
-  "   vmstep                   Show the virtual machine step count only",
-#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE)
-  ".system CMD ARGS...      Run CMD ARGS... in a system shell",
-#endif
-  ".tables ?TABLE?          List names of tables matching LIKE pattern TABLE",
-#ifndef SQLITE_SHELL_FIDDLE
-  ",testcase NAME           Begin redirecting output to 'testcase-out.txt'",
-#endif
-  ",testctrl CMD ...        Run various sqlite3_test_control() operations",
-  "                           Run \".testctrl\" with no arguments for details",
-  ".timeout MS              Try opening locked tables for MS milliseconds",
-  ".timer on|off            Turn SQL timer on or off",
-#ifndef SQLITE_OMIT_TRACE
-  ".trace ?OPTIONS?         Output each SQL statement as it is run",
-  "    FILE                    Send output to FILE",
-  "    stdout                  Send output to stdout",
-  "    stderr                  Send output to stderr",
-  "    off                     Disable tracing",
-  "    --expanded              Expand query parameters",
-#ifdef SQLITE_ENABLE_NORMALIZE
-  "    --normalized            Normal the SQL statements",
-#endif
-  "    --plain                 Show SQL as it is input",
-  "    --stmt                  Trace statement execution (SQLITE_TRACE_STMT)",
-  "    --profile               Profile statements (SQLITE_TRACE_PROFILE)",
-  "    --row                   Trace each row (SQLITE_TRACE_ROW)",
-  "    --close                 Trace connection close (SQLITE_TRACE_CLOSE)",
-#endif /* SQLITE_OMIT_TRACE */
-#ifdef SQLITE_DEBUG
-  ".unmodule NAME ...       Unregister virtual table modules",
-  "    --allexcept             Unregister everything except those named",
-#endif
-  ".version                 Show source, library and compiler versions",
-  ".vfsinfo ?AUX?           Information about the top-level VFS",
-  ".vfslist                 List all available VFSes",
-  ".vfsname ?AUX?           Print the name of the VFS stack",
-  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
-  "     Negative values right-justify",
-#ifndef SQLITE_SHELL_FIDDLE
-  ".www                     Display output of the next command in web browser",
-  "    --plain                 Show results as text/plain, not as HTML",
-#endif
-};
-
-/*
-** Output help text.
-**
-** zPattern describes the set of commands for which help text is provided.
-** If zPattern is NULL, then show all commands, but only give a one-line
-** description of each.
-**
-** Return the number of matches.
-*/
-static int showHelp(FILE *out, const char *zPattern){
-  int i = 0;
-  int j = 0;
-  int n = 0;
-  char *zPat;
-  if( zPattern==0
-   || zPattern[0]=='0'
-   || cli_strcmp(zPattern,"-a")==0
-   || cli_strcmp(zPattern,"-all")==0
-   || cli_strcmp(zPattern,"--all")==0
-  ){
-    enum HelpWanted { HW_NoCull = 0, HW_SummaryOnly = 1, HW_Undoc = 2 };
-    enum HelpHave { HH_Undoc = 2, HH_Summary = 1, HH_More = 0 };
-    /* Show all or most commands
-    ** *zPattern==0   => summary of documented commands only
-    ** *zPattern=='0' => whole help for undocumented commands
-    ** Otherwise      => whole help for documented commands
-    */
-    enum HelpWanted hw = HW_SummaryOnly;
-    enum HelpHave hh = HH_More;
-    if( zPattern!=0 ){
-      hw = (*zPattern=='0')? HW_NoCull|HW_Undoc : HW_NoCull;
-    }
-    for(i=0; ip);
-  sqlite3_free(pSession->zName);
-  for(i=0; inFilter; i++){
-    sqlite3_free(pSession->azFilter[i]);
-  }
-  sqlite3_free(pSession->azFilter);
-  memset(pSession, 0, sizeof(OpenSession));
-}
-#endif
-
-/*
-** Close all OpenSession objects and release all associated resources.
-*/
-#if defined(SQLITE_ENABLE_SESSION)
-static void session_close_all(ShellState *p, int i){
-  int j;
-  struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i];
-  for(j=0; jnSession; j++){
-    session_close(&pAuxDb->aSession[j]);
-  }
-  pAuxDb->nSession = 0;
-}
-#else
-# define session_close_all(X,Y)
-#endif
-
-/*
-** Implementation of the xFilter function for an open session.  Omit
-** any tables named by ".session filter" but let all other table through.
-*/
-#if defined(SQLITE_ENABLE_SESSION)
-static int session_filter(void *pCtx, const char *zTab){
-  OpenSession *pSession = (OpenSession*)pCtx;
-  int i;
-  for(i=0; inFilter; i++){
-    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
-  }
-  return 1;
-}
-#endif
-
-/*
-** Try to deduce the type of file for zName based on its content.  Return
-** one of the SHELL_OPEN_* constants.
-**
-** If the file does not exist or is empty but its name looks like a ZIP
-** archive and the dfltZip flag is true, then assume it is a ZIP archive.
-** Otherwise, assume an ordinary database regardless of the filename if
-** the type cannot be determined from content.
-*/
-int deduceDatabaseType(const char *zName, int dfltZip){
-  FILE *f = sqlite3_fopen(zName, "rb");
-  size_t n;
-  int rc = SHELL_OPEN_UNSPEC;
-  char zBuf[100];
-  if( f==0 ){
-    if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
-       return SHELL_OPEN_ZIPFILE;
-    }else{
-       return SHELL_OPEN_NORMAL;
-    }
-  }
-  n = fread(zBuf, 16, 1, f);
-  if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
-    fclose(f);
-    return SHELL_OPEN_NORMAL;
-  }
-  fseek(f, -25, SEEK_END);
-  n = fread(zBuf, 25, 1, f);
-  if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
-    rc = SHELL_OPEN_APPENDVFS;
-  }else{
-    fseek(f, -22, SEEK_END);
-    n = fread(zBuf, 22, 1, f);
-    if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
-       && zBuf[3]==0x06 ){
-      rc = SHELL_OPEN_ZIPFILE;
-    }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
-      rc = SHELL_OPEN_ZIPFILE;
-    }
-  }
-  fclose(f);
-  return rc;
-}
-
-#ifndef SQLITE_OMIT_DESERIALIZE
-/*
-** Reconstruct an in-memory database using the output from the "dbtotxt"
-** program.  Read content from the file in p->aAuxDb[].zDbFilename.
-** If p->aAuxDb[].zDbFilename is 0, then read from standard input.
-*/
-static unsigned char *readHexDb(ShellState *p, int *pnData){
-  unsigned char *a = 0;
-  int nLine;
-  int n = 0;
-  int pgsz = 0;
-  int iOffset = 0;
-  int j, k;
-  int rc;
-  FILE *in;
-  const char *zDbFilename = p->pAuxDb->zDbFilename;
-  unsigned int x[16];
-  char zLine[1000];
-  if( zDbFilename ){
-    in = sqlite3_fopen(zDbFilename, "r");
-    if( in==0 ){
-      sqlite3_fprintf(stderr,"cannot open \"%s\" for reading\n", zDbFilename);
-      return 0;
-    }
-    nLine = 0;
-  }else{
-    in = p->in;
-    nLine = p->lineno;
-    if( in==0 ) in = stdin;
-  }
-  *pnData = 0;
-  nLine++;
-  if( sqlite3_fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
-  rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
-  if( rc!=2 ) goto readHexDb_error;
-  if( n<0 ) goto readHexDb_error;
-  if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
-  n = (n+pgsz-1)&~(pgsz-1);  /* Round n up to the next multiple of pgsz */
-  a = sqlite3_malloc( n ? n : 1 );
-  shell_check_oom(a);
-  memset(a, 0, n);
-  if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
-    sqlite3_fputs("invalid pagesize\n", stderr);
-    goto readHexDb_error;
-  }
-  for(nLine++; sqlite3_fgets(zLine, sizeof(zLine), in)!=0; nLine++){
-    rc = sscanf(zLine, "| page %d offset %d", &j, &k);
-    if( rc==2 ){
-      iOffset = k;
-      continue;
-    }
-    if( cli_strncmp(zLine, "| end ", 6)==0 ){
-      break;
-    }
-    rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
-                &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
-                &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
-    if( rc==17 ){
-      k = iOffset+j;
-      if( k+16<=n && k>=0 ){
-        int ii;
-        for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
-      }
-    }
-  }
-  *pnData = n;
-  if( in!=p->in ){
-    fclose(in);
-  }else{
-    p->lineno = nLine;
-  }
-  return a;
-
-readHexDb_error:
-  if( in!=p->in ){
-    fclose(in);
-  }else{
-    while( sqlite3_fgets(zLine, sizeof(zLine), p->in)!=0 ){
-      nLine++;
-      if(cli_strncmp(zLine, "| end ", 6)==0 ) break;
-    }
-    p->lineno = nLine;
-  }
-  sqlite3_free(a);
-  sqlite3_fprintf(stderr,"Error on line %d of --hexdb input\n", nLine);
-  return 0;
-}
-#endif /* SQLITE_OMIT_DESERIALIZE */
-
-/*
-** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
-*/
-static void shellUSleepFunc(
-  sqlite3_context *context,
-  int argcUnused,
-  sqlite3_value **argv
-){
-  int sleep = sqlite3_value_int(argv[0]);
-  (void)argcUnused;
-  sqlite3_sleep(sleep/1000);
-  sqlite3_result_int(context, sleep);
-}
-
-/* Flags for open_db().
-**
-** The default behavior of open_db() is to exit(1) if the database fails to
-** open.  The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
-** but still returns without calling exit.
-**
-** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
-** ZIP archive if the file does not exist or is empty and its name matches
-** the *.zip pattern.
-*/
-#define OPEN_DB_KEEPALIVE   0x001   /* Return after error if true */
-#define OPEN_DB_ZIPFILE     0x002   /* Open as ZIP if name matches *.zip */
-
-/*
-** Make sure the database is open.  If it is not, then open it.  If
-** the database fails to open, print an error message and exit.
-*/
-static void open_db(ShellState *p, int openFlags){
-  if( p->db==0 ){
-    const char *zDbFilename = p->pAuxDb->zDbFilename;
-    if( p->openMode==SHELL_OPEN_UNSPEC ){
-      if( zDbFilename==0 || zDbFilename[0]==0 ){
-        p->openMode = SHELL_OPEN_NORMAL;
-      }else{
-        p->openMode = (u8)deduceDatabaseType(zDbFilename,
-                             (openFlags & OPEN_DB_ZIPFILE)!=0);
-      }
-    }
-    switch( p->openMode ){
-      case SHELL_OPEN_APPENDVFS: {
-        sqlite3_open_v2(zDbFilename, &p->db,
-           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
-        break;
-      }
-      case SHELL_OPEN_HEXDB:
-      case SHELL_OPEN_DESERIALIZE: {
-        sqlite3_open(0, &p->db);
-        break;
-      }
-      case SHELL_OPEN_ZIPFILE: {
-        sqlite3_open(":memory:", &p->db);
-        break;
-      }
-      case SHELL_OPEN_READONLY: {
-        sqlite3_open_v2(zDbFilename, &p->db,
-            SQLITE_OPEN_READONLY|p->openFlags, 0);
-        break;
-      }
-      case SHELL_OPEN_UNSPEC:
-      case SHELL_OPEN_NORMAL: {
-        sqlite3_open_v2(zDbFilename, &p->db,
-           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
-        break;
-      }
-    }
-    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
-      sqlite3_fprintf(stderr,"Error: unable to open database \"%s\": %s\n",
-            zDbFilename, sqlite3_errmsg(p->db));
-      if( (openFlags & OPEN_DB_KEEPALIVE)==0 ){
-        exit(1);
-      }
-      sqlite3_close(p->db);
-      sqlite3_open(":memory:", &p->db);
-      if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
-        sqlite3_fputs("Also: unable to open substitute in-memory database.\n",
-                      stderr);
-        exit(1);
-      }else{
-        sqlite3_fprintf(stderr,
-              "Notice: using substitute in-memory database instead of \"%s\"\n",
-              zDbFilename);
-      }
-    }
-    globalDb = p->db;
-    sqlite3_db_config(p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, (int)0, (int*)0);
-
-    /* Reflect the use or absence of --unsafe-testing invocation. */
-    {
-      int testmode_on = ShellHasFlag(p,SHFLG_TestingMode);
-      sqlite3_db_config(p->db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, testmode_on,0);
-      sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, !testmode_on,0);
-    }
-
-#ifndef SQLITE_OMIT_LOAD_EXTENSION
-    sqlite3_enable_load_extension(p->db, 1);
-#endif
-    sqlite3_sha_init(p->db, 0, 0);
-    sqlite3_shathree_init(p->db, 0, 0);
-    sqlite3_uint_init(p->db, 0, 0);
-    sqlite3_stmtrand_init(p->db, 0, 0);
-    sqlite3_decimal_init(p->db, 0, 0);
-    sqlite3_percentile_init(p->db, 0, 0);
-    sqlite3_base64_init(p->db, 0, 0);
-    sqlite3_base85_init(p->db, 0, 0);
-    sqlite3_regexp_init(p->db, 0, 0);
-    sqlite3_ieee_init(p->db, 0, 0);
-    sqlite3_series_init(p->db, 0, 0);
-#ifndef SQLITE_SHELL_FIDDLE
-    sqlite3_fileio_init(p->db, 0, 0);
-    sqlite3_completion_init(p->db, 0, 0);
-#endif
-#ifdef SQLITE_HAVE_ZLIB
-    if( !p->bSafeModePersist ){
-      sqlite3_zipfile_init(p->db, 0, 0);
-      sqlite3_sqlar_init(p->db, 0, 0);
-    }
-#endif
-#ifdef SQLITE_SHELL_EXTFUNCS
-    /* Create a preprocessing mechanism for extensions to make
-     * their own provisions for being built into the shell.
-     * This is a short-span macro. See further below for usage.
-     */
-#define SHELL_SUB_MACRO(base, variant) base ## _ ## variant
-#define SHELL_SUBMACRO(base, variant) SHELL_SUB_MACRO(base, variant)
-    /* Let custom-included extensions get their ..._init() called.
-     * The WHATEVER_INIT( db, pzErrorMsg, pApi ) macro should cause
-     * the extension's sqlite3_*_init( db, pzErrorMsg, pApi )
-     * initialization routine to be called.
-     */
-    {
-      int irc = SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, INIT)(p->db);
-    /* Let custom-included extensions expose their functionality.
-     * The WHATEVER_EXPOSE( db, pzErrorMsg ) macro should cause
-     * the SQL functions, virtual tables, collating sequences or
-     * VFS's implemented by the extension to be registered.
-     */
-      if( irc==SQLITE_OK
-          || irc==SQLITE_OK_LOAD_PERMANENTLY ){
-        SHELL_SUBMACRO(SQLITE_SHELL_EXTFUNCS, EXPOSE)(p->db, 0);
-      }
-#undef SHELL_SUB_MACRO
-#undef SHELL_SUBMACRO
-    }
-#endif
-
-    sqlite3_create_function(p->db, "strtod", 1, SQLITE_UTF8, 0,
-                            shellStrtod, 0, 0);
-    sqlite3_create_function(p->db, "dtostr", 1, SQLITE_UTF8, 0,
-                            shellDtostr, 0, 0);
-    sqlite3_create_function(p->db, "dtostr", 2, SQLITE_UTF8, 0,
-                            shellDtostr, 0, 0);
-    sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
-                            shellAddSchemaName, 0, 0);
-    sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
-                            shellModuleSchema, 0, 0);
-    sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
-                            shellPutsFunc, 0, 0);
-    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
-                            shellUSleepFunc, 0, 0);
-#ifndef SQLITE_NOHAVE_SYSTEM
-    sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
-                            editFunc, 0, 0);
-    sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
-                            editFunc, 0, 0);
-#endif
-
-    if( p->openMode==SHELL_OPEN_ZIPFILE ){
-      char *zSql = sqlite3_mprintf(
-         "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename);
-      shell_check_oom(zSql);
-      sqlite3_exec(p->db, zSql, 0, 0, 0);
-      sqlite3_free(zSql);
-    }
-#ifndef SQLITE_OMIT_DESERIALIZE
-    else
-    if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
-      int rc;
-      int nData = 0;
-      unsigned char *aData;
-      if( p->openMode==SHELL_OPEN_DESERIALIZE ){
-        aData = (unsigned char*)readFile(zDbFilename, &nData);
-      }else{
-        aData = readHexDb(p, &nData);
-      }
-      if( aData==0 ){
-        return;
-      }
-      rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
-                   SQLITE_DESERIALIZE_RESIZEABLE |
-                   SQLITE_DESERIALIZE_FREEONCLOSE);
-      if( rc ){
-        sqlite3_fprintf(stderr,"Error: sqlite3_deserialize() returns %d\n", rc);
-      }
-      if( p->szMax>0 ){
-        sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
-      }
-    }
-#endif
-  }
-  if( p->db!=0 ){
-    if( p->bSafeModePersist ){
-      sqlite3_set_authorizer(p->db, safeModeAuth, p);
-    }
-    sqlite3_db_config(
-        p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0
-    );
-  }
-}
-
-/*
-** Attempt to close the database connection.  Report errors.
-*/
-void close_db(sqlite3 *db){
-  int rc = sqlite3_close(db);
-  if( rc ){
-    sqlite3_fprintf(stderr,
-        "Error: sqlite3_close() returns %d: %s\n", rc, sqlite3_errmsg(db));
-  }
-}
-
-#if HAVE_READLINE || HAVE_EDITLINE
-/*
-** Readline completion callbacks
-*/
-static char *readline_completion_generator(const char *text, int state){
-  static sqlite3_stmt *pStmt = 0;
-  char *zRet;
-  if( state==0 ){
-    char *zSql;
-    sqlite3_finalize(pStmt);
-    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
-                           "  FROM completion(%Q) ORDER BY 1", text);
-    shell_check_oom(zSql);
-    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
-    sqlite3_free(zSql);
-  }
-  if( sqlite3_step(pStmt)==SQLITE_ROW ){
-    const char *z = (const char*)sqlite3_column_text(pStmt,0);
-    zRet = z ? strdup(z) : 0;
-  }else{
-    sqlite3_finalize(pStmt);
-    pStmt = 0;
-    zRet = 0;
-  }
-  return zRet;
-}
-static char **readline_completion(const char *zText, int iStart, int iEnd){
-  (void)iStart;
-  (void)iEnd;
-  rl_attempted_completion_over = 1;
-  return rl_completion_matches(zText, readline_completion_generator);
-}
-
-#elif HAVE_LINENOISE
-/*
-** Linenoise completion callback. Note that the 3rd argument is from
-** the "msteveb" version of linenoise, not the "antirez" version.
-*/
-static void linenoise_completion(const char *zLine, linenoiseCompletions *lc,
-                                 void *pUserData){
-  i64 nLine = strlen(zLine);
-  i64 i, iStart;
-  sqlite3_stmt *pStmt = 0;
-  char *zSql;
-  char zBuf[1000];
-
-  UNUSED_PARAMETER(pUserData);
-  if( nLine>(i64)sizeof(zBuf)-30 ) return;
-  if( zLine[0]=='.' || zLine[0]=='#') return;
-  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
-  if( i==nLine-1 ) return;
-  iStart = i+1;
-  memcpy(zBuf, zLine, iStart);
-  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
-                         "  FROM completion(%Q,%Q) ORDER BY 1",
-                         &zLine[iStart], zLine);
-  shell_check_oom(zSql);
-  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
-  sqlite3_free(zSql);
-  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
-  while( sqlite3_step(pStmt)==SQLITE_ROW ){
-    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
-    int nCompletion = sqlite3_column_bytes(pStmt, 0);
-    if( iStart+nCompletion < (i64)sizeof(zBuf)-1 && zCompletion ){
-      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
-      linenoiseAddCompletion(lc, zBuf);
-    }
-  }
-  sqlite3_finalize(pStmt);
-}
-#endif
-
-/*
-** Do C-language style dequoting.
-**
-**    \a    -> alarm
-**    \b    -> backspace
-**    \t    -> tab
-**    \n    -> newline
-**    \v    -> vertical tab
-**    \f    -> form feed
-**    \r    -> carriage return
-**    \s    -> space
-**    \"    -> "
-**    \'    -> '
-**    \\    -> backslash
-**    \NNN  -> ascii character NNN in octal
-**    \xHH  -> ascii character HH in hexadecimal
-*/
-static void resolve_backslashes(char *z){
-  int i, j;
-  char c;
-  while( *z && *z!='\\' ) z++;
-  for(i=j=0; (c = z[i])!=0; i++, j++){
-    if( c=='\\' && z[i+1]!=0 ){
-      c = z[++i];
-      if( c=='a' ){
-        c = '\a';
-      }else if( c=='b' ){
-        c = '\b';
-      }else if( c=='t' ){
-        c = '\t';
-      }else if( c=='n' ){
-        c = '\n';
-      }else if( c=='v' ){
-        c = '\v';
-      }else if( c=='f' ){
-        c = '\f';
-      }else if( c=='r' ){
-        c = '\r';
-      }else if( c=='"' ){
-        c = '"';
-      }else if( c=='\'' ){
-        c = '\'';
-      }else if( c=='\\' ){
-        c = '\\';
-      }else if( c=='x' ){
-        int nhd = 0, hdv;
-        u8 hv = 0;
-        while( nhd<2 && (c=z[i+1+nhd])!=0 && (hdv=hexDigitValue(c))>=0 ){
-          hv = (u8)((hv<<4)|hdv);
-          ++nhd;
-        }
-        i += nhd;
-        c = (u8)hv;
-      }else if( c>='0' && c<='7' ){
-        c -= '0';
-        if( z[i+1]>='0' && z[i+1]<='7' ){
-          i++;
-          c = (c<<3) + z[i] - '0';
-          if( z[i+1]>='0' && z[i+1]<='7' ){
-            i++;
-            c = (c<<3) + z[i] - '0';
-          }
-        }
-      }
-    }
-    z[j] = c;
-  }
-  if( j=0; i++){}
-  }else{
-    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
-  }
-  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
-  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
-    return 1;
-  }
-  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
-    return 0;
-  }
-  sqlite3_fprintf(stderr,
-       "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg);
-  return 0;
-}
-
-/*
-** Set or clear a shell flag according to a boolean value.
-*/
-static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
-  if( booleanValue(zArg) ){
-    ShellSetFlag(p, mFlag);
-  }else{
-    ShellClearFlag(p, mFlag);
-  }
-}
-
-/*
-** Close an output file, assuming it is not stderr or stdout
-*/
-static void output_file_close(FILE *f){
-  if( f && f!=stdout && f!=stderr ) fclose(f);
-}
-
-/*
-** Try to open an output file.   The names "stdout" and "stderr" are
-** recognized and do the right thing.  NULL is returned if the output
-** filename is "off".
-*/
-static FILE *output_file_open(const char *zFile){
-  FILE *f;
-  if( cli_strcmp(zFile,"stdout")==0 ){
-    f = stdout;
-  }else if( cli_strcmp(zFile, "stderr")==0 ){
-    f = stderr;
-  }else if( cli_strcmp(zFile, "off")==0 ){
-    f = 0;
-  }else{
-    f = sqlite3_fopen(zFile, "w");
-    if( f==0 ){
-      sqlite3_fprintf(stderr,"Error: cannot open \"%s\"\n", zFile);
-    }
-  }
-  return f;
-}
-
-#ifndef SQLITE_OMIT_TRACE
-/*
-** A routine for handling output from sqlite3_trace().
-*/
-static int sql_trace_callback(
-  unsigned mType,         /* The trace type */
-  void *pArg,             /* The ShellState pointer */
-  void *pP,               /* Usually a pointer to sqlite_stmt */
-  void *pX                /* Auxiliary output */
-){
-  ShellState *p = (ShellState*)pArg;
-  sqlite3_stmt *pStmt;
-  const char *zSql;
-  i64 nSql;
-  if( p->traceOut==0 ) return 0;
-  if( mType==SQLITE_TRACE_CLOSE ){
-    sputz(p->traceOut, "-- closing database connection\n");
-    return 0;
-  }
-  if( mType!=SQLITE_TRACE_ROW && pX!=0 && ((const char*)pX)[0]=='-' ){
-    zSql = (const char*)pX;
-  }else{
-    pStmt = (sqlite3_stmt*)pP;
-    switch( p->eTraceType ){
-      case SHELL_TRACE_EXPANDED: {
-        zSql = sqlite3_expanded_sql(pStmt);
-        break;
-      }
-#ifdef SQLITE_ENABLE_NORMALIZE
-      case SHELL_TRACE_NORMALIZED: {
-        zSql = sqlite3_normalized_sql(pStmt);
-        break;
-      }
-#endif
-      default: {
-        zSql = sqlite3_sql(pStmt);
-        break;
-      }
-    }
-  }
-  if( zSql==0 ) return 0;
-  nSql = strlen(zSql);
-  if( nSql>1000000000 ) nSql = 1000000000;
-  while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
-  switch( mType ){
-    case SQLITE_TRACE_ROW:
-    case SQLITE_TRACE_STMT: {
-      sqlite3_fprintf(p->traceOut, "%.*s;\n", (int)nSql, zSql);
-      break;
-    }
-    case SQLITE_TRACE_PROFILE: {
-      sqlite3_int64 nNanosec = pX ? *(sqlite3_int64*)pX : 0;
-      sqlite3_fprintf(p->traceOut,
-                      "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec);
-      break;
-    }
-  }
-  return 0;
-}
-#endif
-
-/*
-** A no-op routine that runs with the ".breakpoint" doc-command.  This is
-** a useful spot to set a debugger breakpoint.
-**
-** This routine does not do anything practical.  The code are there simply
-** to prevent the compiler from optimizing this routine out.
-*/
-static void test_breakpoint(void){
-  static unsigned int nCall = 0;
-  if( (nCall++)==0xffffffff ) printf("Many .breakpoints have run\n");
-}
-
-/*
-** An object used to read a CSV and other files for import.
-*/
-typedef struct ImportCtx ImportCtx;
-struct ImportCtx {
-  const char *zFile;  /* Name of the input file */
-  FILE *in;           /* Read the CSV text from this input stream */
-  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
-  char *z;            /* Accumulated text for a field */
-  int n;              /* Number of bytes in z */
-  int nAlloc;         /* Space allocated for z[] */
-  int nLine;          /* Current line number */
-  int nRow;           /* Number of rows imported */
-  int nErr;           /* Number of errors encountered */
-  int bNotFirst;      /* True if one or more bytes already read */
-  int cTerm;          /* Character that terminated the most recent field */
-  int cColSep;        /* The column separator character.  (Usually ",") */
-  int cRowSep;        /* The row separator character.  (Usually "\n") */
-};
-
-/* Clean up resourced used by an ImportCtx */
-static void import_cleanup(ImportCtx *p){
-  if( p->in!=0 && p->xCloser!=0 ){
-    p->xCloser(p->in);
-    p->in = 0;
-  }
-  sqlite3_free(p->z);
-  p->z = 0;
-}
-
-/* Append a single byte to z[] */
-static void import_append_char(ImportCtx *p, int c){
-  if( p->n+1>=p->nAlloc ){
-    p->nAlloc += p->nAlloc + 100;
-    p->z = sqlite3_realloc64(p->z, p->nAlloc);
-    shell_check_oom(p->z);
-  }
-  p->z[p->n++] = (char)c;
-}
-
-/* Read a single field of CSV text.  Compatible with rfc4180 and extended
-** with the option of having a separator other than ",".
-**
-**   +  Input comes from p->in.
-**   +  Store results in p->z of length p->n.  Space to hold p->z comes
-**      from sqlite3_malloc64().
-**   +  Use p->cSep as the column separator.  The default is ",".
-**   +  Use p->rSep as the row separator.  The default is "\n".
-**   +  Keep track of the line number in p->nLine.
-**   +  Store the character that terminates the field in p->cTerm.  Store
-**      EOF on end-of-file.
-**   +  Report syntax errors on stderr
-*/
-static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
-  int c;
-  int cSep = (u8)p->cColSep;
-  int rSep = (u8)p->cRowSep;
-  p->n = 0;
-  c = fgetc(p->in);
-  if( c==EOF || seenInterrupt ){
-    p->cTerm = EOF;
-    return 0;
-  }
-  if( c=='"' ){
-    int pc, ppc;
-    int startLine = p->nLine;
-    int cQuote = c;
-    pc = ppc = 0;
-    while( 1 ){
-      c = fgetc(p->in);
-      if( c==rSep ) p->nLine++;
-      if( c==cQuote ){
-        if( pc==cQuote ){
-          pc = 0;
-          continue;
-        }
-      }
-      if( (c==cSep && pc==cQuote)
-       || (c==rSep && pc==cQuote)
-       || (c==rSep && pc=='\r' && ppc==cQuote)
-       || (c==EOF && pc==cQuote)
-      ){
-        do{ p->n--; }while( p->z[p->n]!=cQuote );
-        p->cTerm = c;
-        break;
-      }
-      if( pc==cQuote && c!='\r' ){
-        sqlite3_fprintf(stderr,"%s:%d: unescaped %c character\n", 
-                        p->zFile, p->nLine, cQuote);
-      }
-      if( c==EOF ){
-        sqlite3_fprintf(stderr,"%s:%d: unterminated %c-quoted field\n",
-              p->zFile, startLine, cQuote);
-        p->cTerm = c;
-        break;
-      }
-      import_append_char(p, c);
-      ppc = pc;
-      pc = c;
-    }
-  }else{
-    /* If this is the first field being parsed and it begins with the
-    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
-    if( (c&0xff)==0xef && p->bNotFirst==0 ){
-      import_append_char(p, c);
-      c = fgetc(p->in);
-      if( (c&0xff)==0xbb ){
-        import_append_char(p, c);
-        c = fgetc(p->in);
-        if( (c&0xff)==0xbf ){
-          p->bNotFirst = 1;
-          p->n = 0;
-          return csv_read_one_field(p);
-        }
-      }
-    }
-    while( c!=EOF && c!=cSep && c!=rSep ){
-      import_append_char(p, c);
-      c = fgetc(p->in);
-    }
-    if( c==rSep ){
-      p->nLine++;
-      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
-    }
-    p->cTerm = c;
-  }
-  if( p->z ) p->z[p->n] = 0;
-  p->bNotFirst = 1;
-  return p->z;
-}
-
-/* Read a single field of ASCII delimited text.
-**
-**   +  Input comes from p->in.
-**   +  Store results in p->z of length p->n.  Space to hold p->z comes
-**      from sqlite3_malloc64().
-**   +  Use p->cSep as the column separator.  The default is "\x1F".
-**   +  Use p->rSep as the row separator.  The default is "\x1E".
-**   +  Keep track of the row number in p->nLine.
-**   +  Store the character that terminates the field in p->cTerm.  Store
-**      EOF on end-of-file.
-**   +  Report syntax errors on stderr
-*/
-static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
-  int c;
-  int cSep = (u8)p->cColSep;
-  int rSep = (u8)p->cRowSep;
-  p->n = 0;
-  c = fgetc(p->in);
-  if( c==EOF || seenInterrupt ){
-    p->cTerm = EOF;
-    return 0;
-  }
-  while( c!=EOF && c!=cSep && c!=rSep ){
-    import_append_char(p, c);
-    c = fgetc(p->in);
-  }
-  if( c==rSep ){
-    p->nLine++;
-  }
-  p->cTerm = c;
-  if( p->z ) p->z[p->n] = 0;
-  return p->z;
-}
-
-/*
-** Try to transfer data for table zTable.  If an error is seen while
-** moving forward, try to go backwards.  The backwards movement won't
-** work for WITHOUT ROWID tables.
-*/
-static void tryToCloneData(
-  ShellState *p,
-  sqlite3 *newDb,
-  const char *zTable
-){
-  sqlite3_stmt *pQuery = 0;
-  sqlite3_stmt *pInsert = 0;
-  char *zQuery = 0;
-  char *zInsert = 0;
-  int rc;
-  int i, j, n;
-  int nTable = strlen30(zTable);
-  int k = 0;
-  int cnt = 0;
-  const int spinRate = 10000;
-
-  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
-  shell_check_oom(zQuery);
-  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
-  if( rc ){
-    sqlite3_fprintf(stderr,"Error %d: %s on [%s]\n",
-          sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
-    goto end_data_xfer;
-  }
-  n = sqlite3_column_count(pQuery);
-  zInsert = sqlite3_malloc64(200 + nTable + n*3);
-  shell_check_oom(zInsert);
-  sqlite3_snprintf(200+nTable,zInsert,
-                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
-  i = strlen30(zInsert);
-  for(j=1; jdb, zQuery, -1, &pQuery, 0);
-    if( rc ){
-      sqlite3_fprintf(stderr,"Warning: cannot step \"%s\" backwards", zTable);
-      break;
-    }
-  } /* End for(k=0...) */
-
-end_data_xfer:
-  sqlite3_finalize(pQuery);
-  sqlite3_finalize(pInsert);
-  sqlite3_free(zQuery);
-  sqlite3_free(zInsert);
-}
-
-
-/*
-** Try to transfer all rows of the schema that match zWhere.  For
-** each row, invoke xForEach() on the object defined by that row.
-** If an error is encountered while moving forward through the
-** sqlite_schema table, try again moving backwards.
-*/
-static void tryToCloneSchema(
-  ShellState *p,
-  sqlite3 *newDb,
-  const char *zWhere,
-  void (*xForEach)(ShellState*,sqlite3*,const char*)
-){
-  sqlite3_stmt *pQuery = 0;
-  char *zQuery = 0;
-  int rc;
-  const unsigned char *zName;
-  const unsigned char *zSql;
-  char *zErrMsg = 0;
-
-  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
-                           " WHERE %s ORDER BY rowid ASC", zWhere);
-  shell_check_oom(zQuery);
-  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
-  if( rc ){
-    sqlite3_fprintf(stderr,
-          "Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db),
-          sqlite3_errmsg(p->db), zQuery);
-    goto end_schema_xfer;
-  }
-  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
-    zName = sqlite3_column_text(pQuery, 0);
-    zSql = sqlite3_column_text(pQuery, 1);
-    if( zName==0 || zSql==0 ) continue;
-    if( sqlite3_stricmp((char*)zName, "sqlite_sequence")!=0 ){
-      sqlite3_fprintf(stdout, "%s... ", zName); fflush(stdout);
-      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
-      if( zErrMsg ){
-        sqlite3_fprintf(stderr,"Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
-        sqlite3_free(zErrMsg);
-        zErrMsg = 0;
-      }
-    }
-    if( xForEach ){
-      xForEach(p, newDb, (const char*)zName);
-    }
-    sputz(stdout, "done\n");
-  }
-  if( rc!=SQLITE_DONE ){
-    sqlite3_finalize(pQuery);
-    sqlite3_free(zQuery);
-    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
-                             " WHERE %s ORDER BY rowid DESC", zWhere);
-    shell_check_oom(zQuery);
-    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
-    if( rc ){
-      sqlite3_fprintf(stderr,"Error: (%d) %s on [%s]\n",
-            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery);
-      goto end_schema_xfer;
-    }
-    while( sqlite3_step(pQuery)==SQLITE_ROW ){
-      zName = sqlite3_column_text(pQuery, 0);
-      zSql = sqlite3_column_text(pQuery, 1);
-      if( zName==0 || zSql==0 ) continue;
-      if( sqlite3_stricmp((char*)zName, "sqlite_sequence")==0 ) continue;
-      sqlite3_fprintf(stdout, "%s... ", zName); fflush(stdout);
-      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
-      if( zErrMsg ){
-        sqlite3_fprintf(stderr,"Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
-        sqlite3_free(zErrMsg);
-        zErrMsg = 0;
-      }
-      if( xForEach ){
-        xForEach(p, newDb, (const char*)zName);
-      }
-      sputz(stdout, "done\n");
-    }
-  }
-end_schema_xfer:
-  sqlite3_finalize(pQuery);
-  sqlite3_free(zQuery);
-}
-
-/*
-** Open a new database file named "zNewDb".  Try to recover as much information
-** as possible out of the main database (which might be corrupt) and write it
-** into zNewDb.
-*/
-static void tryToClone(ShellState *p, const char *zNewDb){
-  int rc;
-  sqlite3 *newDb = 0;
-  if( access(zNewDb,0)==0 ){
-    sqlite3_fprintf(stderr,"File \"%s\" already exists.\n", zNewDb);
-    return;
-  }
-  rc = sqlite3_open(zNewDb, &newDb);
-  if( rc ){
-    sqlite3_fprintf(stderr,
-        "Cannot create output database: %s\n", sqlite3_errmsg(newDb));
-  }else{
-    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
-    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
-    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
-    tryToCloneSchema(p, newDb, "type!='table'", 0);
-    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
-    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
-  }
-  close_db(newDb);
-}
-
-#ifndef SQLITE_SHELL_FIDDLE
-/*
-** Change the output stream (file or pipe or console) to something else.
-*/
-static void output_redir(ShellState *p, FILE *pfNew){
-  if( p->out != stdout ){
-    sqlite3_fputs("Output already redirected.\n", stderr);
-  }else{
-    p->out = pfNew;
-    setCrlfMode(p);
-    if( p->mode==MODE_Www ){
-      sqlite3_fputs(
-        "\n"
-        "
\n",
-        p->out
-      );
-    }
-  }
-}
-
-/*
-** Change the output file back to stdout.
-**
-** If the p->doXdgOpen flag is set, that means the output was being
-** redirected to a temporary file named by p->zTempFile.  In that case,
-** launch start/open/xdg-open on that temporary file.
-*/
-static void output_reset(ShellState *p){
-  if( p->outfile[0]=='|' ){
-#ifndef SQLITE_OMIT_POPEN
-    pclose(p->out);
-#endif
-  }else{
-    if( p->mode==MODE_Www ){
-      sqlite3_fputs("
\n", p->out); - } - output_file_close(p->out); -#ifndef SQLITE_NOHAVE_SYSTEM - if( p->doXdgOpen ){ - const char *zXdgOpenCmd = -#if defined(_WIN32) - "start"; -#elif defined(__APPLE__) - "open"; -#else - "xdg-open"; -#endif - char *zCmd; - zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); - if( system(zCmd) ){ - sqlite3_fprintf(stderr,"Failed: [%s]\n", zCmd); - }else{ - /* Give the start/open/xdg-open command some time to get - ** going before we continue, and potential delete the - ** p->zTempFile data file out from under it */ - sqlite3_sleep(2000); - } - sqlite3_free(zCmd); - outputModePop(p); - p->doXdgOpen = 0; - } -#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ - } - p->outfile[0] = 0; - p->out = stdout; - setCrlfMode(p); -} -#else -# define output_redir(SS,pfO) -# define output_reset(SS) -#endif - -/* -** Run an SQL command and return the single integer result. -*/ -static int db_int(sqlite3 *db, const char *zSql){ - sqlite3_stmt *pStmt; - int res = 0; - sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ - res = sqlite3_column_int(pStmt,0); - } - sqlite3_finalize(pStmt); - return res; -} - -#if SQLITE_SHELL_HAVE_RECOVER -/* -** Convert a 2-byte or 4-byte big-endian integer into a native integer -*/ -static unsigned int get2byteInt(unsigned char *a){ - return (a[0]<<8) + a[1]; -} -static unsigned int get4byteInt(unsigned char *a){ - return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; -} - -/* -** Implementation of the ".dbinfo" command. -** -** Return 1 on error, 2 to exit, and 0 otherwise. -*/ -static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ - static const struct { const char *zName; int ofst; } aField[] = { - { "file change counter:", 24 }, - { "database page count:", 28 }, - { "freelist page count:", 36 }, - { "schema cookie:", 40 }, - { "schema format:", 44 }, - { "default cache size:", 48 }, - { "autovacuum top root:", 52 }, - { "incremental vacuum:", 64 }, - { "text encoding:", 56 }, - { "user version:", 60 }, - { "application id:", 68 }, - { "software version:", 96 }, - }; - static const struct { const char *zName; const char *zSql; } aQuery[] = { - { "number of tables:", - "SELECT count(*) FROM %s WHERE type='table'" }, - { "number of indexes:", - "SELECT count(*) FROM %s WHERE type='index'" }, - { "number of triggers:", - "SELECT count(*) FROM %s WHERE type='trigger'" }, - { "number of views:", - "SELECT count(*) FROM %s WHERE type='view'" }, - { "schema size:", - "SELECT total(length(sql)) FROM %s" }, - }; - int i, rc; - unsigned iDataVersion; - char *zSchemaTab; - char *zDb = nArg>=2 ? azArg[1] : "main"; - sqlite3_stmt *pStmt = 0; - unsigned char aHdr[100]; - open_db(p, 0); - if( p->db==0 ) return 1; - rc = sqlite3_prepare_v2(p->db, - "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1", - -1, &pStmt, 0); - if( rc ){ - sqlite3_fprintf(stderr,"error: %s\n", sqlite3_errmsg(p->db)); - sqlite3_finalize(pStmt); - return 1; - } - sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); - if( sqlite3_step(pStmt)==SQLITE_ROW - && sqlite3_column_bytes(pStmt,0)>100 - ){ - const u8 *pb = sqlite3_column_blob(pStmt,0); - shell_check_oom(pb); - memcpy(aHdr, pb, 100); - sqlite3_finalize(pStmt); - }else{ - sqlite3_fputs("unable to read database header\n", stderr); - sqlite3_finalize(pStmt); - return 1; - } - i = get2byteInt(aHdr+16); - if( i==1 ) i = 65536; - sqlite3_fprintf(p->out, "%-20s %d\n", "database page size:", i); - sqlite3_fprintf(p->out, "%-20s %d\n", "write format:", aHdr[18]); - sqlite3_fprintf(p->out, "%-20s %d\n", "read format:", aHdr[19]); - sqlite3_fprintf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); - for(i=0; iout, "%-20s %u", aField[i].zName, val); - switch( ofst ){ - case 56: { - if( val==1 ) sqlite3_fputs(" (utf8)", p->out); - if( val==2 ) sqlite3_fputs(" (utf16le)", p->out); - if( val==3 ) sqlite3_fputs(" (utf16be)", p->out); - } - } - sqlite3_fputs("\n", p->out); - } - if( zDb==0 ){ - zSchemaTab = sqlite3_mprintf("main.sqlite_schema"); - }else if( cli_strcmp(zDb,"temp")==0 ){ - zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema"); - }else{ - zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb); - } - for(i=0; idb, zSql); - sqlite3_free(zSql); - sqlite3_fprintf(p->out, "%-20s %d\n", aQuery[i].zName, val); - } - sqlite3_free(zSchemaTab); - sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); - sqlite3_fprintf(p->out, "%-20s %u\n", "data version", iDataVersion); - return 0; -} -#endif /* SQLITE_SHELL_HAVE_RECOVER */ - -/* -** Print the given string as an error message. -*/ -static void shellEmitError(const char *zErr){ - sqlite3_fprintf(stderr,"Error: %s\n", zErr); -} -/* -** Print the current sqlite3_errmsg() value to stderr and return 1. -*/ -static int shellDatabaseError(sqlite3 *db){ - shellEmitError(sqlite3_errmsg(db)); - return 1; -} - -/* -** Compare the pattern in zGlob[] against the text in z[]. Return TRUE -** if they match and FALSE (0) if they do not match. -** -** Globbing rules: -** -** '*' Matches any sequence of zero or more characters. -** -** '?' Matches exactly one character. -** -** [...] Matches one character from the enclosed list of -** characters. -** -** [^...] Matches one character not in the enclosed list. -** -** '#' Matches any sequence of one or more digits with an -** optional + or - sign in front -** -** ' ' Any span of whitespace matches any other span of -** whitespace. -** -** Extra whitespace at the end of z[] is ignored. -*/ -static int testcase_glob(const char *zGlob, const char *z){ - int c, c2; - int invert; - int seen; - - while( (c = (*(zGlob++)))!=0 ){ - if( IsSpace(c) ){ - if( !IsSpace(*z) ) return 0; - while( IsSpace(*zGlob) ) zGlob++; - while( IsSpace(*z) ) z++; - }else if( c=='*' ){ - while( (c=(*(zGlob++))) == '*' || c=='?' ){ - if( c=='?' && (*(z++))==0 ) return 0; - } - if( c==0 ){ - return 1; - }else if( c=='[' ){ - while( *z && testcase_glob(zGlob-1,z)==0 ){ - z++; - } - return (*z)!=0; - } - while( (c2 = (*(z++)))!=0 ){ - while( c2!=c ){ - c2 = *(z++); - if( c2==0 ) return 0; - } - if( testcase_glob(zGlob,z) ) return 1; - } - return 0; - }else if( c=='?' ){ - if( (*(z++))==0 ) return 0; - }else if( c=='[' ){ - int prior_c = 0; - seen = 0; - invert = 0; - c = *(z++); - if( c==0 ) return 0; - c2 = *(zGlob++); - if( c2=='^' ){ - invert = 1; - c2 = *(zGlob++); - } - if( c2==']' ){ - if( c==']' ) seen = 1; - c2 = *(zGlob++); - } - while( c2 && c2!=']' ){ - if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ - c2 = *(zGlob++); - if( c>=prior_c && c<=c2 ) seen = 1; - prior_c = 0; - }else{ - if( c==c2 ){ - seen = 1; - } - prior_c = c2; - } - c2 = *(zGlob++); - } - if( c2==0 || (seen ^ invert)==0 ) return 0; - }else if( c=='#' ){ - if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; - if( !IsDigit(z[0]) ) return 0; - z++; - while( IsDigit(z[0]) ){ z++; } - }else{ - if( c!=(*(z++)) ) return 0; - } - } - while( IsSpace(*z) ){ z++; } - return *z==0; -} - - -/* -** Compare the string as a command-line option with either one or two -** initial "-" characters. -*/ -static int optionMatch(const char *zStr, const char *zOpt){ - if( zStr[0]!='-' ) return 0; - zStr++; - if( zStr[0]=='-' ) zStr++; - return cli_strcmp(zStr, zOpt)==0; -} - -/* -** Delete a file. -*/ -int shellDeleteFile(const char *zFilename){ - int rc; -#ifdef _WIN32 - wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename); - rc = _wunlink(z); - sqlite3_free(z); -#else - rc = unlink(zFilename); -#endif - return rc; -} - -/* -** Try to delete the temporary file (if there is one) and free the -** memory used to hold the name of the temp file. -*/ -static void clearTempFile(ShellState *p){ - if( p->zTempFile==0 ) return; - if( p->doXdgOpen ) return; - if( shellDeleteFile(p->zTempFile) ) return; - sqlite3_free(p->zTempFile); - p->zTempFile = 0; -} - -/* -** Create a new temp file name with the given suffix. -*/ -static void newTempFile(ShellState *p, const char *zSuffix){ - clearTempFile(p); - sqlite3_free(p->zTempFile); - p->zTempFile = 0; - if( p->db ){ - sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); - } - if( p->zTempFile==0 ){ - /* If p->db is an in-memory database then the TEMPFILENAME file-control - ** will not work and we will need to fallback to guessing */ - char *zTemp; - sqlite3_uint64 r; - sqlite3_randomness(sizeof(r), &r); - zTemp = getenv("TEMP"); - if( zTemp==0 ) zTemp = getenv("TMP"); - if( zTemp==0 ){ -#ifdef _WIN32 - zTemp = "\\tmp"; -#else - zTemp = "/tmp"; -#endif - } - p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix); - }else{ - p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); - } - shell_check_oom(p->zTempFile); -} - - -/* -** The implementation of SQL scalar function fkey_collate_clause(), used -** by the ".lint fkey-indexes" command. This scalar function is always -** called with four arguments - the parent table name, the parent column name, -** the child table name and the child column name. -** -** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col') -** -** If either of the named tables or columns do not exist, this function -** returns an empty string. An empty string is also returned if both tables -** and columns exist but have the same default collation sequence. Or, -** if both exist but the default collation sequences are different, this -** function returns the string " COLLATE ", where -** is the default collation sequence of the parent column. -*/ -static void shellFkeyCollateClause( - sqlite3_context *pCtx, - int nVal, - sqlite3_value **apVal -){ - sqlite3 *db = sqlite3_context_db_handle(pCtx); - const char *zParent; - const char *zParentCol; - const char *zParentSeq; - const char *zChild; - const char *zChildCol; - const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ - int rc; - - assert( nVal==4 ); - zParent = (const char*)sqlite3_value_text(apVal[0]); - zParentCol = (const char*)sqlite3_value_text(apVal[1]); - zChild = (const char*)sqlite3_value_text(apVal[2]); - zChildCol = (const char*)sqlite3_value_text(apVal[3]); - - sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); - rc = sqlite3_table_column_metadata( - db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0 - ); - if( rc==SQLITE_OK ){ - rc = sqlite3_table_column_metadata( - db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0 - ); - } - - if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){ - char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq); - sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); - sqlite3_free(z); - } -} - - -/* -** The implementation of dot-command ".lint fkey-indexes". -*/ -static int lintFkeyIndexes( - ShellState *pState, /* Current shell tool state */ - char **azArg, /* Array of arguments passed to dot command */ - int nArg /* Number of entries in azArg[] */ -){ - sqlite3 *db = pState->db; /* Database handle to query "main" db of */ - int bVerbose = 0; /* If -verbose is present */ - int bGroupByParent = 0; /* If -groupbyparent is present */ - int i; /* To iterate through azArg[] */ - const char *zIndent = ""; /* How much to indent CREATE INDEX by */ - int rc; /* Return code */ - sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */ - FILE *out = pState->out; /* Send output here */ - - /* - ** This SELECT statement returns one row for each foreign key constraint - ** in the schema of the main database. The column values are: - ** - ** 0. The text of an SQL statement similar to: - ** - ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?" - ** - ** This SELECT is similar to the one that the foreign keys implementation - ** needs to run internally on child tables. If there is an index that can - ** be used to optimize this query, then it can also be used by the FK - ** implementation to optimize DELETE or UPDATE statements on the parent - ** table. - ** - ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by - ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema - ** contains an index that can be used to optimize the query. - ** - ** 2. Human readable text that describes the child table and columns. e.g. - ** - ** "child_table(child_key1, child_key2)" - ** - ** 3. Human readable text that describes the parent table and columns. e.g. - ** - ** "parent_table(parent_key1, parent_key2)" - ** - ** 4. A full CREATE INDEX statement for an index that could be used to - ** optimize DELETE or UPDATE statements on the parent table. e.g. - ** - ** "CREATE INDEX child_table_child_key ON child_table(child_key)" - ** - ** 5. The name of the parent table. - ** - ** These six values are used by the C logic below to generate the report. - */ - const char *zSql = - "SELECT " - " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '" - " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' " - " || fkey_collate_clause(" - " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')" - ", " - " 'SEARCH ' || s.name || ' USING COVERING INDEX*('" - " || group_concat('*=?', ' AND ') || ')'" - ", " - " s.name || '(' || group_concat(f.[from], ', ') || ')'" - ", " - " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'" - ", " - " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))" - " || ' ON ' || quote(s.name) || '('" - " || group_concat(quote(f.[from]) ||" - " fkey_collate_clause(" - " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')" - " || ');'" - ", " - " f.[table] " - "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f " - "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " - "GROUP BY s.name, f.id " - "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)" - ; - const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)"; - - for(i=2; i1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ - bVerbose = 1; - } - else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ - bGroupByParent = 1; - zIndent = " "; - } - else{ - sqlite3_fprintf(stderr, - "Usage: %s %s ?-verbose? ?-groupbyparent?\n", azArg[0], azArg[1]); - return SQLITE_ERROR; - } - } - - /* Register the fkey_collate_clause() SQL function */ - rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8, - 0, shellFkeyCollateClause, 0, 0 - ); - - - if( rc==SQLITE_OK ){ - rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); - } - if( rc==SQLITE_OK ){ - sqlite3_bind_int(pSql, 1, bGroupByParent); - } - - if( rc==SQLITE_OK ){ - int rc2; - char *zPrev = 0; - while( SQLITE_ROW==sqlite3_step(pSql) ){ - int res = -1; - sqlite3_stmt *pExplain = 0; - const char *zEQP = (const char*)sqlite3_column_text(pSql, 0); - const char *zGlob = (const char*)sqlite3_column_text(pSql, 1); - const char *zFrom = (const char*)sqlite3_column_text(pSql, 2); - const char *zTarget = (const char*)sqlite3_column_text(pSql, 3); - const char *zCI = (const char*)sqlite3_column_text(pSql, 4); - const char *zParent = (const char*)sqlite3_column_text(pSql, 5); - - if( zEQP==0 ) continue; - if( zGlob==0 ) continue; - rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); - if( rc!=SQLITE_OK ) break; - if( SQLITE_ROW==sqlite3_step(pExplain) ){ - const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3); - res = zPlan!=0 && ( 0==sqlite3_strglob(zGlob, zPlan) - || 0==sqlite3_strglob(zGlobIPK, zPlan)); - } - rc = sqlite3_finalize(pExplain); - if( rc!=SQLITE_OK ) break; - - if( res<0 ){ - sqlite3_fputs("Error: internal error", stderr); - break; - }else{ - if( bGroupByParent - && (bVerbose || res==0) - && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) - ){ - sqlite3_fprintf(out, "-- Parent table %s\n", zParent); - sqlite3_free(zPrev); - zPrev = sqlite3_mprintf("%s", zParent); - } - - if( res==0 ){ - sqlite3_fprintf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); - }else if( bVerbose ){ - sqlite3_fprintf(out, - "%s/* no extra indexes required for %s -> %s */\n", - zIndent, zFrom, zTarget - ); - } - } - } - sqlite3_free(zPrev); - - if( rc!=SQLITE_OK ){ - sqlite3_fprintf(stderr,"%s\n", sqlite3_errmsg(db)); - } - - rc2 = sqlite3_finalize(pSql); - if( rc==SQLITE_OK && rc2!=SQLITE_OK ){ - rc = rc2; - sqlite3_fprintf(stderr,"%s\n", sqlite3_errmsg(db)); - } - }else{ - sqlite3_fprintf(stderr,"%s\n", sqlite3_errmsg(db)); - } - - return rc; -} - -/* -** Implementation of ".lint" dot command. -*/ -static int lintDotCommand( - ShellState *pState, /* Current shell tool state */ - char **azArg, /* Array of arguments passed to dot command */ - int nArg /* Number of entries in azArg[] */ -){ - int n; - n = (nArg>=2 ? strlen30(azArg[1]) : 0); - if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; - return lintFkeyIndexes(pState, azArg, nArg); - - usage: - sqlite3_fprintf(stderr,"Usage %s sub-command ?switches...?\n", azArg[0]); - sqlite3_fprintf(stderr, "Where sub-commands are:\n"); - sqlite3_fprintf(stderr, " fkey-indexes\n"); - return SQLITE_ERROR; -} - -static void shellPrepare( - sqlite3 *db, - int *pRc, - const char *zSql, - sqlite3_stmt **ppStmt -){ - *ppStmt = 0; - if( *pRc==SQLITE_OK ){ - int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); - if( rc!=SQLITE_OK ){ - sqlite3_fprintf(stderr, - "sql error: %s (%d)\n", sqlite3_errmsg(db), sqlite3_errcode(db)); - *pRc = rc; - } - } -} - -/* -** Create a prepared statement using printf-style arguments for the SQL. -*/ -static void shellPreparePrintf( - sqlite3 *db, - int *pRc, - sqlite3_stmt **ppStmt, - const char *zFmt, - ... -){ - *ppStmt = 0; - if( *pRc==SQLITE_OK ){ - va_list ap; - char *z; - va_start(ap, zFmt); - z = sqlite3_vmprintf(zFmt, ap); - va_end(ap); - if( z==0 ){ - *pRc = SQLITE_NOMEM; - }else{ - shellPrepare(db, pRc, z, ppStmt); - sqlite3_free(z); - } - } -} - -/* -** Finalize the prepared statement created using shellPreparePrintf(). -*/ -static void shellFinalize( - int *pRc, - sqlite3_stmt *pStmt -){ - if( pStmt ){ - sqlite3 *db = sqlite3_db_handle(pStmt); - int rc = sqlite3_finalize(pStmt); - if( *pRc==SQLITE_OK ){ - if( rc!=SQLITE_OK ){ - sqlite3_fprintf(stderr,"SQL error: %s\n", sqlite3_errmsg(db)); - } - *pRc = rc; - } - } -} - -#if !defined SQLITE_OMIT_VIRTUALTABLE -/* Reset the prepared statement created using shellPreparePrintf(). -** -** This routine is could be marked "static". But it is not always used, -** depending on compile-time options. By omitting the "static", we avoid -** nuisance compiler warnings about "defined but not used". -*/ -void shellReset( - int *pRc, - sqlite3_stmt *pStmt -){ - int rc = sqlite3_reset(pStmt); - if( *pRc==SQLITE_OK ){ - if( rc!=SQLITE_OK ){ - sqlite3 *db = sqlite3_db_handle(pStmt); - sqlite3_fprintf(stderr,"SQL error: %s\n", sqlite3_errmsg(db)); - } - *pRc = rc; - } -} -#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */ - -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) -/****************************************************************************** -** The ".archive" or ".ar" command. -*/ -/* -** Structure representing a single ".ar" command. -*/ -typedef struct ArCommand ArCommand; -struct ArCommand { - u8 eCmd; /* An AR_CMD_* value */ - u8 bVerbose; /* True if --verbose */ - u8 bZip; /* True if the archive is a ZIP */ - u8 bDryRun; /* True if --dry-run */ - u8 bAppend; /* True if --append */ - u8 bGlob; /* True if --glob */ - u8 fromCmdLine; /* Run from -A instead of .archive */ - int nArg; /* Number of command arguments */ - char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */ - const char *zFile; /* --file argument, or NULL */ - const char *zDir; /* --directory argument, or NULL */ - char **azArg; /* Array of command arguments */ - ShellState *p; /* Shell state */ - FILE *out; /* Output to this stream */ - sqlite3 *db; /* Database containing the archive */ -}; - -/* -** Print a usage message for the .ar command to stderr and return SQLITE_ERROR. -*/ -static int arUsage(FILE *f){ - showHelp(f,"archive"); - return SQLITE_ERROR; -} - -/* -** Print an error message for the .ar command to stderr and return -** SQLITE_ERROR. -*/ -static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){ - va_list ap; - char *z; - va_start(ap, zFmt); - z = sqlite3_vmprintf(zFmt, ap); - va_end(ap); - shellEmitError(z); - if( pAr->fromCmdLine ){ - sqlite3_fputs("Use \"-A\" for more help\n", stderr); - }else{ - sqlite3_fputs("Use \".archive --help\" for more help\n", stderr); - } - sqlite3_free(z); - return SQLITE_ERROR; -} - -/* -** Values for ArCommand.eCmd. -*/ -#define AR_CMD_CREATE 1 -#define AR_CMD_UPDATE 2 -#define AR_CMD_INSERT 3 -#define AR_CMD_EXTRACT 4 -#define AR_CMD_LIST 5 -#define AR_CMD_HELP 6 -#define AR_CMD_REMOVE 7 - -/* -** Other (non-command) switches. -*/ -#define AR_SWITCH_VERBOSE 8 -#define AR_SWITCH_FILE 9 -#define AR_SWITCH_DIRECTORY 10 -#define AR_SWITCH_APPEND 11 -#define AR_SWITCH_DRYRUN 12 -#define AR_SWITCH_GLOB 13 - -static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){ - switch( eSwitch ){ - case AR_CMD_CREATE: - case AR_CMD_EXTRACT: - case AR_CMD_LIST: - case AR_CMD_REMOVE: - case AR_CMD_UPDATE: - case AR_CMD_INSERT: - case AR_CMD_HELP: - if( pAr->eCmd ){ - return arErrorMsg(pAr, "multiple command options"); - } - pAr->eCmd = eSwitch; - break; - - case AR_SWITCH_DRYRUN: - pAr->bDryRun = 1; - break; - case AR_SWITCH_GLOB: - pAr->bGlob = 1; - break; - case AR_SWITCH_VERBOSE: - pAr->bVerbose = 1; - break; - case AR_SWITCH_APPEND: - pAr->bAppend = 1; - deliberate_fall_through; - case AR_SWITCH_FILE: - pAr->zFile = zArg; - break; - case AR_SWITCH_DIRECTORY: - pAr->zDir = zArg; - break; - } - - return SQLITE_OK; -} - -/* -** Parse the command line for an ".ar" command. The results are written into -** structure (*pAr). SQLITE_OK is returned if the command line is parsed -** successfully, otherwise an error message is written to stderr and -** SQLITE_ERROR returned. -*/ -static int arParseCommand( - char **azArg, /* Array of arguments passed to dot command */ - int nArg, /* Number of entries in azArg[] */ - ArCommand *pAr /* Populate this object */ -){ - struct ArSwitch { - const char *zLong; - char cShort; - u8 eSwitch; - u8 bArg; - } aSwitch[] = { - { "create", 'c', AR_CMD_CREATE, 0 }, - { "extract", 'x', AR_CMD_EXTRACT, 0 }, - { "insert", 'i', AR_CMD_INSERT, 0 }, - { "list", 't', AR_CMD_LIST, 0 }, - { "remove", 'r', AR_CMD_REMOVE, 0 }, - { "update", 'u', AR_CMD_UPDATE, 0 }, - { "help", 'h', AR_CMD_HELP, 0 }, - { "verbose", 'v', AR_SWITCH_VERBOSE, 0 }, - { "file", 'f', AR_SWITCH_FILE, 1 }, - { "append", 'a', AR_SWITCH_APPEND, 1 }, - { "directory", 'C', AR_SWITCH_DIRECTORY, 1 }, - { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 }, - { "glob", 'g', AR_SWITCH_GLOB, 0 }, - }; - int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch); - struct ArSwitch *pEnd = &aSwitch[nSwitch]; - - if( nArg<=1 ){ - sqlite3_fprintf(stderr, "Wrong number of arguments. Usage:\n"); - return arUsage(stderr); - }else{ - char *z = azArg[1]; - if( z[0]!='-' ){ - /* Traditional style [tar] invocation */ - int i; - int iArg = 2; - for(i=0; z[i]; i++){ - const char *zArg = 0; - struct ArSwitch *pOpt; - for(pOpt=&aSwitch[0]; pOptcShort ) break; - } - if( pOpt==pEnd ){ - return arErrorMsg(pAr, "unrecognized option: %c", z[i]); - } - if( pOpt->bArg ){ - if( iArg>=nArg ){ - return arErrorMsg(pAr, "option requires an argument: %c",z[i]); - } - zArg = azArg[iArg++]; - } - if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; - } - pAr->nArg = nArg-iArg; - if( pAr->nArg>0 ){ - pAr->azArg = &azArg[iArg]; - } - }else{ - /* Non-traditional invocation */ - int iArg; - for(iArg=1; iArgazArg = &azArg[iArg]; - pAr->nArg = nArg-iArg; - break; - } - n = strlen30(z); - - if( z[1]!='-' ){ - int i; - /* One or more short options */ - for(i=1; icShort ) break; - } - if( pOpt==pEnd ){ - return arErrorMsg(pAr, "unrecognized option: %c", z[i]); - } - if( pOpt->bArg ){ - if( i<(n-1) ){ - zArg = &z[i+1]; - i = n; - }else{ - if( iArg>=(nArg-1) ){ - return arErrorMsg(pAr, "option requires an argument: %c", - z[i]); - } - zArg = azArg[++iArg]; - } - } - if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; - } - }else if( z[2]=='\0' ){ - /* A -- option, indicating that all remaining command line words - ** are command arguments. */ - pAr->azArg = &azArg[iArg+1]; - pAr->nArg = nArg-iArg-1; - break; - }else{ - /* A long option */ - const char *zArg = 0; /* Argument for option, if any */ - struct ArSwitch *pMatch = 0; /* Matching option */ - struct ArSwitch *pOpt; /* Iterator */ - for(pOpt=&aSwitch[0]; pOptzLong; - if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ - if( pMatch ){ - return arErrorMsg(pAr, "ambiguous option: %s",z); - }else{ - pMatch = pOpt; - } - } - } - - if( pMatch==0 ){ - return arErrorMsg(pAr, "unrecognized option: %s", z); - } - if( pMatch->bArg ){ - if( iArg>=(nArg-1) ){ - return arErrorMsg(pAr, "option requires an argument: %s", z); - } - zArg = azArg[++iArg]; - } - if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; - } - } - } - } - if( pAr->eCmd==0 ){ - sqlite3_fprintf(stderr, "Required argument missing. Usage:\n"); - return arUsage(stderr); - } - return SQLITE_OK; -} - -/* -** This function assumes that all arguments within the ArCommand.azArg[] -** array refer to archive members, as for the --extract, --list or --remove -** commands. It checks that each of them are "present". If any specified -** file is not present in the archive, an error is printed to stderr and an -** error code returned. Otherwise, if all specified arguments are present -** in the archive, SQLITE_OK is returned. Here, "present" means either an -** exact equality when pAr->bGlob is false or a "name GLOB pattern" match -** when pAr->bGlob is true. -** -** This function strips any trailing '/' characters from each argument. -** This is consistent with the way the [tar] command seems to work on -** Linux. -*/ -static int arCheckEntries(ArCommand *pAr){ - int rc = SQLITE_OK; - if( pAr->nArg ){ - int i, j; - sqlite3_stmt *pTest = 0; - const char *zSel = (pAr->bGlob) - ? "SELECT name FROM %s WHERE glob($name,name)" - : "SELECT name FROM %s WHERE name=$name"; - - shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable); - j = sqlite3_bind_parameter_index(pTest, "$name"); - for(i=0; inArg && rc==SQLITE_OK; i++){ - char *z = pAr->azArg[i]; - int n = strlen30(z); - int bOk = 0; - while( n>0 && z[n-1]=='/' ) n--; - z[n] = '\0'; - sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); - if( SQLITE_ROW==sqlite3_step(pTest) ){ - bOk = 1; - } - shellReset(&rc, pTest); - if( rc==SQLITE_OK && bOk==0 ){ - sqlite3_fprintf(stderr,"not found in archive: %s\n", z); - rc = SQLITE_ERROR; - } - } - shellFinalize(&rc, pTest); - } - return rc; -} - -/* -** Format a WHERE clause that can be used against the "sqlar" table to -** identify all archive members that match the command arguments held -** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning. -** The caller is responsible for eventually calling sqlite3_free() on -** any non-NULL (*pzWhere) value. Here, "match" means strict equality -** when pAr->bGlob is false and GLOB match when pAr->bGlob is true. -*/ -static void arWhereClause( - int *pRc, - ArCommand *pAr, - char **pzWhere /* OUT: New WHERE clause */ -){ - char *zWhere = 0; - const char *zSameOp = (pAr->bGlob)? "GLOB" : "="; - if( *pRc==SQLITE_OK ){ - if( pAr->nArg==0 ){ - zWhere = sqlite3_mprintf("1"); - }else{ - int i; - const char *zSep = ""; - for(i=0; inArg; i++){ - const char *z = pAr->azArg[i]; - zWhere = sqlite3_mprintf( - "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'", - zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z - ); - if( zWhere==0 ){ - *pRc = SQLITE_NOMEM; - break; - } - zSep = " OR "; - } - } - } - *pzWhere = zWhere; -} - -/* -** Implementation of .ar "lisT" command. -*/ -static int arListCommand(ArCommand *pAr){ - const char *zSql = "SELECT %s FROM %s WHERE %s"; - const char *azCols[] = { - "name", - "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name" - }; - - char *zWhere = 0; - sqlite3_stmt *pSql = 0; - int rc; - - rc = arCheckEntries(pAr); - arWhereClause(&rc, pAr, &zWhere); - - shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], - pAr->zSrcTable, zWhere); - if( pAr->bDryRun ){ - sqlite3_fprintf(pAr->out, "%s\n", sqlite3_sql(pSql)); - }else{ - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ - if( pAr->bVerbose ){ - sqlite3_fprintf(pAr->out, "%s % 10d %s %s\n", - sqlite3_column_text(pSql, 0), sqlite3_column_int(pSql, 1), - sqlite3_column_text(pSql, 2),sqlite3_column_text(pSql, 3)); - }else{ - sqlite3_fprintf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0)); - } - } - } - shellFinalize(&rc, pSql); - sqlite3_free(zWhere); - return rc; -} - -/* -** Implementation of .ar "Remove" command. -*/ -static int arRemoveCommand(ArCommand *pAr){ - int rc = 0; - char *zSql = 0; - char *zWhere = 0; - - if( pAr->nArg ){ - /* Verify that args actually exist within the archive before proceeding. - ** And formulate a WHERE clause to match them. */ - rc = arCheckEntries(pAr); - arWhereClause(&rc, pAr, &zWhere); - } - if( rc==SQLITE_OK ){ - zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;", - pAr->zSrcTable, zWhere); - if( pAr->bDryRun ){ - sqlite3_fprintf(pAr->out, "%s\n", zSql); - }else{ - char *zErr = 0; - rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); - if( rc!=SQLITE_OK ){ - sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); - }else{ - rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0); - } - } - if( zErr ){ - sqlite3_fprintf(stdout, "ERROR: %s\n", zErr); /* stdout? */ - sqlite3_free(zErr); - } - } - } - sqlite3_free(zWhere); - sqlite3_free(zSql); - return rc; -} - -/* -** Implementation of .ar "eXtract" command. -*/ -static int arExtractCommand(ArCommand *pAr){ - const char *zSql1 = - "SELECT " - " ($dir || name)," - " writefile(($dir || name), %s, mode, mtime) " - "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)" - " AND name NOT GLOB '*..[/\\]*'"; - - const char *azExtraArg[] = { - "sqlar_uncompress(data, sz)", - "data" - }; - - sqlite3_stmt *pSql = 0; - int rc = SQLITE_OK; - char *zDir = 0; - char *zWhere = 0; - int i, j; - - /* If arguments are specified, check that they actually exist within - ** the archive before proceeding. And formulate a WHERE clause to - ** match them. */ - rc = arCheckEntries(pAr); - arWhereClause(&rc, pAr, &zWhere); - - if( rc==SQLITE_OK ){ - if( pAr->zDir ){ - zDir = sqlite3_mprintf("%s/", pAr->zDir); - }else{ - zDir = sqlite3_mprintf(""); - } - if( zDir==0 ) rc = SQLITE_NOMEM; - } - - shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, - azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere - ); - - if( rc==SQLITE_OK ){ - j = sqlite3_bind_parameter_index(pSql, "$dir"); - sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); - - /* Run the SELECT statement twice. The first time, writefile() is called - ** for all archive members that should be extracted. The second time, - ** only for the directories. This is because the timestamps for - ** extracted directories must be reset after they are populated (as - ** populating them changes the timestamp). */ - for(i=0; i<2; i++){ - j = sqlite3_bind_parameter_index(pSql, "$dirOnly"); - sqlite3_bind_int(pSql, j, i); - if( pAr->bDryRun ){ - sqlite3_fprintf(pAr->out, "%s\n", sqlite3_sql(pSql)); - }else{ - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ - if( i==0 && pAr->bVerbose ){ - sqlite3_fprintf(pAr->out, "%s\n", sqlite3_column_text(pSql, 0)); - } - } - } - shellReset(&rc, pSql); - } - shellFinalize(&rc, pSql); - } - - sqlite3_free(zDir); - sqlite3_free(zWhere); - return rc; -} - -/* -** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out. -*/ -static int arExecSql(ArCommand *pAr, const char *zSql){ - int rc; - if( pAr->bDryRun ){ - sqlite3_fprintf(pAr->out, "%s\n", zSql); - rc = SQLITE_OK; - }else{ - char *zErr = 0; - rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); - if( zErr ){ - sqlite3_fprintf(stdout, "ERROR: %s\n", zErr); - sqlite3_free(zErr); - } - } - return rc; -} - - -/* -** Implementation of .ar "create", "insert", and "update" commands. -** -** create -> Create a new SQL archive -** insert -> Insert or reinsert all files listed -** update -> Insert files that have changed or that were not -** previously in the archive -** -** Create the "sqlar" table in the database if it does not already exist. -** Then add each file in the azFile[] array to the archive. Directories -** are added recursively. If argument bVerbose is non-zero, a message is -** printed on stdout for each file archived. -** -** The create command is the same as update, except that it drops -** any existing "sqlar" table before beginning. The "insert" command -** always overwrites every file named on the command-line, where as -** "update" only overwrites if the size or mtime or mode has changed. -*/ -static int arCreateOrUpdateCommand( - ArCommand *pAr, /* Command arguments and options */ - int bUpdate, /* true for a --create. */ - int bOnlyIfChanged /* Only update if file has changed */ -){ - const char *zCreate = - "CREATE TABLE IF NOT EXISTS sqlar(\n" - " name TEXT PRIMARY KEY, -- name of the file\n" - " mode INT, -- access permissions\n" - " mtime INT, -- last modification time\n" - " sz INT, -- original file size\n" - " data BLOB -- compressed content\n" - ")"; - const char *zDrop = "DROP TABLE IF EXISTS sqlar"; - const char *zInsertFmt[2] = { - "REPLACE INTO %s(name,mode,mtime,sz,data)\n" - " SELECT\n" - " %s,\n" - " mode,\n" - " mtime,\n" - " CASE substr(lsmode(mode),1,1)\n" - " WHEN '-' THEN length(data)\n" - " WHEN 'd' THEN 0\n" - " ELSE -1 END,\n" - " sqlar_compress(data)\n" - " FROM fsdir(%Q,%Q) AS disk\n" - " WHERE lsmode(mode) NOT LIKE '?%%'%s;" - , - "REPLACE INTO %s(name,mode,mtime,data)\n" - " SELECT\n" - " %s,\n" - " mode,\n" - " mtime,\n" - " data\n" - " FROM fsdir(%Q,%Q) AS disk\n" - " WHERE lsmode(mode) NOT LIKE '?%%'%s;" - }; - int i; /* For iterating through azFile[] */ - int rc; /* Return code */ - const char *zTab = 0; /* SQL table into which to insert */ - char *zSql; - char zTemp[50]; - char *zExists = 0; - - arExecSql(pAr, "PRAGMA page_size=512"); - rc = arExecSql(pAr, "SAVEPOINT ar;"); - if( rc!=SQLITE_OK ) return rc; - zTemp[0] = 0; - if( pAr->bZip ){ - /* Initialize the zipfile virtual table, if necessary */ - if( pAr->zFile ){ - sqlite3_uint64 r; - sqlite3_randomness(sizeof(r),&r); - sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r); - zTab = zTemp; - zSql = sqlite3_mprintf( - "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)", - zTab, pAr->zFile - ); - rc = arExecSql(pAr, zSql); - sqlite3_free(zSql); - }else{ - zTab = "zip"; - } - }else{ - /* Initialize the table for an SQLAR */ - zTab = "sqlar"; - if( bUpdate==0 ){ - rc = arExecSql(pAr, zDrop); - if( rc!=SQLITE_OK ) goto end_ar_transaction; - } - rc = arExecSql(pAr, zCreate); - } - if( bOnlyIfChanged ){ - zExists = sqlite3_mprintf( - " AND NOT EXISTS(" - "SELECT 1 FROM %s AS mem" - " WHERE mem.name=disk.name" - " AND mem.mtime=disk.mtime" - " AND mem.mode=disk.mode)", zTab); - }else{ - zExists = sqlite3_mprintf(""); - } - if( zExists==0 ) rc = SQLITE_NOMEM; - for(i=0; inArg && rc==SQLITE_OK; i++){ - char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, - pAr->bVerbose ? "shell_putsnl(name)" : "name", - pAr->azArg[i], pAr->zDir, zExists); - rc = arExecSql(pAr, zSql2); - sqlite3_free(zSql2); - } -end_ar_transaction: - if( rc!=SQLITE_OK ){ - sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); - }else{ - rc = arExecSql(pAr, "RELEASE ar;"); - if( pAr->bZip && pAr->zFile ){ - zSql = sqlite3_mprintf("DROP TABLE %s", zTemp); - arExecSql(pAr, zSql); - sqlite3_free(zSql); - } - } - sqlite3_free(zExists); - return rc; -} - -/* -** Implementation of ".ar" dot command. -*/ -static int arDotCommand( - ShellState *pState, /* Current shell tool state */ - int fromCmdLine, /* True if -A command-line option, not .ar cmd */ - char **azArg, /* Array of arguments passed to dot command */ - int nArg /* Number of entries in azArg[] */ -){ - ArCommand cmd; - int rc; - memset(&cmd, 0, sizeof(cmd)); - cmd.fromCmdLine = fromCmdLine; - rc = arParseCommand(azArg, nArg, &cmd); - if( rc==SQLITE_OK ){ - int eDbType = SHELL_OPEN_UNSPEC; - cmd.p = pState; - cmd.out = pState->out; - cmd.db = pState->db; - if( cmd.zFile ){ - eDbType = deduceDatabaseType(cmd.zFile, 1); - }else{ - eDbType = pState->openMode; - } - if( eDbType==SHELL_OPEN_ZIPFILE ){ - if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){ - if( cmd.zFile==0 ){ - cmd.zSrcTable = sqlite3_mprintf("zip"); - }else{ - cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile); - } - } - cmd.bZip = 1; - }else if( cmd.zFile ){ - int flags; - if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS; - if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT - || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){ - flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; - }else{ - flags = SQLITE_OPEN_READONLY; - } - cmd.db = 0; - if( cmd.bDryRun ){ - sqlite3_fprintf(cmd.out, "-- open database '%s'%s\n", cmd.zFile, - eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : ""); - } - rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, - eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0); - if( rc!=SQLITE_OK ){ - sqlite3_fprintf(stderr, "cannot open file: %s (%s)\n", - cmd.zFile, sqlite3_errmsg(cmd.db)); - goto end_ar_command; - } - sqlite3_fileio_init(cmd.db, 0, 0); - sqlite3_sqlar_init(cmd.db, 0, 0); - sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p, - shellPutsFunc, 0, 0); - - } - if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){ - if( cmd.eCmd!=AR_CMD_CREATE - && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0) - ){ - sqlite3_fprintf(stderr, "database does not contain an 'sqlar' table\n"); - rc = SQLITE_ERROR; - goto end_ar_command; - } - cmd.zSrcTable = sqlite3_mprintf("sqlar"); - } - - switch( cmd.eCmd ){ - case AR_CMD_CREATE: - rc = arCreateOrUpdateCommand(&cmd, 0, 0); - break; - - case AR_CMD_EXTRACT: - rc = arExtractCommand(&cmd); - break; - - case AR_CMD_LIST: - rc = arListCommand(&cmd); - break; - - case AR_CMD_HELP: - arUsage(pState->out); - break; - - case AR_CMD_INSERT: - rc = arCreateOrUpdateCommand(&cmd, 1, 0); - break; - - case AR_CMD_REMOVE: - rc = arRemoveCommand(&cmd); - break; - - default: - assert( cmd.eCmd==AR_CMD_UPDATE ); - rc = arCreateOrUpdateCommand(&cmd, 1, 1); - break; - } - } -end_ar_command: - if( cmd.db!=pState->db ){ - close_db(cmd.db); - } - sqlite3_free(cmd.zSrcTable); - - return rc; -} -/* End of the ".archive" or ".ar" command logic -*******************************************************************************/ -#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */ - -#if SQLITE_SHELL_HAVE_RECOVER - -/* -** This function is used as a callback by the recover extension. Simply -** print the supplied SQL statement to stdout. -*/ -static int recoverSqlCb(void *pCtx, const char *zSql){ - ShellState *pState = (ShellState*)pCtx; - sqlite3_fprintf(pState->out, "%s;\n", zSql); - return SQLITE_OK; -} - -/* -** This function is called to recover data from the database. A script -** to construct a new database containing all recovered data is output -** on stream pState->out. -*/ -static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){ - int rc = SQLITE_OK; - const char *zRecoveryDb = ""; /* Name of "recovery" database. Debug only */ - const char *zLAF = "lost_and_found"; - int bFreelist = 1; /* 0 if --ignore-freelist is specified */ - int bRowids = 1; /* 0 if --no-rowids */ - sqlite3_recover *p = 0; - int i = 0; - - for(i=1; iout, azArg[0]); - return 1; - } - } - - p = sqlite3_recover_init_sql( - pState->db, "main", recoverSqlCb, (void*)pState - ); - - sqlite3_recover_config(p, 789, (void*)zRecoveryDb); /* Debug use only */ - sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF); - sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids); - sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist); - - sqlite3_recover_run(p); - if( sqlite3_recover_errcode(p)!=SQLITE_OK ){ - const char *zErr = sqlite3_recover_errmsg(p); - int errCode = sqlite3_recover_errcode(p); - sqlite3_fprintf(stderr,"sql error: %s (%d)\n", zErr, errCode); - } - rc = sqlite3_recover_finish(p); - return rc; -} -#endif /* SQLITE_SHELL_HAVE_RECOVER */ - -/* -** Implementation of ".intck STEPS_PER_UNLOCK" command. -*/ -static int intckDatabaseCmd(ShellState *pState, i64 nStepPerUnlock){ - sqlite3_intck *p = 0; - int rc = SQLITE_OK; - - rc = sqlite3_intck_open(pState->db, "main", &p); - if( rc==SQLITE_OK ){ - i64 nStep = 0; - i64 nError = 0; - const char *zErr = 0; - while( SQLITE_OK==sqlite3_intck_step(p) ){ - const char *zMsg = sqlite3_intck_message(p); - if( zMsg ){ - sqlite3_fprintf(pState->out, "%s\n", zMsg); - nError++; - } - nStep++; - if( nStepPerUnlock && (nStep % nStepPerUnlock)==0 ){ - sqlite3_intck_unlock(p); - } - } - rc = sqlite3_intck_error(p, &zErr); - if( zErr ){ - sqlite3_fprintf(stderr,"%s\n", zErr); - } - sqlite3_intck_close(p); - - sqlite3_fprintf(pState->out, "%lld steps, %lld errors\n", nStep, nError); - } - - return rc; -} - -/* - * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it. - * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE, - * close db and set it to 0, and return the columns spec, to later - * be sqlite3_free()'ed by the caller. - * The return is 0 when either: - * (a) The db was not initialized and zCol==0 (There are no columns.) - * (b) zCol!=0 (Column was added, db initialized as needed.) - * The 3rd argument, pRenamed, references an out parameter. If the - * pointer is non-zero, its referent will be set to a summary of renames - * done if renaming was necessary, or set to 0 if none was done. The out - * string (if any) must be sqlite3_free()'ed by the caller. - */ -#ifdef SHELL_DEBUG -#define rc_err_oom_die(rc) \ - if( rc==SQLITE_NOMEM ) shell_check_oom(0); \ - else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \ - sqlite3_fprintf(stderr,"E:%d\n",rc), assert(0) -#else -static void rc_err_oom_die(int rc){ - if( rc==SQLITE_NOMEM ) shell_check_oom(0); - assert(rc==SQLITE_OK||rc==SQLITE_DONE); -} -#endif - -#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */ -static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB); -#else /* Otherwise, memory is faster/better for the transient DB. */ -static const char *zCOL_DB = ":memory:"; -#endif - -/* Define character (as C string) to separate generated column ordinal - * from protected part of incoming column names. This defaults to "_" - * so that incoming column identifiers that did not need not be quoted - * remain usable without being quoted. It must be one character. - */ -#ifndef SHELL_AUTOCOLUMN_SEP -# define AUTOCOLUMN_SEP "_" -#else -# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP) -#endif - -static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){ - /* Queries and D{D,M}L used here */ - static const char * const zTabMake = "\ -CREATE TABLE ColNames(\ - cpos INTEGER PRIMARY KEY,\ - name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\ -CREATE VIEW RepeatedNames AS \ -SELECT DISTINCT t.name FROM ColNames t \ -WHERE t.name COLLATE NOCASE IN (\ - SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\ -);\ -"; - static const char * const zTabFill = "\ -INSERT INTO ColNames(name,nlen,chop,reps,suff)\ - VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\ -"; - static const char * const zHasDupes = "\ -SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\ - 1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')" -#else /* ...RENAME_MINIMAL_ONE_PASS */ -"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */ -" SELECT 0 AS nlz" -" UNION" -" SELECT nlz+1 AS nlz FROM Lzn" -" WHERE EXISTS(" -" SELECT 1" -" FROM ColNames t, ColNames o" -" WHERE" -" iif(t.name IN (SELECT * FROM RepeatedNames)," -" printf('%s"AUTOCOLUMN_SEP"%s'," -" t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2))," -" t.name" -" )" -" =" -" iif(o.name IN (SELECT * FROM RepeatedNames)," -" printf('%s"AUTOCOLUMN_SEP"%s'," -" o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2))," -" o.name" -" )" -" COLLATE NOCASE" -" AND o.cpos<>t.cpos" -" GROUP BY t.cpos" -" )" -") UPDATE Colnames AS t SET" -" chop = 0," /* No chopping, never touch incoming names. */ -" suff = iif(name IN (SELECT * FROM RepeatedNames)," -" printf('"AUTOCOLUMN_SEP"%s', substring(" -" printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2))," -" ''" -" )" -#endif - ; - static const char * const zCollectVar = "\ -SELECT\ - '('||x'0a'\ - || group_concat(\ - cname||' TEXT',\ - ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\ - ||')' AS ColsSpec \ -FROM (\ - SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \ - FROM ColNames ORDER BY cpos\ -)"; - static const char * const zRenamesDone = - "SELECT group_concat(" - " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff))," - " ','||x'0a')" - "FROM ColNames WHERE suff<>'' OR chop!=0" - ; - int rc; - sqlite3_stmt *pStmt = 0; - assert(pDb!=0); - if( zColNew ){ - /* Add initial or additional column. Init db if necessary. */ - if( *pDb==0 ){ - if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0; -#ifdef SHELL_COLFIX_DB - if(*zCOL_DB!=':') - sqlite3_exec(*pDb,"drop table if exists ColNames;" - "drop view if exists RepeatedNames;",0,0,0); -#endif -#undef SHELL_COLFIX_DB - rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0); - rc_err_oom_die(rc); - } - assert(*pDb!=0); - rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0); - rc_err_oom_die(rc); - rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0); - rc_err_oom_die(rc); - rc = sqlite3_step(pStmt); - rc_err_oom_die(rc); - sqlite3_finalize(pStmt); - return 0; - }else if( *pDb==0 ){ - return 0; - }else{ - /* Formulate the columns spec, close the DB, zero *pDb. */ - char *zColsSpec = 0; - int hasDupes = db_int(*pDb, zHasDupes); - int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0; - if( hasDupes ){ -#ifdef SHELL_COLUMN_RENAME_CLEAN - rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0); - rc_err_oom_die(rc); -#endif - rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0); - rc_err_oom_die(rc); - rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0); - rc_err_oom_die(rc); - sqlite3_bind_int(pStmt, 1, nDigits); - rc = sqlite3_step(pStmt); - sqlite3_finalize(pStmt); - if( rc!=SQLITE_DONE ) rc_err_oom_die(SQLITE_NOMEM); - } - assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */ - rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0); - rc_err_oom_die(rc); - rc = sqlite3_step(pStmt); - if( rc==SQLITE_ROW ){ - zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); - }else{ - zColsSpec = 0; - } - if( pzRenamed!=0 ){ - if( !hasDupes ) *pzRenamed = 0; - else{ - sqlite3_finalize(pStmt); - if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0) - && SQLITE_ROW==sqlite3_step(pStmt) ){ - *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); - }else - *pzRenamed = 0; - } - } - sqlite3_finalize(pStmt); - sqlite3_close(*pDb); - *pDb = 0; - return zColsSpec; - } -} - -/* -** Check if the sqlite_schema table contains one or more virtual tables. If -** parameter zLike is not NULL, then it is an SQL expression that the -** sqlite_schema row must also match. If one or more such rows are found, -** print the following warning to the output: -** -** WARNING: Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled -*/ -static int outputDumpWarning(ShellState *p, const char *zLike){ - int rc = SQLITE_OK; - sqlite3_stmt *pStmt = 0; - shellPreparePrintf(p->db, &rc, &pStmt, - "SELECT 1 FROM sqlite_schema o WHERE " - "sql LIKE 'CREATE VIRTUAL TABLE%%' AND %s", zLike ? zLike : "true" - ); - if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ - sqlite3_fputs("/* WARNING: " - "Script requires that SQLITE_DBCONFIG_DEFENSIVE be disabled */\n", - p->out - ); - } - shellFinalize(&rc, pStmt); - return rc; -} - -/* -** Fault-Simulator state and logic. -*/ -static struct { - int iId; /* ID that triggers a simulated fault. -1 means "any" */ - int iErr; /* The error code to return on a fault */ - int iCnt; /* Trigger the fault only if iCnt is already zero */ - int iInterval; /* Reset iCnt to this value after each fault */ - int eVerbose; /* When to print output */ - int nHit; /* Number of hits seen so far */ - int nRepeat; /* Turn off after this many hits. 0 for never */ - int nSkip; /* Skip this many before first fault */ -} faultsim_state = {-1, 0, 0, 0, 0, 0, 0, 0}; - -/* -** This is the fault-sim callback -*/ -static int faultsim_callback(int iArg){ - if( faultsim_state.iId>0 && faultsim_state.iId!=iArg ){ - return SQLITE_OK; - } - if( faultsim_state.iCnt ){ - if( faultsim_state.iCnt>0 ) faultsim_state.iCnt--; - if( faultsim_state.eVerbose>=2 ){ - sqlite3_fprintf(stdout, - "FAULT-SIM id=%d no-fault (cnt=%d)\n", iArg, faultsim_state.iCnt); - } - return SQLITE_OK; - } - if( faultsim_state.eVerbose>=1 ){ - sqlite3_fprintf(stdout, - "FAULT-SIM id=%d returns %d\n", iArg, faultsim_state.iErr); - } - faultsim_state.iCnt = faultsim_state.iInterval; - faultsim_state.nHit++; - if( faultsim_state.nRepeat>0 && faultsim_state.nRepeat<=faultsim_state.nHit ){ - faultsim_state.iCnt = -1; - } - return faultsim_state.iErr; -} - -/* -** If an input line begins with "." then invoke this routine to -** process that line. -** -** Return 1 on error, 2 to exit, and 0 otherwise. -*/ -static int do_meta_command(char *zLine, ShellState *p){ - int h = 1; - int nArg = 0; - int n, c; - int rc = 0; - char *azArg[52]; - -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( p->expert.pExpert ){ - expertFinish(p, 1, 0); - } -#endif - - /* Parse the input line into tokens. - */ - while( zLine[h] && nArgdb, shellAuth, p); - }else if( p->bSafeModePersist ){ - sqlite3_set_authorizer(p->db, safeModeAuth, p); - }else{ - sqlite3_set_authorizer(p->db, 0, 0); - } - }else -#endif - -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \ - && !defined(SQLITE_SHELL_FIDDLE) - if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){ - open_db(p, 0); - failIfSafeMode(p, "cannot run .archive in safe mode"); - rc = arDotCommand(p, 0, azArg, nArg); - }else -#endif - -#ifndef SQLITE_SHELL_FIDDLE - if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0) - || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0) - ){ - const char *zDestFile = 0; - const char *zDb = 0; - sqlite3 *pDest; - sqlite3_backup *pBackup; - int j; - int bAsync = 0; - const char *zVfs = 0; - failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); - for(j=1; jdb, zDb); - if( pBackup==0 ){ - shellDatabaseError(pDest); - close_db(pDest); - return 1; - } - while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} - sqlite3_backup_finish(pBackup); - if( rc==SQLITE_DONE ){ - rc = 0; - }else{ - shellDatabaseError(pDest); - rc = 1; - } - close_db(pDest); - }else -#endif /* !defined(SQLITE_SHELL_FIDDLE) */ - - if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){ - if( nArg==2 ){ - bail_on_error = booleanValue(azArg[1]); - }else{ - eputz("Usage: .bail on|off\n"); - rc = 1; - } - }else - - /* Undocumented. Legacy only. See "crlf" below */ - if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){ - eputz("The \".binary\" command is deprecated.\n"); - rc = 1; - }else - - /* The undocumented ".breakpoint" command causes a call to the no-op - ** routine named test_breakpoint(). - */ - if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){ - test_breakpoint(); - }else - -#ifndef SQLITE_SHELL_FIDDLE - if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){ - failIfSafeMode(p, "cannot run .cd in safe mode"); - if( nArg==2 ){ -#if defined(_WIN32) || defined(WIN32) - wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]); - rc = !SetCurrentDirectoryW(z); - sqlite3_free(z); -#else - rc = chdir(azArg[1]); -#endif - if( rc ){ - sqlite3_fprintf(stderr,"Cannot change to directory \"%s\"\n", azArg[1]); - rc = 1; - } - }else{ - eputz("Usage: .cd DIRECTORY\n"); - rc = 1; - } - }else -#endif /* !defined(SQLITE_SHELL_FIDDLE) */ - - if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){ - if( nArg==2 ){ - setOrClearFlag(p, SHFLG_CountChanges, azArg[1]); - }else{ - eputz("Usage: .changes on|off\n"); - rc = 1; - } - }else - -#ifndef SQLITE_SHELL_FIDDLE - /* Cancel output redirection, if it is currently set (by .testcase) - ** Then read the content of the testcase-out.txt file and compare against - ** azArg[1]. If there are differences, report an error and exit. - */ - if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){ - char *zRes = 0; - output_reset(p); - if( nArg!=2 ){ - eputz("Usage: .check GLOB-PATTERN\n"); - rc = 2; - }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ - rc = 2; - }else if( testcase_glob(azArg[1],zRes)==0 ){ - sqlite3_fprintf(stderr, - "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", - p->zTestcase, azArg[1], zRes); - rc = 1; - }else{ - sqlite3_fprintf(p->out, "testcase-%s ok\n", p->zTestcase); - p->nCheck++; - } - sqlite3_free(zRes); - }else -#endif /* !defined(SQLITE_SHELL_FIDDLE) */ - -#ifndef SQLITE_SHELL_FIDDLE - if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){ - failIfSafeMode(p, "cannot run .clone in safe mode"); - if( nArg==2 ){ - tryToClone(p, azArg[1]); - }else{ - eputz("Usage: .clone FILENAME\n"); - rc = 1; - } - }else -#endif /* !defined(SQLITE_SHELL_FIDDLE) */ - - if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){ - if( nArg==1 ){ - /* List available connections */ - int i; - for(i=0; iaAuxDb); i++){ - const char *zFile = p->aAuxDb[i].zDbFilename; - if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){ - zFile = "(not open)"; - }else if( zFile==0 ){ - zFile = "(memory)"; - }else if( zFile[0]==0 ){ - zFile = "(temporary-file)"; - } - if( p->pAuxDb == &p->aAuxDb[i] ){ - sqlite3_fprintf(stdout, "ACTIVE %d: %s\n", i, zFile); - }else if( p->aAuxDb[i].db!=0 ){ - sqlite3_fprintf(stdout, " %d: %s\n", i, zFile); - } - } - }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){ - int i = azArg[1][0] - '0'; - if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && iaAuxDb) ){ - p->pAuxDb->db = p->db; - p->pAuxDb = &p->aAuxDb[i]; - globalDb = p->db = p->pAuxDb->db; - p->pAuxDb->db = 0; - } - }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0 - && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){ - int i = azArg[2][0] - '0'; - if( i<0 || i>=ArraySize(p->aAuxDb) ){ - /* No-op */ - }else if( p->pAuxDb == &p->aAuxDb[i] ){ - eputz("cannot close the active database connection\n"); - rc = 1; - }else if( p->aAuxDb[i].db ){ - session_close_all(p, i); - close_db(p->aAuxDb[i].db); - p->aAuxDb[i].db = 0; - } - }else{ - eputz("Usage: .connection [close] [CONNECTION-NUMBER]\n"); - rc = 1; - } - }else - - if( c=='c' && n==4 - && (cli_strncmp(azArg[0], "crlf", n)==0 - || cli_strncmp(azArg[0], "crnl",n)==0) - ){ - if( nArg==2 ){ -#ifdef _WIN32 - p->crlfMode = booleanValue(azArg[1]); -#else - p->crlfMode = 0; -#endif - } - sqlite3_fprintf(stderr, "crlf is %s\n", p->crlfMode ? "ON" : "OFF"); - }else - - if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){ - char **azName = 0; - int nName = 0; - sqlite3_stmt *pStmt; - int i; - open_db(p, 0); - rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); - if( rc ){ - shellDatabaseError(p->db); - rc = 1; - }else{ - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - const char *zSchema = (const char *)sqlite3_column_text(pStmt,1); - const char *zFile = (const char*)sqlite3_column_text(pStmt,2); - if( zSchema==0 || zFile==0 ) continue; - azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*)); - shell_check_oom(azName); - azName[nName*2] = strdup(zSchema); - azName[nName*2+1] = strdup(zFile); - nName++; - } - } - sqlite3_finalize(pStmt); - for(i=0; idb, azName[i*2]); - int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]); - const char *z = azName[i*2+1]; - sqlite3_fprintf(p->out, "%s: %s %s%s\n", - azName[i*2], z && z[0] ? z : "\"\"", bRdonly ? "r/o" : "r/w", - eTxn==SQLITE_TXN_NONE ? "" : - eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn"); - free(azName[i*2]); - free(azName[i*2+1]); - } - sqlite3_free(azName); - }else - - if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){ - static const struct DbConfigChoices { - const char *zName; - int op; - } aDbConfig[] = { - { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, - { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL }, - { "dqs_dml", SQLITE_DBCONFIG_DQS_DML }, - { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, - { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, - { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, - { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW }, - { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, - { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE }, - { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT }, - { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, - { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, - { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, - { "reverse_scanorder", SQLITE_DBCONFIG_REVERSE_SCANORDER }, - { "stmt_scanstatus", SQLITE_DBCONFIG_STMT_SCANSTATUS }, - { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, - { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA }, - { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA }, - }; - int ii, v; - open_db(p, 0); - for(ii=0; ii1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue; - if( nArg>=3 ){ - sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); - } - sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); - sqlite3_fprintf(p->out, "%19s %s\n", - aDbConfig[ii].zName, v ? "on" : "off"); - if( nArg>1 ) break; - } - if( nArg>1 && ii==ArraySize(aDbConfig) ){ - sqlite3_fprintf(stderr,"Error: unknown dbconfig \"%s\"\n", azArg[1]); - eputz("Enter \".dbconfig\" with no arguments for a list\n"); - } - }else - -#if SQLITE_SHELL_HAVE_RECOVER - if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){ - rc = shell_dbinfo_command(p, nArg, azArg); - }else - - if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){ - open_db(p, 0); - rc = recoverDatabaseCmd(p, nArg, azArg); - }else -#endif /* SQLITE_SHELL_HAVE_RECOVER */ - - if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){ - char *zLike = 0; - char *zSql; - int i; - int savedShowHeader = p->showHeader; - int savedShellFlags = p->shellFlgs; - ShellClearFlag(p, - SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo - |SHFLG_DumpDataOnly|SHFLG_DumpNoSys); - for(i=1; ishellFlgs & SHFLG_DumpDataOnly)==0 ){ - /* When playing back a "dump", the content might appear in an order - ** which causes immediate foreign key constraints to be violated. - ** So disable foreign-key constraint enforcement to prevent problems. */ - sqlite3_fputs("PRAGMA foreign_keys=OFF;\n", p->out); - sqlite3_fputs("BEGIN TRANSACTION;\n", p->out); - } - p->writableSchema = 0; - p->showHeader = 0; - /* Set writable_schema=ON since doing so forces SQLite to initialize - ** as much of the schema as it can even if the sqlite_schema table is - ** corrupt. */ - sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); - p->nErr = 0; - if( zLike==0 ) zLike = sqlite3_mprintf("true"); - zSql = sqlite3_mprintf( - "SELECT name, type, sql FROM sqlite_schema AS o " - "WHERE (%s) AND type=='table'" - " AND sql NOT NULL" - " ORDER BY tbl_name='sqlite_sequence', rowid", - zLike - ); - run_schema_dump_query(p,zSql); - sqlite3_free(zSql); - if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ - zSql = sqlite3_mprintf( - "SELECT sql FROM sqlite_schema AS o " - "WHERE (%s) AND sql NOT NULL" - " AND type IN ('index','trigger','view') " - "ORDER BY type COLLATE NOCASE DESC", - zLike - ); - run_table_dump_query(p, zSql); - sqlite3_free(zSql); - } - sqlite3_free(zLike); - if( p->writableSchema ){ - sqlite3_fputs("PRAGMA writable_schema=OFF;\n", p->out); - p->writableSchema = 0; - } - sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); - sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); - if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ - sqlite3_fputs(p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n", p->out); - } - p->showHeader = savedShowHeader; - p->shellFlgs = savedShellFlags; - }else - - if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){ - if( nArg==2 ){ - setOrClearFlag(p, SHFLG_Echo, azArg[1]); - }else{ - eputz("Usage: .echo on|off\n"); - rc = 1; - } - }else - - if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){ - if( nArg==2 ){ - p->autoEQPtest = 0; - if( p->autoEQPtrace ){ - if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); - p->autoEQPtrace = 0; - } - if( cli_strcmp(azArg[1],"full")==0 ){ - p->autoEQP = AUTOEQP_full; - }else if( cli_strcmp(azArg[1],"trigger")==0 ){ - p->autoEQP = AUTOEQP_trigger; -#ifdef SQLITE_DEBUG - }else if( cli_strcmp(azArg[1],"test")==0 ){ - p->autoEQP = AUTOEQP_on; - p->autoEQPtest = 1; - }else if( cli_strcmp(azArg[1],"trace")==0 ){ - p->autoEQP = AUTOEQP_full; - p->autoEQPtrace = 1; - open_db(p, 0); - sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0); - sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); -#endif - }else{ - p->autoEQP = (u8)booleanValue(azArg[1]); - } - }else{ - eputz("Usage: .eqp off|on|trace|trigger|full\n"); - rc = 1; - } - }else - -#ifndef SQLITE_SHELL_FIDDLE - if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){ - if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); - rc = 2; - }else -#endif - - /* The ".explain" command is automatic now. It is largely pointless. It - ** retained purely for backwards compatibility */ - if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){ - int val = 1; - if( nArg>=2 ){ - if( cli_strcmp(azArg[1],"auto")==0 ){ - val = 99; - }else{ - val = booleanValue(azArg[1]); - } - } - if( val==1 && p->mode!=MODE_Explain ){ - p->normalMode = p->mode; - p->mode = MODE_Explain; - p->autoExplain = 0; - }else if( val==0 ){ - if( p->mode==MODE_Explain ) p->mode = p->normalMode; - p->autoExplain = 0; - }else if( val==99 ){ - if( p->mode==MODE_Explain ) p->mode = p->normalMode; - p->autoExplain = 1; - } - }else - -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){ - if( p->bSafeMode ){ - sqlite3_fprintf(stderr, - "Cannot run experimental commands such as \"%s\" in safe mode\n", - azArg[0]); - rc = 1; - }else{ - open_db(p, 0); - expertDotCommand(p, azArg, nArg); - } - }else -#endif - - if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){ - static const struct { - const char *zCtrlName; /* Name of a test-control option */ - int ctrlCode; /* Integer code for that option */ - const char *zUsage; /* Usage notes */ - } aCtrl[] = { - { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" }, - { "data_version", SQLITE_FCNTL_DATA_VERSION, "" }, - { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" }, - { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" }, - { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" }, - /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/ - { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" }, - { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" }, - { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" }, - { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" }, - /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/ - }; - int filectrl = -1; - int iCtrl = -1; - sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */ - int isOk = 0; /* 0: usage 1: %lld 2: no-result */ - int n2, i; - const char *zCmd = 0; - const char *zSchema = 0; - - open_db(p, 0); - zCmd = nArg>=2 ? azArg[1] : "help"; - - if( zCmd[0]=='-' - && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0) - && nArg>=4 - ){ - zSchema = azArg[2]; - for(i=3; iout); - for(i=0; iout, - " .filectrl %s %s\n", aCtrl[i].zCtrlName, aCtrl[i].zUsage); - } - rc = 1; - goto meta_command_exit; - } - - /* convert filectrl text option to value. allow any unique prefix - ** of the option name, or a numerical value. */ - n2 = strlen30(zCmd); - for(i=0; idb, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes); - isOk = 1; - break; - } - case SQLITE_FCNTL_LOCK_TIMEOUT: - case SQLITE_FCNTL_CHUNK_SIZE: { - int x; - if( nArg!=3 ) break; - x = (int)integerValue(azArg[2]); - sqlite3_file_control(p->db, zSchema, filectrl, &x); - isOk = 2; - break; - } - case SQLITE_FCNTL_PERSIST_WAL: - case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { - int x; - if( nArg!=2 && nArg!=3 ) break; - x = nArg==3 ? booleanValue(azArg[2]) : -1; - sqlite3_file_control(p->db, zSchema, filectrl, &x); - iRes = x; - isOk = 1; - break; - } - case SQLITE_FCNTL_DATA_VERSION: - case SQLITE_FCNTL_HAS_MOVED: { - int x; - if( nArg!=2 ) break; - sqlite3_file_control(p->db, zSchema, filectrl, &x); - iRes = x; - isOk = 1; - break; - } - case SQLITE_FCNTL_TEMPFILENAME: { - char *z = 0; - if( nArg!=2 ) break; - sqlite3_file_control(p->db, zSchema, filectrl, &z); - if( z ){ - sqlite3_fprintf(p->out, "%s\n", z); - sqlite3_free(z); - } - isOk = 2; - break; - } - case SQLITE_FCNTL_RESERVE_BYTES: { - int x; - if( nArg>=3 ){ - x = atoi(azArg[2]); - sqlite3_file_control(p->db, zSchema, filectrl, &x); - } - x = -1; - sqlite3_file_control(p->db, zSchema, filectrl, &x); - sqlite3_fprintf(p->out, "%d\n", x); - isOk = 2; - break; - } - } - } - if( isOk==0 && iCtrl>=0 ){ - sqlite3_fprintf(p->out, "Usage: .filectrl %s %s\n", - zCmd, aCtrl[iCtrl].zUsage); - rc = 1; - }else if( isOk==1 ){ - char zBuf[100]; - sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes); - sqlite3_fprintf(p->out, "%s\n", zBuf); - } - }else - - if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){ - ShellState data; - int doStats = 0; - memcpy(&data, p, sizeof(data)); - data.showHeader = 0; - data.cMode = data.mode = MODE_Semi; - if( nArg==2 && optionMatch(azArg[1], "indent") ){ - data.cMode = data.mode = MODE_Pretty; - nArg = 1; - } - if( nArg!=1 ){ - eputz("Usage: .fullschema ?--indent?\n"); - rc = 1; - goto meta_command_exit; - } - open_db(p, 0); - rc = sqlite3_exec(p->db, - "SELECT sql FROM" - " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" - " FROM sqlite_schema UNION ALL" - " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) " - "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " - "ORDER BY x", - callback, &data, 0 - ); - if( rc==SQLITE_OK ){ - sqlite3_stmt *pStmt; - rc = sqlite3_prepare_v2(p->db, - "SELECT rowid FROM sqlite_schema" - " WHERE name GLOB 'sqlite_stat[134]'", - -1, &pStmt, 0); - if( rc==SQLITE_OK ){ - doStats = sqlite3_step(pStmt)==SQLITE_ROW; - sqlite3_finalize(pStmt); - } - } - if( doStats==0 ){ - sqlite3_fputs("/* No STAT tables available */\n", p->out); - }else{ - sqlite3_fputs("ANALYZE sqlite_schema;\n", p->out); - data.cMode = data.mode = MODE_Insert; - data.zDestTable = "sqlite_stat1"; - shell_exec(&data, "SELECT * FROM sqlite_stat1", 0); - data.zDestTable = "sqlite_stat4"; - shell_exec(&data, "SELECT * FROM sqlite_stat4", 0); - sqlite3_fputs("ANALYZE sqlite_schema;\n", p->out); - } - }else - - if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){ - if( nArg==2 ){ - p->showHeader = booleanValue(azArg[1]); - p->shellFlgs |= SHFLG_HeaderSet; - }else{ - eputz("Usage: .headers on|off\n"); - rc = 1; - } - }else - - if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){ - if( nArg>=2 ){ - n = showHelp(p->out, azArg[1]); - if( n==0 ){ - sqlite3_fprintf(p->out, "Nothing matches '%s'\n", azArg[1]); - } - }else{ - showHelp(p->out, 0); - } - }else - -#ifndef SQLITE_SHELL_FIDDLE - if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){ - char *zTable = 0; /* Insert data into this table */ - char *zSchema = 0; /* Schema of zTable */ - char *zFile = 0; /* Name of file to extra content from */ - sqlite3_stmt *pStmt = NULL; /* A statement */ - int nCol; /* Number of columns in the table */ - i64 nByte; /* Number of bytes in an SQL string */ - int i, j; /* Loop counters */ - int needCommit; /* True to COMMIT or ROLLBACK at end */ - int nSep; /* Number of bytes in p->colSeparator[] */ - char *zSql = 0; /* An SQL statement */ - ImportCtx sCtx; /* Reader context */ - char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ - int eVerbose = 0; /* Larger for more console output */ - int nSkip = 0; /* Initial lines to skip */ - int useOutputMode = 1; /* Use output mode to determine separators */ - char *zCreate = 0; /* CREATE TABLE statement text */ - - failIfSafeMode(p, "cannot run .import in safe mode"); - memset(&sCtx, 0, sizeof(sCtx)); - if( p->mode==MODE_Ascii ){ - xRead = ascii_read_one_field; - }else{ - xRead = csv_read_one_field; - } - rc = 1; - for(i=1; iout, "ERROR: extra argument: \"%s\". Usage:\n",z); - showHelp(p->out, "import"); - goto meta_command_exit; - } - }else if( cli_strcmp(z,"-v")==0 ){ - eVerbose++; - }else if( cli_strcmp(z,"-schema")==0 && iout, "ERROR: unknown option: \"%s\". Usage:\n", z); - showHelp(p->out, "import"); - goto meta_command_exit; - } - } - if( zTable==0 ){ - sqlite3_fprintf(p->out, "ERROR: missing %s argument. Usage:\n", - zFile==0 ? "FILE" : "TABLE"); - showHelp(p->out, "import"); - goto meta_command_exit; - } - seenInterrupt = 0; - open_db(p, 0); - if( useOutputMode ){ - /* If neither the --csv or --ascii options are specified, then set - ** the column and row separator characters from the output mode. */ - nSep = strlen30(p->colSeparator); - if( nSep==0 ){ - eputz("Error: non-null column separator required for import\n"); - goto meta_command_exit; - } - if( nSep>1 ){ - eputz("Error: multi-character column separators not allowed" - " for import\n"); - goto meta_command_exit; - } - nSep = strlen30(p->rowSeparator); - if( nSep==0 ){ - eputz("Error: non-null row separator required for import\n"); - goto meta_command_exit; - } - if( nSep==2 && p->mode==MODE_Csv - && cli_strcmp(p->rowSeparator,SEP_CrLf)==0 - ){ - /* When importing CSV (only), if the row separator is set to the - ** default output row separator, change it to the default input - ** row separator. This avoids having to maintain different input - ** and output row separators. */ - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); - nSep = strlen30(p->rowSeparator); - } - if( nSep>1 ){ - eputz("Error: multi-character row separators not allowed" - " for import\n"); - goto meta_command_exit; - } - sCtx.cColSep = (u8)p->colSeparator[0]; - sCtx.cRowSep = (u8)p->rowSeparator[0]; - } - sCtx.zFile = zFile; - sCtx.nLine = 1; - if( sCtx.zFile[0]=='|' ){ -#ifdef SQLITE_OMIT_POPEN - eputz("Error: pipes are not supported in this OS\n"); - goto meta_command_exit; -#else - sCtx.in = sqlite3_popen(sCtx.zFile+1, "r"); - sCtx.zFile = ""; - sCtx.xCloser = pclose; -#endif - }else{ - sCtx.in = sqlite3_fopen(sCtx.zFile, "rb"); - sCtx.xCloser = fclose; - } - if( sCtx.in==0 ){ - sqlite3_fprintf(stderr,"Error: cannot open \"%s\"\n", zFile); - goto meta_command_exit; - } - if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){ - char zSep[2]; - zSep[1] = 0; - zSep[0] = sCtx.cColSep; - sqlite3_fputs("Column separator ", p->out); - output_c_string(p->out, zSep); - sqlite3_fputs(", row separator ", p->out); - zSep[0] = sCtx.cRowSep; - output_c_string(p->out, zSep); - sqlite3_fputs("\n", p->out); - } - sCtx.z = sqlite3_malloc64(120); - if( sCtx.z==0 ){ - import_cleanup(&sCtx); - shell_out_of_memory(); - } - /* Below, resources must be freed before exit. */ - while( (nSkip--)>0 ){ - while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){} - } - import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ - if( sqlite3_table_column_metadata(p->db, zSchema, zTable,0,0,0,0,0,0) ){ - /* Table does not exist. Create it. */ - sqlite3 *dbCols = 0; - char *zRenames = 0; - char *zColDefs; - zCreate = sqlite3_mprintf("CREATE TABLE \"%w\".\"%w\"", - zSchema ? zSchema : "main", zTable); - while( xRead(&sCtx) ){ - zAutoColumn(sCtx.z, &dbCols, 0); - if( sCtx.cTerm!=sCtx.cColSep ) break; - } - zColDefs = zAutoColumn(0, &dbCols, &zRenames); - if( zRenames!=0 ){ - sqlite3_fprintf((stdin_is_interactive && p->in==stdin)? p->out : stderr, - "Columns renamed during .import %s due to duplicates:\n" - "%s\n", sCtx.zFile, zRenames); - sqlite3_free(zRenames); - } - assert(dbCols==0); - if( zColDefs==0 ){ - sqlite3_fprintf(stderr,"%s: empty file\n", sCtx.zFile); - import_cleanup(&sCtx); - rc = 1; - sqlite3_free(zCreate); - goto meta_command_exit; - } - zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs); - if( zCreate==0 ){ - import_cleanup(&sCtx); - shell_out_of_memory(); - } - if( eVerbose>=1 ){ - sqlite3_fprintf(p->out, "%s\n", zCreate); - } - rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); - if( rc ){ - sqlite3_fprintf(stderr, - "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db)); - } - sqlite3_free(zCreate); - zCreate = 0; - if( rc ){ - import_cleanup(&sCtx); - rc = 1; - goto meta_command_exit; - } - } - zSql = sqlite3_mprintf("SELECT count(*) FROM pragma_table_info(%Q,%Q);", - zTable, zSchema); - if( zSql==0 ){ - import_cleanup(&sCtx); - shell_out_of_memory(); - } - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - zSql = 0; - if( rc ){ - if (pStmt) sqlite3_finalize(pStmt); - shellDatabaseError(p->db); - import_cleanup(&sCtx); - rc = 1; - goto meta_command_exit; - } - if( sqlite3_step(pStmt)==SQLITE_ROW ){ - nCol = sqlite3_column_int(pStmt, 0); - }else{ - nCol = 0; - } - sqlite3_finalize(pStmt); - pStmt = 0; - if( nCol==0 ) return 0; /* no columns, no error */ - - nByte = 64 /* space for "INSERT INTO", "VALUES(", ")\0" */ - + (zSchema ? strlen(zSchema)*2 + 2: 0) /* Quoted schema name */ - + strlen(zTable)*2 + 2 /* Quoted table name */ - + nCol*2; /* Space for ",?" for each column */ - zSql = sqlite3_malloc64( nByte ); - if( zSql==0 ){ - import_cleanup(&sCtx); - shell_out_of_memory(); - } - if( zSchema ){ - sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\".\"%w\" VALUES(?", - zSchema, zTable); - }else{ - sqlite3_snprintf(nByte, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); - } - j = strlen30(zSql); - for(i=1; i=2 ){ - sqlite3_fprintf(p->out, "Insert using: %s\n", zSql); - } - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - zSql = 0; - if( rc ){ - shellDatabaseError(p->db); - if (pStmt) sqlite3_finalize(pStmt); - import_cleanup(&sCtx); - rc = 1; - goto meta_command_exit; - } - needCommit = sqlite3_get_autocommit(p->db); - if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); - do{ - int startLine = sCtx.nLine; - for(i=0; imode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; - /* - ** For CSV mode, per RFC 4180, accept EOF in lieu of final - ** record terminator but only for last field of multi-field row. - ** (If there are too few fields, it's not valid CSV anyway.) - */ - if( z==0 && (xRead==csv_read_one_field) && i==nCol-1 && i>0 ){ - z = ""; - } - sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); - if( i=nCol ){ - sqlite3_step(pStmt); - rc = sqlite3_reset(pStmt); - if( rc!=SQLITE_OK ){ - sqlite3_fprintf(stderr,"%s:%d: INSERT failed: %s\n", - sCtx.zFile, startLine, sqlite3_errmsg(p->db)); - sCtx.nErr++; - }else{ - sCtx.nRow++; - } - } - }while( sCtx.cTerm!=EOF ); - - import_cleanup(&sCtx); - sqlite3_finalize(pStmt); - if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); - if( eVerbose>0 ){ - sqlite3_fprintf(p->out, - "Added %d rows with %d errors using %d lines of input\n", - sCtx.nRow, sCtx.nErr, sCtx.nLine-1); - } - }else -#endif /* !defined(SQLITE_SHELL_FIDDLE) */ - -#ifndef SQLITE_UNTESTABLE - if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){ - char *zSql; - char *zCollist = 0; - sqlite3_stmt *pStmt; - int tnum = 0; - int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */ - int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */ - int i; - if( !ShellHasFlag(p,SHFLG_TestingMode) ){ - sqlite3_fprintf(stderr,".%s unavailable without --unsafe-testing\n", - "imposter"); - rc = 1; - goto meta_command_exit; - } - if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){ - eputz("Usage: .imposter INDEX IMPOSTER\n" - " .imposter off\n"); - /* Also allowed, but not documented: - ** - ** .imposter TABLE IMPOSTER - ** - ** where TABLE is a WITHOUT ROWID table. In that case, the - ** imposter is another WITHOUT ROWID table with the columns in - ** storage order. */ - rc = 1; - goto meta_command_exit; - } - open_db(p, 0); - if( nArg==2 ){ - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); - goto meta_command_exit; - } - zSql = sqlite3_mprintf( - "SELECT rootpage, 0 FROM sqlite_schema" - " WHERE name='%q' AND type='index'" - "UNION ALL " - "SELECT rootpage, 1 FROM sqlite_schema" - " WHERE name='%q' AND type='table'" - " AND sql LIKE '%%without%%rowid%%'", - azArg[1], azArg[1] - ); - sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( sqlite3_step(pStmt)==SQLITE_ROW ){ - tnum = sqlite3_column_int(pStmt, 0); - isWO = sqlite3_column_int(pStmt, 1); - } - sqlite3_finalize(pStmt); - zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]); - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - i = 0; - while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ - char zLabel[20]; - const char *zCol = (const char*)sqlite3_column_text(pStmt,2); - i++; - if( zCol==0 ){ - if( sqlite3_column_int(pStmt,1)==-1 ){ - zCol = "_ROWID_"; - }else{ - sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i); - zCol = zLabel; - } - } - if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){ - lenPK = (int)strlen(zCollist); - } - if( zCollist==0 ){ - zCollist = sqlite3_mprintf("\"%w\"", zCol); - }else{ - zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol); - } - } - sqlite3_finalize(pStmt); - if( i==0 || tnum==0 ){ - sqlite3_fprintf(stderr,"no such index: \"%s\"\n", azArg[1]); - rc = 1; - sqlite3_free(zCollist); - goto meta_command_exit; - } - if( lenPK==0 ) lenPK = 100000; - zSql = sqlite3_mprintf( - "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID", - azArg[2], zCollist, lenPK, zCollist); - sqlite3_free(zCollist); - rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); - if( rc==SQLITE_OK ){ - rc = sqlite3_exec(p->db, zSql, 0, 0, 0); - sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); - if( rc ){ - sqlite3_fprintf(stderr, - "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); - }else{ - sqlite3_fprintf(stdout, "%s;\n", zSql); - sqlite3_fprintf(stdout, - "WARNING: writing to an imposter table will corrupt" - " the \"%s\" %s!\n", azArg[1], isWO ? "table" : "index"); - } - }else{ - sqlite3_fprintf(stderr,"SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc); - rc = 1; - } - sqlite3_free(zSql); - }else -#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */ - - if( c=='i' && cli_strncmp(azArg[0], "intck", n)==0 ){ - i64 iArg = 0; - if( nArg==2 ){ - iArg = integerValue(azArg[1]); - if( iArg==0 ) iArg = -1; - } - if( (nArg!=1 && nArg!=2) || iArg<0 ){ - sqlite3_fprintf(stderr,"%s","Usage: .intck STEPS_PER_UNLOCK\n"); - rc = 1; - goto meta_command_exit; - } - open_db(p, 0); - rc = intckDatabaseCmd(p, iArg); - }else - -#ifdef SQLITE_ENABLE_IOTRACE - if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){ - SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); - if( iotrace && iotrace!=stdout ) fclose(iotrace); - iotrace = 0; - if( nArg<2 ){ - sqlite3IoTrace = 0; - }else if( cli_strcmp(azArg[1], "-")==0 ){ - sqlite3IoTrace = iotracePrintf; - iotrace = stdout; - }else{ - iotrace = sqlite3_fopen(azArg[1], "w"); - if( iotrace==0 ){ - sqlite3_fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); - sqlite3IoTrace = 0; - rc = 1; - }else{ - sqlite3IoTrace = iotracePrintf; - } - } - }else -#endif - - if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){ - static const struct { - const char *zLimitName; /* Name of a limit */ - int limitCode; /* Integer code for that limit */ - } aLimit[] = { - { "length", SQLITE_LIMIT_LENGTH }, - { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, - { "column", SQLITE_LIMIT_COLUMN }, - { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, - { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, - { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, - { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, - { "attached", SQLITE_LIMIT_ATTACHED }, - { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, - { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, - { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, - { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, - }; - int i, n2; - open_db(p, 0); - if( nArg==1 ){ - for(i=0; idb, aLimit[i].limitCode, -1)); - } - }else if( nArg>3 ){ - eputz("Usage: .limit NAME ?NEW-VALUE?\n"); - rc = 1; - goto meta_command_exit; - }else{ - int iLimit = -1; - n2 = strlen30(azArg[1]); - for(i=0; idb, aLimit[iLimit].limitCode, - (int)integerValue(azArg[2])); - } - sqlite3_fprintf(stdout, "%20s %d\n", aLimit[iLimit].zLimitName, - sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); - } - }else - - if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){ - open_db(p, 0); - lintDotCommand(p, azArg, nArg); - }else - -#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE) - if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){ - const char *zFile, *zProc; - char *zErrMsg = 0; - failIfSafeMode(p, "cannot run .load in safe mode"); - if( nArg<2 || azArg[1][0]==0 ){ - /* Must have a non-empty FILE. (Will not load self.) */ - eputz("Usage: .load FILE ?ENTRYPOINT?\n"); - rc = 1; - goto meta_command_exit; - } - zFile = azArg[1]; - zProc = nArg>=3 ? azArg[2] : 0; - open_db(p, 0); - rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); - if( rc!=SQLITE_OK ){ - shellEmitError(zErrMsg); - sqlite3_free(zErrMsg); - rc = 1; - } - }else -#endif - - if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){ - if( nArg!=2 ){ - eputz("Usage: .log FILENAME\n"); - rc = 1; - }else{ - const char *zFile = azArg[1]; - if( p->bSafeMode - && cli_strcmp(zFile,"on")!=0 - && cli_strcmp(zFile,"off")!=0 - ){ - sputz(stdout, "cannot set .log to anything other" - " than \"on\" or \"off\"\n"); - zFile = "off"; - } - output_file_close(p->pLog); - if( cli_strcmp(zFile,"on")==0 ) zFile = "stdout"; - p->pLog = output_file_open(zFile); - } - }else - - if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){ - const char *zMode = 0; - const char *zTabname = 0; - int i, n2; - ColModeOpts cmOpts = ColModeOpts_default; - for(i=1; imode==MODE_Column - || (p->mode>=MODE_Markdown && p->mode<=MODE_Box) - ){ - sqlite3_fprintf(p->out, - "current output mode: %s --wrap %d --wordwrap %s --%squote\n", - modeDescr[p->mode], p->cmOpts.iWrap, - p->cmOpts.bWordWrap ? "on" : "off", - p->cmOpts.bQuote ? "" : "no"); - }else{ - sqlite3_fprintf(p->out, - "current output mode: %s\n", modeDescr[p->mode]); - } - zMode = modeDescr[p->mode]; - } - n2 = strlen30(zMode); - if( cli_strncmp(zMode,"lines",n2)==0 ){ - p->mode = MODE_Line; - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); - }else if( cli_strncmp(zMode,"columns",n2)==0 ){ - p->mode = MODE_Column; - if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){ - p->showHeader = 1; - } - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); - p->cmOpts = cmOpts; - }else if( cli_strncmp(zMode,"list",n2)==0 ){ - p->mode = MODE_List; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); - }else if( cli_strncmp(zMode,"html",n2)==0 ){ - p->mode = MODE_Html; - }else if( cli_strncmp(zMode,"tcl",n2)==0 ){ - p->mode = MODE_Tcl; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); - }else if( cli_strncmp(zMode,"csv",n2)==0 ){ - p->mode = MODE_Csv; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); - }else if( cli_strncmp(zMode,"tabs",n2)==0 ){ - p->mode = MODE_List; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); - }else if( cli_strncmp(zMode,"insert",n2)==0 ){ - p->mode = MODE_Insert; - set_table_name(p, zTabname ? zTabname : "table"); - }else if( cli_strncmp(zMode,"quote",n2)==0 ){ - p->mode = MODE_Quote; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); - }else if( cli_strncmp(zMode,"ascii",n2)==0 ){ - p->mode = MODE_Ascii; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); - }else if( cli_strncmp(zMode,"markdown",n2)==0 ){ - p->mode = MODE_Markdown; - p->cmOpts = cmOpts; - }else if( cli_strncmp(zMode,"table",n2)==0 ){ - p->mode = MODE_Table; - p->cmOpts = cmOpts; - }else if( cli_strncmp(zMode,"box",n2)==0 ){ - p->mode = MODE_Box; - p->cmOpts = cmOpts; - }else if( cli_strncmp(zMode,"count",n2)==0 ){ - p->mode = MODE_Count; - }else if( cli_strncmp(zMode,"off",n2)==0 ){ - p->mode = MODE_Off; - }else if( cli_strncmp(zMode,"json",n2)==0 ){ - p->mode = MODE_Json; - }else{ - eputz("Error: mode should be one of: " - "ascii box column csv html insert json line list markdown " - "qbox quote table tabs tcl\n"); - rc = 1; - } - p->cMode = p->mode; - }else - -#ifndef SQLITE_SHELL_FIDDLE - if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){ - if( nArg!=2 ){ - eputz("Usage: .nonce NONCE\n"); - rc = 1; - }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){ - sqlite3_fprintf(stderr,"line %d: incorrect nonce: \"%s\"\n", - p->lineno, azArg[1]); - exit(1); - }else{ - p->bSafeMode = 0; - return 0; /* Return immediately to bypass the safe mode reset - ** at the end of this procedure */ - } - }else -#endif /* !defined(SQLITE_SHELL_FIDDLE) */ - - if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){ - if( nArg==2 ){ - sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, - "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); - }else{ - eputz("Usage: .nullvalue STRING\n"); - rc = 1; - } - }else - - if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){ - const char *zFN = 0; /* Pointer to constant filename */ - char *zNewFilename = 0; /* Name of the database file to open */ - int iName = 1; /* Index in azArg[] of the filename */ - int newFlag = 0; /* True to delete file before opening */ - int openMode = SHELL_OPEN_UNSPEC; - - /* Check for command-line arguments */ - for(iName=1; iNameopenFlags |= SQLITE_OPEN_NOFOLLOW; -#ifndef SQLITE_OMIT_DESERIALIZE - }else if( optionMatch(z, "deserialize") ){ - openMode = SHELL_OPEN_DESERIALIZE; - }else if( optionMatch(z, "hexdb") ){ - openMode = SHELL_OPEN_HEXDB; - }else if( optionMatch(z, "maxsize") && iName+1szMax = integerValue(azArg[++iName]); -#endif /* SQLITE_OMIT_DESERIALIZE */ - }else -#endif /* !SQLITE_SHELL_FIDDLE */ - if( z[0]=='-' ){ - sqlite3_fprintf(stderr,"unknown option: %s\n", z); - rc = 1; - goto meta_command_exit; - }else if( zFN ){ - sqlite3_fprintf(stderr,"extra argument: \"%s\"\n", z); - rc = 1; - goto meta_command_exit; - }else{ - zFN = z; - } - } - - /* Close the existing database */ - session_close_all(p, -1); - close_db(p->db); - p->db = 0; - p->pAuxDb->zDbFilename = 0; - sqlite3_free(p->pAuxDb->zFreeOnClose); - p->pAuxDb->zFreeOnClose = 0; - p->openMode = openMode; - p->openFlags = 0; - p->szMax = 0; - - /* If a filename is specified, try to open it first */ - if( zFN || p->openMode==SHELL_OPEN_HEXDB ){ - if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN); -#ifndef SQLITE_SHELL_FIDDLE - if( p->bSafeMode - && p->openMode!=SHELL_OPEN_HEXDB - && zFN - && cli_strcmp(zFN,":memory:")!=0 - ){ - failIfSafeMode(p, "cannot open disk-based database files in safe mode"); - } -#else - /* WASM mode has its own sandboxed pseudo-filesystem. */ -#endif - if( zFN ){ - zNewFilename = sqlite3_mprintf("%s", zFN); - shell_check_oom(zNewFilename); - }else{ - zNewFilename = 0; - } - p->pAuxDb->zDbFilename = zNewFilename; - open_db(p, OPEN_DB_KEEPALIVE); - if( p->db==0 ){ - sqlite3_fprintf(stderr,"Error: cannot open '%s'\n", zNewFilename); - sqlite3_free(zNewFilename); - }else{ - p->pAuxDb->zFreeOnClose = zNewFilename; - } - } - if( p->db==0 ){ - /* As a fall-back open a TEMP database */ - p->pAuxDb->zDbFilename = 0; - open_db(p, 0); - } - }else - -#ifndef SQLITE_SHELL_FIDDLE - if( (c=='o' - && (cli_strncmp(azArg[0], "output", n)==0 - || cli_strncmp(azArg[0], "once", n)==0)) - || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0) - || (c=='w' && n==3 && cli_strcmp(azArg[0],"www")==0) - ){ - char *zFile = 0; - int i; - int eMode = 0; - int bOnce = 0; /* 0: .output, 1: .once, 2: .excel/.www */ - int bPlain = 0; /* --plain option */ - static const char *zBomUtf8 = "\357\273\277"; - const char *zBom = 0; - - failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); - if( c=='e' ){ - eMode = 'x'; - bOnce = 2; - }else if( c=='w' ){ - eMode = 'w'; - bOnce = 2; - }else if( cli_strncmp(azArg[0],"once",n)==0 ){ - bOnce = 1; - } - for(i=1; iout, - "ERROR: unknown option: \"%s\". Usage:\n", azArg[i]); - showHelp(p->out, azArg[0]); - rc = 1; - goto meta_command_exit; - } - }else if( zFile==0 && eMode==0 ){ - zFile = sqlite3_mprintf("%s", z); - if( zFile && zFile[0]=='|' ){ - while( i+1out, - "ERROR: extra parameter: \"%s\". Usage:\n", azArg[i]); - showHelp(p->out, azArg[0]); - rc = 1; - sqlite3_free(zFile); - goto meta_command_exit; - } - } - if( zFile==0 ){ - zFile = sqlite3_mprintf("stdout"); - } - if( bOnce ){ - p->outCount = 2; - }else{ - p->outCount = 0; - } - output_reset(p); -#ifndef SQLITE_NOHAVE_SYSTEM - if( eMode=='e' || eMode=='x' || eMode=='w' ){ - p->doXdgOpen = 1; - outputModePush(p); - if( eMode=='x' ){ - /* spreadsheet mode. Output as CSV. */ - newTempFile(p, "csv"); - ShellClearFlag(p, SHFLG_Echo); - p->mode = MODE_Csv; - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); -#ifdef _WIN32 - zBom = zBomUtf8; /* Always include the BOM on Windows, as Excel does - ** not work without it. */ -#endif - }else if( eMode=='w' ){ - /* web-browser mode. */ - newTempFile(p, "html"); - if( !bPlain ) p->mode = MODE_Www; - }else{ - /* text editor mode */ - newTempFile(p, "txt"); - } - sqlite3_free(zFile); - zFile = sqlite3_mprintf("%s", p->zTempFile); - } -#endif /* SQLITE_NOHAVE_SYSTEM */ - shell_check_oom(zFile); - if( zFile[0]=='|' ){ -#ifdef SQLITE_OMIT_POPEN - eputz("Error: pipes are not supported in this OS\n"); - rc = 1; - output_redir(p, stdout); -#else - FILE *pfPipe = sqlite3_popen(zFile + 1, "w"); - if( pfPipe==0 ){ - sqlite3_fprintf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); - rc = 1; - }else{ - output_redir(p, pfPipe); - if( zBom ) sqlite3_fputs(zBom, pfPipe); - sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); - } -#endif - }else{ - FILE *pfFile = output_file_open(zFile); - if( pfFile==0 ){ - if( cli_strcmp(zFile,"off")!=0 ){ - sqlite3_fprintf(stderr,"Error: cannot write to \"%s\"\n", zFile); - } - rc = 1; - } else { - output_redir(p, pfFile); - if( zBom ) sqlite3_fputs(zBom, pfFile); - if( bPlain && eMode=='w' ){ - sqlite3_fputs( - "\n\n\n", - pfFile - ); - } - sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); - } - } - sqlite3_free(zFile); - }else -#endif /* !defined(SQLITE_SHELL_FIDDLE) */ - - if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){ - open_db(p,0); - if( nArg<=1 ) goto parameter_syntax_error; - - /* .parameter clear - ** Clear all bind parameters by dropping the TEMP table that holds them. - */ - if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){ - sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", - 0, 0, 0); - }else - - /* .parameter list - ** List all bind parameters. - */ - if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){ - sqlite3_stmt *pStmt = 0; - int rx; - int len = 0; - rx = sqlite3_prepare_v2(p->db, - "SELECT max(length(key)) " - "FROM temp.sqlite_parameters;", -1, &pStmt, 0); - if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ - len = sqlite3_column_int(pStmt, 0); - if( len>40 ) len = 40; - } - sqlite3_finalize(pStmt); - pStmt = 0; - if( len ){ - rx = sqlite3_prepare_v2(p->db, - "SELECT key, quote(value) " - "FROM temp.sqlite_parameters;", -1, &pStmt, 0); - while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ - sqlite3_fprintf(p->out, - "%-*s %s\n", len, sqlite3_column_text(pStmt,0), - sqlite3_column_text(pStmt,1)); - } - sqlite3_finalize(pStmt); - } - }else - - /* .parameter init - ** Make sure the TEMP table used to hold bind parameters exists. - ** Create it if necessary. - */ - if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){ - bind_table_init(p); - }else - - /* .parameter set NAME VALUE - ** Set or reset a bind parameter. NAME should be the full parameter - ** name exactly as it appears in the query. (ex: $abc, @def). The - ** VALUE can be in either SQL literal notation, or if not it will be - ** understood to be a text string. - */ - if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){ - int rx; - char *zSql; - sqlite3_stmt *pStmt; - const char *zKey = azArg[2]; - const char *zValue = azArg[3]; - bind_table_init(p); - zSql = sqlite3_mprintf( - "REPLACE INTO temp.sqlite_parameters(key,value)" - "VALUES(%Q,%s);", zKey, zValue); - shell_check_oom(zSql); - pStmt = 0; - rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( rx!=SQLITE_OK ){ - sqlite3_finalize(pStmt); - pStmt = 0; - zSql = sqlite3_mprintf( - "REPLACE INTO temp.sqlite_parameters(key,value)" - "VALUES(%Q,%Q);", zKey, zValue); - shell_check_oom(zSql); - rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( rx!=SQLITE_OK ){ - sqlite3_fprintf(p->out, "Error: %s\n", sqlite3_errmsg(p->db)); - sqlite3_finalize(pStmt); - pStmt = 0; - rc = 1; - } - } - sqlite3_step(pStmt); - sqlite3_finalize(pStmt); - }else - - /* .parameter unset NAME - ** Remove the NAME binding from the parameter binding table, if it - ** exists. - */ - if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){ - char *zSql = sqlite3_mprintf( - "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]); - shell_check_oom(zSql); - sqlite3_exec(p->db, zSql, 0, 0, 0); - sqlite3_free(zSql); - }else - /* If no command name matches, show a syntax error */ - parameter_syntax_error: - showHelp(p->out, "parameter"); - }else - - if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){ - int i; - for(i=1; i<nArg; i++){ - if( i>1 ) sqlite3_fputs(" ", p->out); - sqlite3_fputs(azArg[i], p->out); - } - sqlite3_fputs("\n", p->out); - }else - -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){ - int i; - int nn = 0; - p->flgProgress = 0; - p->mxProgress = 0; - p->nProgress = 0; - for(i=1; i<nArg; i++){ - const char *z = azArg[i]; - if( z[0]=='-' ){ - z++; - if( z[0]=='-' ) z++; - if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){ - p->flgProgress |= SHELL_PROGRESS_QUIET; - continue; - } - if( cli_strcmp(z,"reset")==0 ){ - p->flgProgress |= SHELL_PROGRESS_RESET; - continue; - } - if( cli_strcmp(z,"once")==0 ){ - p->flgProgress |= SHELL_PROGRESS_ONCE; - continue; - } - if( cli_strcmp(z,"limit")==0 ){ - if( i+1>=nArg ){ - eputz("Error: missing argument on --limit\n"); - rc = 1; - goto meta_command_exit; - }else{ - p->mxProgress = (int)integerValue(azArg[++i]); - } - continue; - } - sqlite3_fprintf(stderr,"Error: unknown option: \"%s\"\n", azArg[i]); - rc = 1; - goto meta_command_exit; - }else{ - nn = (int)integerValue(z); - } - } - open_db(p, 0); - sqlite3_progress_handler(p->db, nn, progress_handler, p); - }else -#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ - - if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){ - if( nArg >= 2) { - shell_strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); - } - if( nArg >= 3) { - shell_strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); - } - }else - -#ifndef SQLITE_SHELL_FIDDLE - if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){ - rc = 2; - }else -#endif - -#ifndef SQLITE_SHELL_FIDDLE - if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){ - FILE *inSaved = p->in; - int savedLineno = p->lineno; - failIfSafeMode(p, "cannot run .read in safe mode"); - if( nArg!=2 ){ - eputz("Usage: .read FILE\n"); - rc = 1; - goto meta_command_exit; - } - if( azArg[1][0]=='|' ){ -#ifdef SQLITE_OMIT_POPEN - eputz("Error: pipes are not supported in this OS\n"); - rc = 1; -#else - p->in = sqlite3_popen(azArg[1]+1, "r"); - if( p->in==0 ){ - sqlite3_fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); - rc = 1; - }else{ - rc = process_input(p); - pclose(p->in); - } -#endif - }else if( (p->in = openChrSource(azArg[1]))==0 ){ - sqlite3_fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); - rc = 1; - }else{ - rc = process_input(p); - fclose(p->in); - } - p->in = inSaved; - p->lineno = savedLineno; - }else -#endif /* !defined(SQLITE_SHELL_FIDDLE) */ - -#ifndef SQLITE_SHELL_FIDDLE - if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){ - const char *zSrcFile; - const char *zDb; - sqlite3 *pSrc; - sqlite3_backup *pBackup; - int nTimeout = 0; - - failIfSafeMode(p, "cannot run .restore in safe mode"); - if( nArg==2 ){ - zSrcFile = azArg[1]; - zDb = "main"; - }else if( nArg==3 ){ - zSrcFile = azArg[2]; - zDb = azArg[1]; - }else{ - eputz("Usage: .restore ?DB? FILE\n"); - rc = 1; - goto meta_command_exit; - } - rc = sqlite3_open(zSrcFile, &pSrc); - if( rc!=SQLITE_OK ){ - sqlite3_fprintf(stderr,"Error: cannot open \"%s\"\n", zSrcFile); - close_db(pSrc); - return 1; - } - open_db(p, 0); - pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); - if( pBackup==0 ){ - shellDatabaseError(p->db); - close_db(pSrc); - return 1; - } - while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK - || rc==SQLITE_BUSY ){ - if( rc==SQLITE_BUSY ){ - if( nTimeout++ >= 3 ) break; - sqlite3_sleep(100); - } - } - sqlite3_backup_finish(pBackup); - if( rc==SQLITE_DONE ){ - rc = 0; - }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ - eputz("Error: source database is busy\n"); - rc = 1; - }else{ - shellDatabaseError(p->db); - rc = 1; - } - close_db(pSrc); - }else -#endif /* !defined(SQLITE_SHELL_FIDDLE) */ - - if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){ - if( nArg==2 ){ - if( cli_strcmp(azArg[1], "vm")==0 ){ - p->scanstatsOn = 3; - }else - if( cli_strcmp(azArg[1], "est")==0 ){ - p->scanstatsOn = 2; - }else{ - p->scanstatsOn = (u8)booleanValue(azArg[1]); - } - open_db(p, 0); - sqlite3_db_config( - p->db, SQLITE_DBCONFIG_STMT_SCANSTATUS, p->scanstatsOn, (int*)0 - ); -#if !defined(SQLITE_ENABLE_STMT_SCANSTATUS) - eputz("Warning: .scanstats not available in this build.\n"); -#elif !defined(SQLITE_ENABLE_BYTECODE_VTAB) - if( p->scanstatsOn==3 ){ - eputz("Warning: \".scanstats vm\" not available in this build.\n"); - } -#endif - }else{ - eputz("Usage: .scanstats on|off|est\n"); - rc = 1; - } - }else - - if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){ - ShellText sSelect; - ShellState data; - char *zErrMsg = 0; - const char *zDiv = "("; - const char *zName = 0; - int iSchema = 0; - int bDebug = 0; - int bNoSystemTabs = 0; - int ii; - - open_db(p, 0); - memcpy(&data, p, sizeof(data)); - data.showHeader = 0; - data.cMode = data.mode = MODE_Semi; - initText(&sSelect); - for(ii=1; ii<nArg; ii++){ - if( optionMatch(azArg[ii],"indent") ){ - data.cMode = data.mode = MODE_Pretty; - }else if( optionMatch(azArg[ii],"debug") ){ - bDebug = 1; - }else if( optionMatch(azArg[ii],"nosys") ){ - bNoSystemTabs = 1; - }else if( azArg[ii][0]=='-' ){ - sqlite3_fprintf(stderr,"Unknown option: \"%s\"\n", azArg[ii]); - rc = 1; - goto meta_command_exit; - }else if( zName==0 ){ - zName = azArg[ii]; - }else{ - eputz("Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n"); - rc = 1; - goto meta_command_exit; - } - } - if( zName!=0 ){ - int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0 - || sqlite3_strlike(zName, "sqlite_schema", '\\')==0 - || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 - || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0; - if( isSchema ){ - char *new_argv[2], *new_colv[2]; - new_argv[0] = sqlite3_mprintf( - "CREATE TABLE %s (\n" - " type text,\n" - " name text,\n" - " tbl_name text,\n" - " rootpage integer,\n" - " sql text\n" - ")", zName); - shell_check_oom(new_argv[0]); - new_argv[1] = 0; - new_colv[0] = "sql"; - new_colv[1] = 0; - callback(&data, 1, new_argv, new_colv); - sqlite3_free(new_argv[0]); - } - } - if( zDiv ){ - sqlite3_stmt *pStmt = 0; - rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", - -1, &pStmt, 0); - if( rc ){ - shellDatabaseError(p->db); - sqlite3_finalize(pStmt); - rc = 1; - goto meta_command_exit; - } - appendText(&sSelect, "SELECT sql FROM", 0); - iSchema = 0; - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - const char *zDb = (const char*)sqlite3_column_text(pStmt, 0); - char zScNum[30]; - sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema); - appendText(&sSelect, zDiv, 0); - zDiv = " UNION ALL "; - appendText(&sSelect, "SELECT shell_add_schema(sql,", 0); - if( sqlite3_stricmp(zDb, "main")!=0 ){ - appendText(&sSelect, zDb, '\''); - }else{ - appendText(&sSelect, "NULL", 0); - } - appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0); - appendText(&sSelect, zScNum, 0); - appendText(&sSelect, " AS snum, ", 0); - appendText(&sSelect, zDb, '\''); - appendText(&sSelect, " AS sname FROM ", 0); - appendText(&sSelect, zDb, quoteChar(zDb)); - appendText(&sSelect, ".sqlite_schema", 0); - } - sqlite3_finalize(pStmt); -#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS - if( zName ){ - appendText(&sSelect, - " UNION ALL SELECT shell_module_schema(name)," - " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", - 0); - } -#endif - appendText(&sSelect, ") WHERE ", 0); - if( zName ){ - char *zQarg = sqlite3_mprintf("%Q", zName); - int bGlob; - shell_check_oom(zQarg); - bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 || - strchr(zName, '[') != 0; - if( strchr(zName, '.') ){ - appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0); - }else{ - appendText(&sSelect, "lower(tbl_name)", 0); - } - appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0); - appendText(&sSelect, zQarg, 0); - if( !bGlob ){ - appendText(&sSelect, " ESCAPE '\\' ", 0); - } - appendText(&sSelect, " AND ", 0); - sqlite3_free(zQarg); - } - if( bNoSystemTabs ){ - appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0); - } - appendText(&sSelect, "sql IS NOT NULL" - " ORDER BY snum, rowid", 0); - if( bDebug ){ - sqlite3_fprintf(p->out, "SQL: %s;\n", sSelect.z); - }else{ - rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); - } - freeText(&sSelect); - } - if( zErrMsg ){ - shellEmitError(zErrMsg); - sqlite3_free(zErrMsg); - rc = 1; - }else if( rc != SQLITE_OK ){ - eputz("Error: querying schema information\n"); - rc = 1; - }else{ - rc = 0; - } - }else - - if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0) - || (c=='t' && n==9 && cli_strncmp(azArg[0], "treetrace", n)==0) - ){ - unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff; - sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x); - }else - -#if defined(SQLITE_ENABLE_SESSION) - if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){ - struct AuxDb *pAuxDb = p->pAuxDb; - OpenSession *pSession = &pAuxDb->aSession[0]; - char **azCmd = &azArg[1]; - int iSes = 0; - int nCmd = nArg - 1; - int i; - if( nArg<=1 ) goto session_syntax_error; - open_db(p, 0); - if( nArg>=3 ){ - for(iSes=0; iSes<pAuxDb->nSession; iSes++){ - if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break; - } - if( iSes<pAuxDb->nSession ){ - pSession = &pAuxDb->aSession[iSes]; - azCmd++; - nCmd--; - }else{ - pSession = &pAuxDb->aSession[0]; - iSes = 0; - } - } - - /* .session attach TABLE - ** Invoke the sqlite3session_attach() interface to attach a particular - ** table so that it is never filtered. - */ - if( cli_strcmp(azCmd[0],"attach")==0 ){ - if( nCmd!=2 ) goto session_syntax_error; - if( pSession->p==0 ){ - session_not_open: - eputz("ERROR: No sessions are open\n"); - }else{ - rc = sqlite3session_attach(pSession->p, azCmd[1]); - if( rc ){ - sqlite3_fprintf(stderr, - "ERROR: sqlite3session_attach() returns %d\n",rc); - rc = 0; - } - } - }else - - /* .session changeset FILE - ** .session patchset FILE - ** Write a changeset or patchset into a file. The file is overwritten. - */ - if( cli_strcmp(azCmd[0],"changeset")==0 - || cli_strcmp(azCmd[0],"patchset")==0 - ){ - FILE *out = 0; - failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]); - if( nCmd!=2 ) goto session_syntax_error; - if( pSession->p==0 ) goto session_not_open; - out = sqlite3_fopen(azCmd[1], "wb"); - if( out==0 ){ - sqlite3_fprintf(stderr,"ERROR: cannot open \"%s\" for writing\n", - azCmd[1]); - }else{ - int szChng; - void *pChng; - if( azCmd[0][0]=='c' ){ - rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); - }else{ - rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); - } - if( rc ){ - sqlite3_fprintf(stdout, "Error: error code %d\n", rc); - rc = 0; - } - if( pChng - && fwrite(pChng, szChng, 1, out)!=1 ){ - sqlite3_fprintf(stderr, - "ERROR: Failed to write entire %d-byte output\n", szChng); - } - sqlite3_free(pChng); - fclose(out); - } - }else - - /* .session close - ** Close the identified session - */ - if( cli_strcmp(azCmd[0], "close")==0 ){ - if( nCmd!=1 ) goto session_syntax_error; - if( pAuxDb->nSession ){ - session_close(pSession); - pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession]; - } - }else - - /* .session enable ?BOOLEAN? - ** Query or set the enable flag - */ - if( cli_strcmp(azCmd[0], "enable")==0 ){ - int ii; - if( nCmd>2 ) goto session_syntax_error; - ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); - if( pAuxDb->nSession ){ - ii = sqlite3session_enable(pSession->p, ii); - sqlite3_fprintf(p->out, - "session %s enable flag = %d\n", pSession->zName, ii); - } - }else - - /* .session filter GLOB .... - ** Set a list of GLOB patterns of table names to be excluded. - */ - if( cli_strcmp(azCmd[0], "filter")==0 ){ - int ii, nByte; - if( nCmd<2 ) goto session_syntax_error; - if( pAuxDb->nSession ){ - for(ii=0; ii<pSession->nFilter; ii++){ - sqlite3_free(pSession->azFilter[ii]); - } - sqlite3_free(pSession->azFilter); - nByte = sizeof(pSession->azFilter[0])*(nCmd-1); - pSession->azFilter = sqlite3_malloc( nByte ); - shell_check_oom( pSession->azFilter ); - for(ii=1; ii<nCmd; ii++){ - char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); - shell_check_oom(x); - } - pSession->nFilter = ii-1; - } - }else - - /* .session indirect ?BOOLEAN? - ** Query or set the indirect flag - */ - if( cli_strcmp(azCmd[0], "indirect")==0 ){ - int ii; - if( nCmd>2 ) goto session_syntax_error; - ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); - if( pAuxDb->nSession ){ - ii = sqlite3session_indirect(pSession->p, ii); - sqlite3_fprintf(p->out, - "session %s indirect flag = %d\n", pSession->zName, ii); - } - }else - - /* .session isempty - ** Determine if the session is empty - */ - if( cli_strcmp(azCmd[0], "isempty")==0 ){ - int ii; - if( nCmd!=1 ) goto session_syntax_error; - if( pAuxDb->nSession ){ - ii = sqlite3session_isempty(pSession->p); - sqlite3_fprintf(p->out, - "session %s isempty flag = %d\n", pSession->zName, ii); - } - }else - - /* .session list - ** List all currently open sessions - */ - if( cli_strcmp(azCmd[0],"list")==0 ){ - for(i=0; i<pAuxDb->nSession; i++){ - sqlite3_fprintf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName); - } - }else - - /* .session open DB NAME - ** Open a new session called NAME on the attached database DB. - ** DB is normally "main". - */ - if( cli_strcmp(azCmd[0],"open")==0 ){ - char *zName; - if( nCmd!=3 ) goto session_syntax_error; - zName = azCmd[2]; - if( zName[0]==0 ) goto session_syntax_error; - for(i=0; i<pAuxDb->nSession; i++){ - if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){ - sqlite3_fprintf(stderr,"Session \"%s\" already exists\n", zName); - goto meta_command_exit; - } - } - if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){ - sqlite3_fprintf(stderr, - "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession)); - goto meta_command_exit; - } - pSession = &pAuxDb->aSession[pAuxDb->nSession]; - rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); - if( rc ){ - sqlite3_fprintf(stderr,"Cannot open session: error code=%d\n", rc); - rc = 0; - goto meta_command_exit; - } - pSession->nFilter = 0; - sqlite3session_table_filter(pSession->p, session_filter, pSession); - pAuxDb->nSession++; - pSession->zName = sqlite3_mprintf("%s", zName); - shell_check_oom(pSession->zName); - }else - /* If no command name matches, show a syntax error */ - session_syntax_error: - showHelp(p->out, "session"); - }else -#endif - -#ifdef SQLITE_DEBUG - /* Undocumented commands for internal testing. Subject to change - ** without notice. */ - if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){ - if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){ - int i, v; - for(i=1; i<nArg; i++){ - v = booleanValue(azArg[i]); - sqlite3_fprintf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); - } - } - if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){ - int i; sqlite3_int64 v; - for(i=1; i<nArg; i++){ - char zBuf[200]; - v = integerValue(azArg[i]); - sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v); - sqlite3_fputs(zBuf, p->out); - } - } - }else -#endif - - if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){ - int bIsInit = 0; /* True to initialize the SELFTEST table */ - int bVerbose = 0; /* Verbose output */ - int bSelftestExists; /* True if SELFTEST already exists */ - int i, k; /* Loop counters */ - int nTest = 0; /* Number of tests runs */ - int nErr = 0; /* Number of errors seen */ - ShellText str; /* Answer for a query */ - sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */ - - open_db(p,0); - for(i=1; i<nArg; i++){ - const char *z = azArg[i]; - if( z[0]=='-' && z[1]=='-' ) z++; - if( cli_strcmp(z,"-init")==0 ){ - bIsInit = 1; - }else - if( cli_strcmp(z,"-v")==0 ){ - bVerbose++; - }else - { - sqlite3_fprintf(stderr, - "Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]); - sqlite3_fputs("Should be one of: --init -v\n", stderr); - rc = 1; - goto meta_command_exit; - } - } - if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) - != SQLITE_OK ){ - bSelftestExists = 0; - }else{ - bSelftestExists = 1; - } - if( bIsInit ){ - createSelftestTable(p); - bSelftestExists = 1; - } - initText(&str); - appendText(&str, "x", 0); - for(k=bSelftestExists; k>=0; k--){ - if( k==1 ){ - rc = sqlite3_prepare_v2(p->db, - "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno", - -1, &pStmt, 0); - }else{ - rc = sqlite3_prepare_v2(p->db, - "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," - " (1,'run','PRAGMA integrity_check','ok')", - -1, &pStmt, 0); - } - if( rc ){ - eputz("Error querying the selftest table\n"); - rc = 1; - sqlite3_finalize(pStmt); - goto meta_command_exit; - } - for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){ - int tno = sqlite3_column_int(pStmt, 0); - const char *zOp = (const char*)sqlite3_column_text(pStmt, 1); - const char *zSql = (const char*)sqlite3_column_text(pStmt, 2); - const char *zAns = (const char*)sqlite3_column_text(pStmt, 3); - - if( zOp==0 ) continue; - if( zSql==0 ) continue; - if( zAns==0 ) continue; - k = 0; - if( bVerbose>0 ){ - sqlite3_fprintf(stdout, "%d: %s %s\n", tno, zOp, zSql); - } - if( cli_strcmp(zOp,"memo")==0 ){ - sqlite3_fprintf(p->out, "%s\n", zSql); - }else - if( cli_strcmp(zOp,"run")==0 ){ - char *zErrMsg = 0; - str.n = 0; - str.z[0] = 0; - rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); - nTest++; - if( bVerbose ){ - sqlite3_fprintf(p->out, "Result: %s\n", str.z); - } - if( rc || zErrMsg ){ - nErr++; - rc = 1; - sqlite3_fprintf(p->out, "%d: error-code-%d: %s\n", tno, rc,zErrMsg); - sqlite3_free(zErrMsg); - }else if( cli_strcmp(zAns,str.z)!=0 ){ - nErr++; - rc = 1; - sqlite3_fprintf(p->out, "%d: Expected: [%s]\n", tno, zAns); - sqlite3_fprintf(p->out, "%d: Got: [%s]\n", tno, str.z); - } - } - else{ - sqlite3_fprintf(stderr, - "Unknown operation \"%s\" on selftest line %d\n", zOp, tno); - rc = 1; - break; - } - } /* End loop over rows of content from SELFTEST */ - sqlite3_finalize(pStmt); - } /* End loop over k */ - freeText(&str); - sqlite3_fprintf(p->out, "%d errors out of %d tests\n", nErr, nTest); - }else - - if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){ - if( nArg<2 || nArg>3 ){ - eputz("Usage: .separator COL ?ROW?\n"); - rc = 1; - } - if( nArg>=2 ){ - sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, - "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); - } - if( nArg>=3 ){ - sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, - "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); - } - }else - - if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){ - const char *zLike = 0; /* Which table to checksum. 0 means everything */ - int i; /* Loop counter */ - int bSchema = 0; /* Also hash the schema */ - int bSeparate = 0; /* Hash each table separately */ - int iSize = 224; /* Hash algorithm to use */ - int bDebug = 0; /* Only show the query that would have run */ - sqlite3_stmt *pStmt; /* For querying tables names */ - char *zSql; /* SQL to be run */ - char *zSep; /* Separator */ - ShellText sSql; /* Complete SQL for the query to run the hash */ - ShellText sQuery; /* Set of queries used to read all content */ - open_db(p, 0); - for(i=1; i<nArg; i++){ - const char *z = azArg[i]; - if( z[0]=='-' ){ - z++; - if( z[0]=='-' ) z++; - if( cli_strcmp(z,"schema")==0 ){ - bSchema = 1; - }else - if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0 - || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0 - ){ - iSize = atoi(&z[5]); - }else - if( cli_strcmp(z,"debug")==0 ){ - bDebug = 1; - }else - { - sqlite3_fprintf(stderr, - "Unknown option \"%s\" on \"%s\"\n", azArg[i], azArg[0]); - showHelp(p->out, azArg[0]); - rc = 1; - goto meta_command_exit; - } - }else if( zLike ){ - eputz("Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); - rc = 1; - goto meta_command_exit; - }else{ - zLike = z; - bSeparate = 1; - if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1; - } - } - if( bSchema ){ - zSql = "SELECT lower(name) as tname FROM sqlite_schema" - " WHERE type='table' AND coalesce(rootpage,0)>1" - " UNION ALL SELECT 'sqlite_schema'" - " ORDER BY 1 collate nocase"; - }else{ - zSql = "SELECT lower(name) as tname FROM sqlite_schema" - " WHERE type='table' AND coalesce(rootpage,0)>1" - " AND name NOT LIKE 'sqlite_%'" - " ORDER BY 1 collate nocase"; - } - sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - initText(&sQuery); - initText(&sSql); - appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0); - zSep = "VALUES("; - while( SQLITE_ROW==sqlite3_step(pStmt) ){ - const char *zTab = (const char*)sqlite3_column_text(pStmt,0); - if( zTab==0 ) continue; - if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue; - if( cli_strncmp(zTab, "sqlite_",7)!=0 ){ - appendText(&sQuery,"SELECT * FROM ", 0); - appendText(&sQuery,zTab,'"'); - appendText(&sQuery," NOT INDEXED;", 0); - }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){ - appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema" - " ORDER BY name;", 0); - }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){ - appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence" - " ORDER BY name;", 0); - }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){ - appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1" - " ORDER BY tbl,idx;", 0); - }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){ - appendText(&sQuery, "SELECT * FROM ", 0); - appendText(&sQuery, zTab, 0); - appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0); - } - appendText(&sSql, zSep, 0); - appendText(&sSql, sQuery.z, '\''); - sQuery.n = 0; - appendText(&sSql, ",", 0); - appendText(&sSql, zTab, '\''); - zSep = "),("; - } - sqlite3_finalize(pStmt); - if( bSeparate ){ - zSql = sqlite3_mprintf( - "%s))" - " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label" - " FROM [sha3sum$query]", - sSql.z, iSize); - }else{ - zSql = sqlite3_mprintf( - "%s))" - " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash" - " FROM [sha3sum$query]", - sSql.z, iSize); - } - shell_check_oom(zSql); - freeText(&sQuery); - freeText(&sSql); - if( bDebug ){ - sqlite3_fprintf(p->out, "%s\n", zSql); - }else{ - shell_exec(p, zSql, 0); - } -#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && !defined(SQLITE_OMIT_VIRTUALTABLE) - { - int lrc; - char *zRevText = /* Query for reversible to-blob-to-text check */ - "SELECT lower(name) as tname FROM sqlite_schema\n" - "WHERE type='table' AND coalesce(rootpage,0)>1\n" - "AND name NOT LIKE 'sqlite_%%'%s\n" - "ORDER BY 1 collate nocase"; - zRevText = sqlite3_mprintf(zRevText, zLike? " AND name LIKE $tspec" : ""); - zRevText = sqlite3_mprintf( - /* lower-case query is first run, producing upper-case query. */ - "with tabcols as materialized(\n" - "select tname, cname\n" - "from (" - " select printf('\"%%w\"',ss.tname) as tname," - " printf('\"%%w\"',ti.name) as cname\n" - " from (%z) ss\n inner join pragma_table_info(tname) ti))\n" - "select 'SELECT total(bad_text_count) AS bad_text_count\n" - "FROM ('||group_concat(query, ' UNION ALL ')||')' as btc_query\n" - " from (select 'SELECT COUNT(*) AS bad_text_count\n" - "FROM '||tname||' WHERE '\n" - "||group_concat('CAST(CAST('||cname||' AS BLOB) AS TEXT)<>'||cname\n" - "|| ' AND typeof('||cname||')=''text'' ',\n" - "' OR ') as query, tname from tabcols group by tname)" - , zRevText); - shell_check_oom(zRevText); - if( bDebug ) sqlite3_fprintf(p->out, "%s\n", zRevText); - lrc = sqlite3_prepare_v2(p->db, zRevText, -1, &pStmt, 0); - if( lrc!=SQLITE_OK ){ - /* assert(lrc==SQLITE_NOMEM); // might also be SQLITE_ERROR if the - ** user does cruel and unnatural things like ".limit expr_depth 0". */ - rc = 1; - }else{ - if( zLike ) sqlite3_bind_text(pStmt,1,zLike,-1,SQLITE_STATIC); - lrc = SQLITE_ROW==sqlite3_step(pStmt); - if( lrc ){ - const char *zGenQuery = (char*)sqlite3_column_text(pStmt,0); - sqlite3_stmt *pCheckStmt; - lrc = sqlite3_prepare_v2(p->db, zGenQuery, -1, &pCheckStmt, 0); - if( bDebug ) sqlite3_fprintf(p->out, "%s\n", zGenQuery); - if( lrc!=SQLITE_OK ){ - rc = 1; - }else{ - if( SQLITE_ROW==sqlite3_step(pCheckStmt) ){ - double countIrreversible = sqlite3_column_double(pCheckStmt, 0); - if( countIrreversible>0 ){ - int sz = (int)(countIrreversible + 0.5); - sqlite3_fprintf(stderr, - "Digest includes %d invalidly encoded text field%s.\n", - sz, (sz>1)? "s": ""); - } - } - sqlite3_finalize(pCheckStmt); - } - sqlite3_finalize(pStmt); - } - } - if( rc ) eputz(".sha3sum failed.\n"); - sqlite3_free(zRevText); - } -#endif /* !defined(*_OMIT_SCHEMA_PRAGMAS) && !defined(*_OMIT_VIRTUALTABLE) */ - sqlite3_free(zSql); - }else - -#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) - if( c=='s' - && (cli_strncmp(azArg[0], "shell", n)==0 - || cli_strncmp(azArg[0],"system",n)==0) - ){ - char *zCmd; - int i, x; - failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); - if( nArg<2 ){ - eputz("Usage: .system COMMAND\n"); - rc = 1; - goto meta_command_exit; - } - zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); - for(i=2; i<nArg && zCmd!=0; i++){ - zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"", - zCmd, azArg[i]); - } - /*consoleRestore();*/ - x = zCmd!=0 ? system(zCmd) : 1; - /*consoleRenewSetup();*/ - sqlite3_free(zCmd); - if( x ) sqlite3_fprintf(stderr,"System command returns %d\n", x); - }else -#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */ - - if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){ - static const char *azBool[] = { "off", "on", "trigger", "full"}; - const char *zOut; - int i; - if( nArg!=1 ){ - eputz("Usage: .show\n"); - rc = 1; - goto meta_command_exit; - } - sqlite3_fprintf(p->out, "%12.12s: %s\n","echo", - azBool[ShellHasFlag(p, SHFLG_Echo)]); - sqlite3_fprintf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); - sqlite3_fprintf(p->out, "%12.12s: %s\n","explain", - p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); - sqlite3_fprintf(p->out, "%12.12s: %s\n","headers", - azBool[p->showHeader!=0]); - if( p->mode==MODE_Column - || (p->mode>=MODE_Markdown && p->mode<=MODE_Box) - ){ - sqlite3_fprintf(p->out, - "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode", - modeDescr[p->mode], p->cmOpts.iWrap, - p->cmOpts.bWordWrap ? "on" : "off", - p->cmOpts.bQuote ? "" : "no"); - }else{ - sqlite3_fprintf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); - } - sqlite3_fprintf(p->out, "%12.12s: ", "nullvalue"); - output_c_string(p->out, p->nullValue); - sqlite3_fputs("\n", p->out); - sqlite3_fprintf(p->out, "%12.12s: %s\n","output", - strlen30(p->outfile) ? p->outfile : "stdout"); - sqlite3_fprintf(p->out, "%12.12s: ", "colseparator"); - output_c_string(p->out, p->colSeparator); - sqlite3_fputs("\n", p->out); - sqlite3_fprintf(p->out, "%12.12s: ", "rowseparator"); - output_c_string(p->out, p->rowSeparator); - sqlite3_fputs("\n", p->out); - switch( p->statsOn ){ - case 0: zOut = "off"; break; - default: zOut = "on"; break; - case 2: zOut = "stmt"; break; - case 3: zOut = "vmstep"; break; - } - sqlite3_fprintf(p->out, "%12.12s: %s\n","stats", zOut); - sqlite3_fprintf(p->out, "%12.12s: ", "width"); - for (i=0;i<p->nWidth;i++) { - sqlite3_fprintf(p->out, "%d ", p->colWidth[i]); - } - sqlite3_fputs("\n", p->out); - sqlite3_fprintf(p->out, "%12.12s: %s\n", "filename", - p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : ""); - }else - - if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){ - if( nArg==2 ){ - if( cli_strcmp(azArg[1],"stmt")==0 ){ - p->statsOn = 2; - }else if( cli_strcmp(azArg[1],"vmstep")==0 ){ - p->statsOn = 3; - }else{ - p->statsOn = (u8)booleanValue(azArg[1]); - } - }else if( nArg==1 ){ - display_stats(p->db, p, 0); - }else{ - eputz("Usage: .stats ?on|off|stmt|vmstep?\n"); - rc = 1; - } - }else - - if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0) - || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0 - || cli_strncmp(azArg[0], "indexes", n)==0) ) - ){ - sqlite3_stmt *pStmt; - char **azResult; - int nRow, nAlloc; - int ii; - ShellText s; - initText(&s); - open_db(p, 0); - rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); - if( rc ){ - sqlite3_finalize(pStmt); - return shellDatabaseError(p->db); - } - - if( nArg>2 && c=='i' ){ - /* It is an historical accident that the .indexes command shows an error - ** when called with the wrong number of arguments whereas the .tables - ** command does not. */ - eputz("Usage: .indexes ?LIKE-PATTERN?\n"); - rc = 1; - sqlite3_finalize(pStmt); - goto meta_command_exit; - } - for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){ - const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); - if( zDbName==0 ) continue; - if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0); - if( sqlite3_stricmp(zDbName, "main")==0 ){ - appendText(&s, "SELECT name FROM ", 0); - }else{ - appendText(&s, "SELECT ", 0); - appendText(&s, zDbName, '\''); - appendText(&s, "||'.'||name FROM ", 0); - } - appendText(&s, zDbName, '"'); - appendText(&s, ".sqlite_schema ", 0); - if( c=='t' ){ - appendText(&s," WHERE type IN ('table','view')" - " AND name NOT LIKE 'sqlite_%'" - " AND name LIKE ?1", 0); - }else{ - appendText(&s," WHERE type='index'" - " AND tbl_name LIKE ?1", 0); - } - } - rc = sqlite3_finalize(pStmt); - if( rc==SQLITE_OK ){ - appendText(&s, " ORDER BY 1", 0); - rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); - } - freeText(&s); - if( rc ) return shellDatabaseError(p->db); - - /* Run the SQL statement prepared by the above block. Store the results - ** as an array of nul-terminated strings in azResult[]. */ - nRow = nAlloc = 0; - azResult = 0; - if( nArg>1 ){ - sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); - }else{ - sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); - } - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - if( nRow>=nAlloc ){ - char **azNew; - int n2 = nAlloc*2 + 10; - azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2); - shell_check_oom(azNew); - nAlloc = n2; - azResult = azNew; - } - azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); - shell_check_oom(azResult[nRow]); - nRow++; - } - if( sqlite3_finalize(pStmt)!=SQLITE_OK ){ - rc = shellDatabaseError(p->db); - } - - /* Pretty-print the contents of array azResult[] to the output */ - if( rc==0 && nRow>0 ){ - int len, maxlen = 0; - int i, j; - int nPrintCol, nPrintRow; - for(i=0; i<nRow; i++){ - len = strlen30(azResult[i]); - if( len>maxlen ) maxlen = len; - } - nPrintCol = 80/(maxlen+2); - if( nPrintCol<1 ) nPrintCol = 1; - nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; - for(i=0; i<nPrintRow; i++){ - for(j=i; j<nRow; j+=nPrintRow){ - char *zSp = j<nPrintRow ? "" : " "; - sqlite3_fprintf(p->out, - "%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:""); - } - sqlite3_fputs("\n", p->out); - } - } - - for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]); - sqlite3_free(azResult); - }else - -#ifndef SQLITE_SHELL_FIDDLE - /* Begin redirecting output to the file "testcase-out.txt" */ - if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){ - output_reset(p); - p->out = output_file_open("testcase-out.txt"); - if( p->out==0 ){ - eputz("Error: cannot open 'testcase-out.txt'\n"); - } - if( nArg>=2 ){ - sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); - }else{ - sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); - } - }else -#endif /* !defined(SQLITE_SHELL_FIDDLE) */ - -#ifndef SQLITE_UNTESTABLE - if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){ - static const struct { - const char *zCtrlName; /* Name of a test-control option */ - int ctrlCode; /* Integer code for that option */ - int unSafe; /* Not valid unless --unsafe-testing */ - const char *zUsage; /* Usage notes */ - } aCtrl[] = { - {"always", SQLITE_TESTCTRL_ALWAYS, 1, "BOOLEAN" }, - {"assert", SQLITE_TESTCTRL_ASSERT, 1, "BOOLEAN" }, - /*{"benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/ - /*{"bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/ - {"byteorder", SQLITE_TESTCTRL_BYTEORDER, 0, "" }, - {"extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" }, - {"fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"args..." }, - {"fk_no_action", SQLITE_TESTCTRL_FK_NO_ACTION, 0, "BOOLEAN" }, - {"imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"}, - {"internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" }, - {"json_selfcheck", SQLITE_TESTCTRL_JSON_SELFCHECK ,0,"BOOLEAN" }, - {"localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" }, - {"never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" }, - {"optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK ..."}, -#ifdef YYCOVERAGE - {"parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" }, -#endif - {"pending_byte", SQLITE_TESTCTRL_PENDING_BYTE,1, "OFFSET " }, - {"prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE,0, "" }, - {"prng_save", SQLITE_TESTCTRL_PRNG_SAVE, 0, "" }, - {"prng_seed", SQLITE_TESTCTRL_PRNG_SEED, 0, "SEED ?db?" }, - {"seek_count", SQLITE_TESTCTRL_SEEK_COUNT, 0, "" }, - {"sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX" }, - {"tune", SQLITE_TESTCTRL_TUNE, 1, "ID VALUE" }, - }; - int testctrl = -1; - int iCtrl = -1; - int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ - int isOk = 0; - int i, n2; - const char *zCmd = 0; - - open_db(p, 0); - zCmd = nArg>=2 ? azArg[1] : "help"; - - /* The argument can optionally begin with "-" or "--" */ - if( zCmd[0]=='-' && zCmd[1] ){ - zCmd++; - if( zCmd[0]=='-' && zCmd[1] ) zCmd++; - } - - /* --help lists all test-controls */ - if( cli_strcmp(zCmd,"help")==0 ){ - sqlite3_fputs("Available test-controls:\n", p->out); - for(i=0; i<ArraySize(aCtrl); i++){ - if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue; - sqlite3_fprintf(p->out, " .testctrl %s %s\n", - aCtrl[i].zCtrlName, aCtrl[i].zUsage); - } - rc = 1; - goto meta_command_exit; - } - - /* convert testctrl text option to value. allow any unique prefix - ** of the option name, or a numerical value. */ - n2 = strlen30(zCmd); - for(i=0; i<ArraySize(aCtrl); i++){ - if( aCtrl[i].unSafe && !ShellHasFlag(p,SHFLG_TestingMode) ) continue; - if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ - if( testctrl<0 ){ - testctrl = aCtrl[i].ctrlCode; - iCtrl = i; - }else{ - sqlite3_fprintf(stderr,"Error: ambiguous test-control: \"%s\"\n" - "Use \".testctrl --help\" for help\n", zCmd); - rc = 1; - goto meta_command_exit; - } - } - } - if( testctrl<0 ){ - sqlite3_fprintf(stderr,"Error: unknown test-control: %s\n" - "Use \".testctrl --help\" for help\n", zCmd); - }else{ - switch(testctrl){ - - /* Special processing for .testctrl opt MASK ... - ** Each MASK argument can be one of: - ** - ** +LABEL Enable the named optimization - ** - ** -LABEL Disable the named optimization - ** - ** INTEGER Mask of optimizations to disable - */ - case SQLITE_TESTCTRL_OPTIMIZATIONS: { - static const struct { - unsigned int mask; /* Mask for this optimization */ - unsigned int bDsply; /* Display this on output */ - const char *zLabel; /* Name of optimization */ - } aLabel[] = { - { 0x00000001, 1, "QueryFlattener" }, - { 0x00000001, 0, "Flatten" }, - { 0x00000002, 1, "WindowFunc" }, - { 0x00000004, 1, "GroupByOrder" }, - { 0x00000008, 1, "FactorOutConst" }, - { 0x00000010, 1, "DistinctOpt" }, - { 0x00000020, 1, "CoverIdxScan" }, - { 0x00000040, 1, "OrderByIdxJoin" }, - { 0x00000080, 1, "Transitive" }, - { 0x00000100, 1, "OmitNoopJoin" }, - { 0x00000200, 1, "CountOfView" }, - { 0x00000400, 1, "CurosrHints" }, - { 0x00000800, 1, "Stat4" }, - { 0x00001000, 1, "PushDown" }, - { 0x00002000, 1, "SimplifyJoin" }, - { 0x00004000, 1, "SkipScan" }, - { 0x00008000, 1, "PropagateConst" }, - { 0x00010000, 1, "MinMaxOpt" }, - { 0x00020000, 1, "SeekScan" }, - { 0x00040000, 1, "OmitOrderBy" }, - { 0x00080000, 1, "BloomFilter" }, - { 0x00100000, 1, "BloomPulldown" }, - { 0x00200000, 1, "BalancedMerge" }, - { 0x00400000, 1, "ReleaseReg" }, - { 0x00800000, 1, "FlttnUnionAll" }, - { 0x01000000, 1, "IndexedEXpr" }, - { 0x02000000, 1, "Coroutines" }, - { 0x04000000, 1, "NullUnusedCols" }, - { 0x08000000, 1, "OnePass" }, - { 0x10000000, 1, "OrderBySubq" }, - { 0xffffffff, 0, "All" }, - }; - unsigned int curOpt; - unsigned int newOpt; - int ii; - sqlite3_test_control(SQLITE_TESTCTRL_GETOPT, p->db, &curOpt); - newOpt = curOpt; - for(ii=2; ii<nArg; ii++){ - const char *z = azArg[ii]; - int useLabel = 0; - const char *zLabel = 0; - if( (z[0]=='+'|| z[0]=='-') && !IsDigit(z[1]) ){ - useLabel = z[0]; - zLabel = &z[1]; - }else if( !IsDigit(z[0]) && z[0]!=0 && !IsDigit(z[1]) ){ - useLabel = '+'; - zLabel = z; - }else{ - newOpt = (unsigned int)strtol(z,0,0); - } - if( useLabel ){ - int jj; - for(jj=0; jj<ArraySize(aLabel); jj++){ - if( sqlite3_stricmp(zLabel, aLabel[jj].zLabel)==0 ) break; - } - if( jj>=ArraySize(aLabel) ){ - sqlite3_fprintf(stderr, - "Error: no such optimization: \"%s\"\n", zLabel); - sqlite3_fputs("Should be one of:", stderr); - for(jj=0; jj<ArraySize(aLabel); jj++){ - sqlite3_fprintf(stderr," %s", aLabel[jj].zLabel); - } - sqlite3_fputs("\n", stderr); - rc = 1; - goto meta_command_exit; - } - if( useLabel=='+' ){ - newOpt &= ~aLabel[jj].mask; - }else{ - newOpt |= aLabel[jj].mask; - } - } - } - if( curOpt!=newOpt ){ - sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,p->db,newOpt); - }else if( nArg<3 ){ - curOpt = ~newOpt; - } - if( newOpt==0 ){ - sqlite3_fputs("+All\n", p->out); - }else if( newOpt==0xffffffff ){ - sqlite3_fputs("-All\n", p->out); - }else{ - int jj; - for(jj=0; jj<ArraySize(aLabel); jj++){ - unsigned int m = aLabel[jj].mask; - if( !aLabel[jj].bDsply ) continue; - if( (curOpt&m)!=(newOpt&m) ){ - sqlite3_fprintf(p->out, "%c%s\n", (newOpt & m)==0 ? '+' : '-', - aLabel[jj].zLabel); - } - } - } - rc2 = isOk = 3; - break; - } - - /* sqlite3_test_control(int, db, int) */ - case SQLITE_TESTCTRL_FK_NO_ACTION: - if( nArg==3 ){ - unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0); - rc2 = sqlite3_test_control(testctrl, p->db, opt); - isOk = 3; - } - break; - - /* sqlite3_test_control(int) */ - case SQLITE_TESTCTRL_PRNG_SAVE: - case SQLITE_TESTCTRL_PRNG_RESTORE: - case SQLITE_TESTCTRL_BYTEORDER: - if( nArg==2 ){ - rc2 = sqlite3_test_control(testctrl); - isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3; - } - break; - - /* sqlite3_test_control(int, uint) */ - case SQLITE_TESTCTRL_PENDING_BYTE: - if( nArg==3 ){ - unsigned int opt = (unsigned int)integerValue(azArg[2]); - rc2 = sqlite3_test_control(testctrl, opt); - isOk = 3; - } - break; - - /* sqlite3_test_control(int, int, sqlite3*) */ - case SQLITE_TESTCTRL_PRNG_SEED: - if( nArg==3 || nArg==4 ){ - int ii = (int)integerValue(azArg[2]); - sqlite3 *db; - if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){ - sqlite3_randomness(sizeof(ii),&ii); - sqlite3_fprintf(stdout, "-- random seed: %d\n", ii); - } - if( nArg==3 ){ - db = 0; - }else{ - db = p->db; - /* Make sure the schema has been loaded */ - sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0); - } - rc2 = sqlite3_test_control(testctrl, ii, db); - isOk = 3; - } - break; - - /* sqlite3_test_control(int, int) */ - case SQLITE_TESTCTRL_ASSERT: - case SQLITE_TESTCTRL_ALWAYS: - if( nArg==3 ){ - int opt = booleanValue(azArg[2]); - rc2 = sqlite3_test_control(testctrl, opt); - isOk = 1; - } - break; - - /* sqlite3_test_control(int, int) */ - case SQLITE_TESTCTRL_LOCALTIME_FAULT: - case SQLITE_TESTCTRL_NEVER_CORRUPT: - if( nArg==3 ){ - int opt = booleanValue(azArg[2]); - rc2 = sqlite3_test_control(testctrl, opt); - isOk = 3; - } - break; - - /* sqlite3_test_control(sqlite3*) */ - case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: - rc2 = sqlite3_test_control(testctrl, p->db); - isOk = 3; - break; - - case SQLITE_TESTCTRL_IMPOSTER: - if( nArg==5 ){ - rc2 = sqlite3_test_control(testctrl, p->db, - azArg[2], - integerValue(azArg[3]), - integerValue(azArg[4])); - isOk = 3; - } - break; - - case SQLITE_TESTCTRL_SEEK_COUNT: { - u64 x = 0; - rc2 = sqlite3_test_control(testctrl, p->db, &x); - sqlite3_fprintf(p->out, "%llu\n", x); - isOk = 3; - break; - } - -#ifdef YYCOVERAGE - case SQLITE_TESTCTRL_PARSER_COVERAGE: { - if( nArg==2 ){ - sqlite3_test_control(testctrl, p->out); - isOk = 3; - } - break; - } -#endif -#ifdef SQLITE_DEBUG - case SQLITE_TESTCTRL_TUNE: { - if( nArg==4 ){ - int id = (int)integerValue(azArg[2]); - int val = (int)integerValue(azArg[3]); - sqlite3_test_control(testctrl, id, &val); - isOk = 3; - }else if( nArg==3 ){ - int id = (int)integerValue(azArg[2]); - sqlite3_test_control(testctrl, -id, &rc2); - isOk = 1; - }else if( nArg==2 ){ - int id = 1; - while(1){ - int val = 0; - rc2 = sqlite3_test_control(testctrl, -id, &val); - if( rc2!=SQLITE_OK ) break; - if( id>1 ) sqlite3_fputs(" ", p->out); - sqlite3_fprintf(p->out, "%d: %d", id, val); - id++; - } - if( id>1 ) sqlite3_fputs("\n", p->out); - isOk = 3; - } - break; - } -#endif - case SQLITE_TESTCTRL_SORTER_MMAP: - if( nArg==3 ){ - int opt = (unsigned int)integerValue(azArg[2]); - rc2 = sqlite3_test_control(testctrl, p->db, opt); - isOk = 3; - } - break; - case SQLITE_TESTCTRL_JSON_SELFCHECK: - if( nArg==2 ){ - rc2 = -1; - isOk = 1; - }else{ - rc2 = booleanValue(azArg[2]); - isOk = 3; - } - sqlite3_test_control(testctrl, &rc2); - break; - case SQLITE_TESTCTRL_FAULT_INSTALL: { - int kk; - int bShowHelp = nArg<=2; - isOk = 3; - for(kk=2; kk<nArg; kk++){ - const char *z = azArg[kk]; - if( z[0]=='-' && z[1]=='-' ) z++; - if( cli_strcmp(z,"off")==0 ){ - sqlite3_test_control(testctrl, 0); - }else if( cli_strcmp(z,"on")==0 ){ - faultsim_state.iCnt = faultsim_state.nSkip; - if( faultsim_state.iErr==0 ) faultsim_state.iErr = 1; - faultsim_state.nHit = 0; - sqlite3_test_control(testctrl, faultsim_callback); - }else if( cli_strcmp(z,"reset")==0 ){ - faultsim_state.iCnt = faultsim_state.nSkip; - faultsim_state.nHit = 0; - sqlite3_test_control(testctrl, faultsim_callback); - }else if( cli_strcmp(z,"status")==0 ){ - sqlite3_fprintf(p->out, "faultsim.iId: %d\n", - faultsim_state.iId); - sqlite3_fprintf(p->out, "faultsim.iErr: %d\n", - faultsim_state.iErr); - sqlite3_fprintf(p->out, "faultsim.iCnt: %d\n", - faultsim_state.iCnt); - sqlite3_fprintf(p->out, "faultsim.nHit: %d\n", - faultsim_state.nHit); - sqlite3_fprintf(p->out, "faultsim.iInterval: %d\n", - faultsim_state.iInterval); - sqlite3_fprintf(p->out, "faultsim.eVerbose: %d\n", - faultsim_state.eVerbose); - sqlite3_fprintf(p->out, "faultsim.nRepeat: %d\n", - faultsim_state.nRepeat); - sqlite3_fprintf(p->out, "faultsim.nSkip: %d\n", - faultsim_state.nSkip); - }else if( cli_strcmp(z,"-v")==0 ){ - if( faultsim_state.eVerbose<2 ) faultsim_state.eVerbose++; - }else if( cli_strcmp(z,"-q")==0 ){ - if( faultsim_state.eVerbose>0 ) faultsim_state.eVerbose--; - }else if( cli_strcmp(z,"-id")==0 && kk+1<nArg ){ - faultsim_state.iId = atoi(azArg[++kk]); - }else if( cli_strcmp(z,"-errcode")==0 && kk+1<nArg ){ - faultsim_state.iErr = atoi(azArg[++kk]); - }else if( cli_strcmp(z,"-interval")==0 && kk+1<nArg ){ - faultsim_state.iInterval = atoi(azArg[++kk]); - }else if( cli_strcmp(z,"-repeat")==0 && kk+1<nArg ){ - faultsim_state.nRepeat = atoi(azArg[++kk]); - }else if( cli_strcmp(z,"-skip")==0 && kk+1<nArg ){ - faultsim_state.nSkip = atoi(azArg[++kk]); - }else if( cli_strcmp(z,"-?")==0 || sqlite3_strglob("*help*",z)==0){ - bShowHelp = 1; - }else{ - sqlite3_fprintf(stderr, - "Unrecognized fault_install argument: \"%s\"\n", - azArg[kk]); - rc = 1; - bShowHelp = 1; - break; - } - } - if( bShowHelp ){ - sqlite3_fputs( - "Usage: .testctrl fault_install ARGS\n" - "Possible arguments:\n" - " off Disable faultsim\n" - " on Activate faultsim\n" - " reset Reset the trigger counter\n" - " status Show current status\n" - " -v Increase verbosity\n" - " -q Decrease verbosity\n" - " --errcode N When triggered, return N as error code\n" - " --id ID Trigger only for the ID specified\n" - " --interval N Trigger only after every N-th call\n" - " --repeat N Turn off after N hits. 0 means never\n" - " --skip N Skip the first N encounters\n" - ,p->out - ); - } - break; - } - } - } - if( isOk==0 && iCtrl>=0 ){ - sqlite3_fprintf(p->out, - "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); - rc = 1; - }else if( isOk==1 ){ - sqlite3_fprintf(p->out, "%d\n", rc2); - }else if( isOk==2 ){ - sqlite3_fprintf(p->out, "0x%08x\n", rc2); - } - }else -#endif /* !defined(SQLITE_UNTESTABLE) */ - - if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){ - open_db(p, 0); - sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); - }else - - if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){ - if( nArg==2 ){ - enableTimer = booleanValue(azArg[1]); - if( enableTimer && !HAS_TIMER ){ - eputz("Error: timer not available on this system.\n"); - enableTimer = 0; - } - }else{ - eputz("Usage: .timer on|off\n"); - rc = 1; - } - }else - -#ifndef SQLITE_OMIT_TRACE - if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){ - int mType = 0; - int jj; - open_db(p, 0); - for(jj=1; jj<nArg; jj++){ - const char *z = azArg[jj]; - if( z[0]=='-' ){ - if( optionMatch(z, "expanded") ){ - p->eTraceType = SHELL_TRACE_EXPANDED; - } -#ifdef SQLITE_ENABLE_NORMALIZE - else if( optionMatch(z, "normalized") ){ - p->eTraceType = SHELL_TRACE_NORMALIZED; - } -#endif - else if( optionMatch(z, "plain") ){ - p->eTraceType = SHELL_TRACE_PLAIN; - } - else if( optionMatch(z, "profile") ){ - mType |= SQLITE_TRACE_PROFILE; - } - else if( optionMatch(z, "row") ){ - mType |= SQLITE_TRACE_ROW; - } - else if( optionMatch(z, "stmt") ){ - mType |= SQLITE_TRACE_STMT; - } - else if( optionMatch(z, "close") ){ - mType |= SQLITE_TRACE_CLOSE; - } - else { - sqlite3_fprintf(stderr,"Unknown option \"%s\" on \".trace\"\n", z); - rc = 1; - goto meta_command_exit; - } - }else{ - output_file_close(p->traceOut); - p->traceOut = output_file_open(z); - } - } - if( p->traceOut==0 ){ - sqlite3_trace_v2(p->db, 0, 0, 0); - }else{ - if( mType==0 ) mType = SQLITE_TRACE_STMT; - sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); - } - }else -#endif /* !defined(SQLITE_OMIT_TRACE) */ - -#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE) - if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){ - int ii; - int lenOpt; - char *zOpt; - if( nArg<2 ){ - eputz("Usage: .unmodule [--allexcept] NAME ...\n"); - rc = 1; - goto meta_command_exit; - } - open_db(p, 0); - zOpt = azArg[1]; - if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++; - lenOpt = (int)strlen(zOpt); - if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){ - assert( azArg[nArg]==0 ); - sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0); - }else{ - for(ii=1; ii<nArg; ii++){ - sqlite3_create_module(p->db, azArg[ii], 0, 0); - } - } - }else -#endif - -#if SQLITE_USER_AUTHENTICATION - if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){ - if( nArg<2 ){ - eputz("Usage: .user SUBCOMMAND ...\n"); - rc = 1; - goto meta_command_exit; - } - open_db(p, 0); - if( cli_strcmp(azArg[1],"login")==0 ){ - if( nArg!=4 ){ - eputz("Usage: .user login USER PASSWORD\n"); - rc = 1; - goto meta_command_exit; - } - rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], - strlen30(azArg[3])); - if( rc ){ - sqlite3_fprintf(stderr,"Authentication failed for user %s\n", azArg[2]); - rc = 1; - } - }else if( cli_strcmp(azArg[1],"add")==0 ){ - if( nArg!=5 ){ - eputz("Usage: .user add USER PASSWORD ISADMIN\n"); - rc = 1; - goto meta_command_exit; - } - rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), - booleanValue(azArg[4])); - if( rc ){ - sqlite3_fprintf(stderr,"User-Add failed: %d\n", rc); - rc = 1; - } - }else if( cli_strcmp(azArg[1],"edit")==0 ){ - if( nArg!=5 ){ - eputz("Usage: .user edit USER PASSWORD ISADMIN\n"); - rc = 1; - goto meta_command_exit; - } - rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), - booleanValue(azArg[4])); - if( rc ){ - sqlite3_fprintf(stderr,"User-Edit failed: %d\n", rc); - rc = 1; - } - }else if( cli_strcmp(azArg[1],"delete")==0 ){ - if( nArg!=3 ){ - eputz("Usage: .user delete USER\n"); - rc = 1; - goto meta_command_exit; - } - rc = sqlite3_user_delete(p->db, azArg[2]); - if( rc ){ - sqlite3_fprintf(stderr,"User-Delete failed: %d\n", rc); - rc = 1; - } - }else{ - eputz("Usage: .user login|add|edit|delete ...\n"); - rc = 1; - goto meta_command_exit; - } - }else -#endif /* SQLITE_USER_AUTHENTICATION */ - - if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){ - char *zPtrSz = sizeof(void*)==8 ? "64-bit" : "32-bit"; - sqlite3_fprintf(p->out, "SQLite %s %s\n" /*extra-version-info*/, - sqlite3_libversion(), sqlite3_sourceid()); -#if SQLITE_HAVE_ZLIB - sqlite3_fprintf(p->out, "zlib version %s\n", zlibVersion()); -#endif -#define CTIMEOPT_VAL_(opt) #opt -#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) -#if defined(__clang__) && defined(__clang_major__) - sqlite3_fprintf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." - CTIMEOPT_VAL(__clang_minor__) "." - CTIMEOPT_VAL(__clang_patchlevel__) " (%s)\n", zPtrSz); -#elif defined(_MSC_VER) - sqlite3_fprintf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) " (%s)\n", zPtrSz); -#elif defined(__GNUC__) && defined(__VERSION__) - sqlite3_fprintf(p->out, "gcc-" __VERSION__ " (%s)\n", zPtrSz); -#endif - }else - - if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){ - const char *zDbName = nArg==2 ? azArg[1] : "main"; - sqlite3_vfs *pVfs = 0; - if( p->db ){ - sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); - if( pVfs ){ - sqlite3_fprintf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); - sqlite3_fprintf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); - sqlite3_fprintf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); - sqlite3_fprintf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); - } - } - }else - - if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){ - sqlite3_vfs *pVfs; - sqlite3_vfs *pCurrent = 0; - if( p->db ){ - sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); - } - for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ - sqlite3_fprintf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, - pVfs==pCurrent ? " <--- CURRENT" : ""); - sqlite3_fprintf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); - sqlite3_fprintf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); - sqlite3_fprintf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); - if( pVfs->pNext ){ - sqlite3_fputs("-----------------------------------\n", p->out); - } - } - }else - - if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){ - const char *zDbName = nArg==2 ? azArg[1] : "main"; - char *zVfsName = 0; - if( p->db ){ - sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); - if( zVfsName ){ - sqlite3_fprintf(p->out, "%s\n", zVfsName); - sqlite3_free(zVfsName); - } - } - }else - - if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){ - unsigned int x = nArg>=2? (unsigned int)integerValue(azArg[1]) : 0xffffffff; - sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x); - }else - - if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){ - int j; - assert( nArg<=ArraySize(azArg) ); - p->nWidth = nArg-1; - p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2); - if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory(); - if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth]; - for(j=1; j<nArg; j++){ - p->colWidth[j-1] = (int)integerValue(azArg[j]); - } - }else - - { - sqlite3_fprintf(stderr,"Error: unknown command or invalid arguments: " - " \"%s\". Enter \".help\" for help\n", azArg[0]); - rc = 1; - } - -meta_command_exit: - if( p->outCount ){ - p->outCount--; - if( p->outCount==0 ) output_reset(p); - } - p->bSafeMode = p->bSafeModePersist; - return rc; -} - -/* Line scan result and intermediate states (supporting scan resumption) -*/ -#ifndef CHAR_BIT -# define CHAR_BIT 8 -#endif -typedef enum { - QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT, - QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT, - QSS_Start = 0 -} QuickScanState; -#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask)) -#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start) -#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start) -#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark) -#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi) - -/* -** Scan line for classification to guide shell's handling. -** The scan is resumable for subsequent lines when prior -** return values are passed as the 2nd argument. -*/ -static QuickScanState quickscan(char *zLine, QuickScanState qss, - SCAN_TRACKER_REFTYPE pst){ - char cin; - char cWait = (char)qss; /* intentional narrowing loss */ - if( cWait==0 ){ - PlainScan: - assert( cWait==0 ); - while( (cin = *zLine++)!=0 ){ - if( IsSpace(cin) ) - continue; - switch (cin){ - case '-': - if( *zLine!='-' ) - break; - while((cin = *++zLine)!=0 ) - if( cin=='\n') - goto PlainScan; - return qss; - case ';': - qss |= QSS_EndingSemi; - continue; - case '/': - if( *zLine=='*' ){ - ++zLine; - cWait = '*'; - CONTINUE_PROMPT_AWAITS(pst, "/*"); - qss = QSS_SETV(qss, cWait); - goto TermScan; - } - break; - case '[': - cin = ']'; - deliberate_fall_through; - case '`': case '\'': case '"': - cWait = cin; - qss = QSS_HasDark | cWait; - CONTINUE_PROMPT_AWAITC(pst, cin); - goto TermScan; - case '(': - CONTINUE_PAREN_INCR(pst, 1); - break; - case ')': - CONTINUE_PAREN_INCR(pst, -1); - break; - default: - break; - } - qss = (qss & ~QSS_EndingSemi) | QSS_HasDark; - } - }else{ - TermScan: - while( (cin = *zLine++)!=0 ){ - if( cin==cWait ){ - switch( cWait ){ - case '*': - if( *zLine != '/' ) - continue; - ++zLine; - cWait = 0; - CONTINUE_PROMPT_AWAITC(pst, 0); - qss = QSS_SETV(qss, 0); - goto PlainScan; - case '`': case '\'': case '"': - if(*zLine==cWait){ - /* Swallow doubled end-delimiter.*/ - ++zLine; - continue; - } - deliberate_fall_through; - case ']': - cWait = 0; - CONTINUE_PROMPT_AWAITC(pst, 0); - qss = QSS_SETV(qss, 0); - goto PlainScan; - default: assert(0); - } - } - } - } - return qss; -} - -/* -** Return TRUE if the line typed in is an SQL command terminator other -** than a semi-colon. The SQL Server style "go" command is understood -** as is the Oracle "/". -*/ -static int line_is_command_terminator(char *zLine){ - while( IsSpace(zLine[0]) ){ zLine++; }; - if( zLine[0]=='/' ) - zLine += 1; /* Oracle */ - else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' ) - zLine += 2; /* SQL Server */ - else - return 0; - return quickscan(zLine, QSS_Start, 0)==QSS_Start; -} - -/* -** The CLI needs a working sqlite3_complete() to work properly. So error -** out of the build if compiling with SQLITE_OMIT_COMPLETE. -*/ -#ifdef SQLITE_OMIT_COMPLETE -# error the CLI application is imcompatable with SQLITE_OMIT_COMPLETE. -#endif - -/* -** Return true if zSql is a complete SQL statement. Return false if it -** ends in the middle of a string literal or C-style comment. -*/ -static int line_is_complete(char *zSql, int nSql){ - int rc; - if( zSql==0 ) return 1; - zSql[nSql] = ';'; - zSql[nSql+1] = 0; - rc = sqlite3_complete(zSql); - zSql[nSql] = 0; - return rc; -} - -/* -** This function is called after processing each line of SQL in the -** runOneSqlLine() function. Its purpose is to detect scenarios where -** defensive mode should be automatically turned off. Specifically, when -** -** 1. The first line of input is "PRAGMA foreign_keys=OFF;", -** 2. The second line of input is "BEGIN TRANSACTION;", -** 3. The database is empty, and -** 4. The shell is not running in --safe mode. -** -** The implementation uses the ShellState.eRestoreState to maintain state: -** -** 0: Have not seen any SQL. -** 1: Have seen "PRAGMA foreign_keys=OFF;". -** 2-6: Currently running .dump transaction. If the "2" bit is set, -** disable DEFENSIVE when done. If "4" is set, disable DQS_DDL. -** 7: Nothing left to do. This function becomes a no-op. -*/ -static int doAutoDetectRestore(ShellState *p, const char *zSql){ - int rc = SQLITE_OK; - - if( p->eRestoreState<7 ){ - switch( p->eRestoreState ){ - case 0: { - const char *zExpect = "PRAGMA foreign_keys=OFF;"; - assert( strlen(zExpect)==24 ); - if( p->bSafeMode==0 - && strlen(zSql)>=24 - && memcmp(zSql, zExpect, 25)==0 - ){ - p->eRestoreState = 1; - }else{ - p->eRestoreState = 7; - } - break; - }; - - case 1: { - int bIsDump = 0; - const char *zExpect = "BEGIN TRANSACTION;"; - assert( strlen(zExpect)==18 ); - if( memcmp(zSql, zExpect, 19)==0 ){ - /* Now check if the database is empty. */ - const char *zQuery = "SELECT 1 FROM sqlite_schema LIMIT 1"; - sqlite3_stmt *pStmt = 0; - - bIsDump = 1; - shellPrepare(p->db, &rc, zQuery, &pStmt); - if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ - bIsDump = 0; - } - shellFinalize(&rc, pStmt); - } - if( bIsDump && rc==SQLITE_OK ){ - int bDefense = 0; - int bDqsDdl = 0; - sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &bDefense); - sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, -1, &bDqsDdl); - sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0); - sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 1, 0); - p->eRestoreState = (bDefense ? 2 : 0) + (bDqsDdl ? 4 : 0); - }else{ - p->eRestoreState = 7; - } - break; - } - - default: { - if( sqlite3_get_autocommit(p->db) ){ - if( (p->eRestoreState & 2) ){ - sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 1, 0); - } - if( (p->eRestoreState & 4) ){ - sqlite3_db_config(p->db, SQLITE_DBCONFIG_DQS_DDL, 0, 0); - } - p->eRestoreState = 7; - } - break; - } - } - } - - return rc; -} - -/* -** Run a single line of SQL. Return the number of errors. -*/ -static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){ - int rc; - char *zErrMsg = 0; - - open_db(p, 0); - if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql); - if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; - BEGIN_TIMER; - rc = shell_exec(p, zSql, &zErrMsg); - END_TIMER(p->out); - if( rc || zErrMsg ){ - char zPrefix[100]; - const char *zErrorTail; - const char *zErrorType; - if( zErrMsg==0 ){ - zErrorType = "Error"; - zErrorTail = sqlite3_errmsg(p->db); - }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){ - zErrorType = "Parse error"; - zErrorTail = &zErrMsg[12]; - }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){ - zErrorType = "Runtime error"; - zErrorTail = &zErrMsg[10]; - }else{ - zErrorType = "Error"; - zErrorTail = zErrMsg; - } - if( in!=0 || !stdin_is_interactive ){ - sqlite3_snprintf(sizeof(zPrefix), zPrefix, - "%s near line %d:", zErrorType, startline); - }else{ - sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType); - } - sqlite3_fprintf(stderr,"%s %s\n", zPrefix, zErrorTail); - sqlite3_free(zErrMsg); - zErrMsg = 0; - return 1; - }else if( ShellHasFlag(p, SHFLG_CountChanges) ){ - char zLineBuf[2000]; - sqlite3_snprintf(sizeof(zLineBuf), zLineBuf, - "changes: %lld total_changes: %lld", - sqlite3_changes64(p->db), sqlite3_total_changes64(p->db)); - sqlite3_fprintf(p->out, "%s\n", zLineBuf); - } - - if( doAutoDetectRestore(p, zSql) ) return 1; - return 0; -} - -static void echo_group_input(ShellState *p, const char *zDo){ - if( ShellHasFlag(p, SHFLG_Echo) ) sqlite3_fprintf(p->out, "%s\n", zDo); -} - -#ifdef SQLITE_SHELL_FIDDLE -/* -** Alternate one_input_line() impl for wasm mode. This is not in the primary -** impl because we need the global shellState and cannot access it from that -** function without moving lots of code around (creating a larger/messier diff). -*/ -static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ - /* Parse the next line from shellState.wasm.zInput. */ - const char *zBegin = shellState.wasm.zPos; - const char *z = zBegin; - char *zLine = 0; - i64 nZ = 0; - - UNUSED_PARAMETER(in); - UNUSED_PARAMETER(isContinuation); - if(!z || !*z){ - return 0; - } - while(*z && isspace(*z)) ++z; - zBegin = z; - for(; *z && '\n'!=*z; ++nZ, ++z){} - if(nZ>0 && '\r'==zBegin[nZ-1]){ - --nZ; - } - shellState.wasm.zPos = z; - zLine = realloc(zPrior, nZ+1); - shell_check_oom(zLine); - memcpy(zLine, zBegin, nZ); - zLine[nZ] = 0; - return zLine; -} -#endif /* SQLITE_SHELL_FIDDLE */ - -/* -** Read input from *in and process it. If *in==0 then input -** is interactive - the user is typing it it. Otherwise, input -** is coming from a file or device. A prompt is issued and history -** is saved only if input is interactive. An interrupt signal will -** cause this routine to exit immediately, unless input is interactive. -** -** Return the number of errors. -*/ -static int process_input(ShellState *p){ - char *zLine = 0; /* A single input line */ - char *zSql = 0; /* Accumulated SQL text */ - i64 nLine; /* Length of current line */ - i64 nSql = 0; /* Bytes of zSql[] used */ - i64 nAlloc = 0; /* Allocated zSql[] space */ - int rc; /* Error code */ - int errCnt = 0; /* Number of errors seen */ - i64 startline = 0; /* Line number for start of current input */ - QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */ - - if( p->inputNesting==MAX_INPUT_NESTING ){ - /* This will be more informative in a later version. */ - sqlite3_fprintf(stderr,"Input nesting limit (%d) reached at line %d." - " Check recursion.\n", MAX_INPUT_NESTING, p->lineno); - return 1; - } - ++p->inputNesting; - p->lineno = 0; - CONTINUE_PROMPT_RESET; - while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ - fflush(p->out); - zLine = one_input_line(p->in, zLine, nSql>0); - if( zLine==0 ){ - /* End of input */ - if( p->in==0 && stdin_is_interactive ) sqlite3_fputs("\n", p->out); - break; - } - if( seenInterrupt ){ - if( p->in!=0 ) break; - seenInterrupt = 0; - } - p->lineno++; - if( QSS_INPLAIN(qss) - && line_is_command_terminator(zLine) - && line_is_complete(zSql, nSql) ){ - memcpy(zLine,";",2); - } - qss = quickscan(zLine, qss, CONTINUE_PROMPT_PSTATE); - if( QSS_PLAINWHITE(qss) && nSql==0 ){ - /* Just swallow single-line whitespace */ - echo_group_input(p, zLine); - qss = QSS_Start; - continue; - } - if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){ - CONTINUE_PROMPT_RESET; - echo_group_input(p, zLine); - if( zLine[0]=='.' ){ - rc = do_meta_command(zLine, p); - if( rc==2 ){ /* exit requested */ - break; - }else if( rc ){ - errCnt++; - } - } - qss = QSS_Start; - continue; - } - /* No single-line dispositions remain; accumulate line(s). */ - nLine = strlen(zLine); - if( nSql+nLine+2>=nAlloc ){ - /* Grow buffer by half-again increments when big. */ - nAlloc = nSql+(nSql>>1)+nLine+100; - zSql = realloc(zSql, nAlloc); - shell_check_oom(zSql); - } - if( nSql==0 ){ - i64 i; - for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} - assert( nAlloc>0 && zSql!=0 ); - memcpy(zSql, zLine+i, nLine+1-i); - startline = p->lineno; - nSql = nLine-i; - }else{ - zSql[nSql++] = '\n'; - memcpy(zSql+nSql, zLine, nLine+1); - nSql += nLine; - } - if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){ - echo_group_input(p, zSql); - errCnt += runOneSqlLine(p, zSql, p->in, startline); - CONTINUE_PROMPT_RESET; - nSql = 0; - if( p->outCount ){ - output_reset(p); - p->outCount = 0; - }else{ - clearTempFile(p); - } - p->bSafeMode = p->bSafeModePersist; - qss = QSS_Start; - }else if( nSql && QSS_PLAINWHITE(qss) ){ - echo_group_input(p, zSql); - nSql = 0; - qss = QSS_Start; - } - } - if( nSql ){ - /* This may be incomplete. Let the SQL parser deal with that. */ - echo_group_input(p, zSql); - errCnt += runOneSqlLine(p, zSql, p->in, startline); - CONTINUE_PROMPT_RESET; - } - free(zSql); - free(zLine); - --p->inputNesting; - return errCnt>0; -} - -/* -** Return a pathname which is the user's home directory. A -** 0 return indicates an error of some kind. -*/ -static char *find_home_dir(int clearFlag){ - static char *home_dir = NULL; - if( clearFlag ){ - free(home_dir); - home_dir = 0; - return 0; - } - if( home_dir ) return home_dir; - -#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ - && !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI) - { - struct passwd *pwent; - uid_t uid = getuid(); - if( (pwent=getpwuid(uid)) != NULL) { - home_dir = pwent->pw_dir; - } - } -#endif - -#if defined(_WIN32_WCE) - /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() - */ - home_dir = "/"; -#else - -#if defined(_WIN32) || defined(WIN32) - if (!home_dir) { - home_dir = getenv("USERPROFILE"); - } -#endif - - if (!home_dir) { - home_dir = getenv("HOME"); - } - -#if defined(_WIN32) || defined(WIN32) - if (!home_dir) { - char *zDrive, *zPath; - int n; - zDrive = getenv("HOMEDRIVE"); - zPath = getenv("HOMEPATH"); - if( zDrive && zPath ){ - n = strlen30(zDrive) + strlen30(zPath) + 1; - home_dir = malloc( n ); - if( home_dir==0 ) return 0; - sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); - return home_dir; - } - home_dir = "c:\\"; - } -#endif - -#endif /* !_WIN32_WCE */ - - if( home_dir ){ - i64 n = strlen(home_dir) + 1; - char *z = malloc( n ); - if( z ) memcpy(z, home_dir, n); - home_dir = z; - } - - return home_dir; -} - -/* -** On non-Windows platforms, look for $XDG_CONFIG_HOME. -** If ${XDG_CONFIG_HOME}/sqlite3/sqliterc is found, return -** the path to it. If there is no $(XDG_CONFIG_HOME) then -** look for $(HOME)/.config/sqlite3/sqliterc and if found -** return that. If none of these are found, return 0. -** -** The string returned is obtained from sqlite3_malloc() and -** should be freed by the caller. -*/ -static char *find_xdg_config(void){ -#if defined(_WIN32) || defined(WIN32) || defined(_WIN32_WCE) \ - || defined(__RTP__) || defined(_WRS_KERNEL) - return 0; -#else - char *zConfig = 0; - const char *zXdgHome; - - zXdgHome = getenv("XDG_CONFIG_HOME"); - if( zXdgHome==0 ){ - const char *zHome = getenv("HOME"); - if( zHome==0 ) return 0; - zConfig = sqlite3_mprintf("%s/.config/sqlite3/sqliterc", zHome); - }else{ - zConfig = sqlite3_mprintf("%s/sqlite3/sqliterc", zXdgHome); - } - shell_check_oom(zConfig); - if( access(zConfig,0)!=0 ){ - sqlite3_free(zConfig); - zConfig = 0; - } - return zConfig; -#endif -} - -/* -** Read input from the file given by sqliterc_override. Or if that -** parameter is NULL, take input from the first of find_xdg_config() -** or ~/.sqliterc which is found. -** -** Returns the number of errors. -*/ -static void process_sqliterc( - ShellState *p, /* Configuration data */ - const char *sqliterc_override /* Name of config file. NULL to use default */ -){ - char *home_dir = NULL; - const char *sqliterc = sqliterc_override; - char *zBuf = 0; - FILE *inSaved = p->in; - int savedLineno = p->lineno; - - if( sqliterc == NULL ){ - sqliterc = zBuf = find_xdg_config(); - } - if( sqliterc == NULL ){ - home_dir = find_home_dir(0); - if( home_dir==0 ){ - eputz("-- warning: cannot find home directory;" - " cannot read ~/.sqliterc\n"); - return; - } - zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); - shell_check_oom(zBuf); - sqliterc = zBuf; - } - p->in = sqlite3_fopen(sqliterc,"rb"); - if( p->in ){ - if( stdin_is_interactive ){ - sqlite3_fprintf(stderr,"-- Loading resources from %s\n", sqliterc); - } - if( process_input(p) && bail_on_error ) exit(1); - fclose(p->in); - }else if( sqliterc_override!=0 ){ - sqlite3_fprintf(stderr,"cannot open: \"%s\"\n", sqliterc); - if( bail_on_error ) exit(1); - } - p->in = inSaved; - p->lineno = savedLineno; - sqlite3_free(zBuf); -} - -/* -** Show available command line options -*/ -static const char zOptions[] = - " -- treat no subsequent arguments as options\n" -#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) - " -A ARGS... run \".archive ARGS\" and exit\n" -#endif - " -append append the database to the end of the file\n" - " -ascii set output mode to 'ascii'\n" - " -bail stop after hitting an error\n" - " -batch force batch I/O\n" - " -box set output mode to 'box'\n" - " -column set output mode to 'column'\n" - " -cmd COMMAND run \"COMMAND\" before reading stdin\n" - " -csv set output mode to 'csv'\n" -#if !defined(SQLITE_OMIT_DESERIALIZE) - " -deserialize open the database using sqlite3_deserialize()\n" -#endif - " -echo print inputs before execution\n" - " -init FILENAME read/process named file\n" - " -[no]header turn headers on or off\n" -#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) - " -heap SIZE Size of heap for memsys3 or memsys5\n" -#endif - " -help show this message\n" - " -html set output mode to HTML\n" - " -interactive force interactive I/O\n" - " -json set output mode to 'json'\n" - " -line set output mode to 'line'\n" - " -list set output mode to 'list'\n" - " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" - " -markdown set output mode to 'markdown'\n" -#if !defined(SQLITE_OMIT_DESERIALIZE) - " -maxsize N maximum size for a --deserialize database\n" -#endif - " -memtrace trace all memory allocations and deallocations\n" - " -mmap N default mmap size set to N\n" -#ifdef SQLITE_ENABLE_MULTIPLEX - " -multiplex enable the multiplexor VFS\n" -#endif - " -newline SEP set output row separator. Default: '\\n'\n" - " -nofollow refuse to open symbolic links to database files\n" - " -nonce STRING set the safe-mode escape nonce\n" - " -no-rowid-in-view Disable rowid-in-view using sqlite3_config()\n" - " -nullvalue TEXT set text string for NULL values. Default ''\n" - " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" - " -pcachetrace trace all page cache operations\n" - " -quote set output mode to 'quote'\n" - " -readonly open the database read-only\n" - " -safe enable safe-mode\n" - " -separator SEP set output column separator. Default: '|'\n" -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - " -sorterref SIZE sorter references threshold size\n" -#endif - " -stats print memory stats before each finalize\n" - " -table set output mode to 'table'\n" - " -tabs set output mode to 'tabs'\n" - " -unsafe-testing allow unsafe commands and modes for testing\n" - " -version show SQLite version\n" - " -vfs NAME use NAME as the default VFS\n" - " -vfstrace enable tracing of all VFS calls\n" -#ifdef SQLITE_HAVE_ZLIB - " -zip open the file as a ZIP Archive\n" -#endif -; -static void usage(int showDetail){ - sqlite3_fprintf(stderr,"Usage: %s [OPTIONS] [FILENAME [SQL]]\n" - "FILENAME is the name of an SQLite database. A new database is created\n" - "if the file does not previously exist. Defaults to :memory:.\n", Argv0); - if( showDetail ){ - sqlite3_fprintf(stderr,"OPTIONS include:\n%s", zOptions); - }else{ - eputz("Use the -help option for additional information\n"); - } - exit(0); -} - -/* -** Internal check: Verify that the SQLite is uninitialized. Print a -** error message if it is initialized. -*/ -static void verify_uninitialized(void){ - if( sqlite3_config(-1)==SQLITE_MISUSE ){ - sputz(stdout, "WARNING: attempt to configure SQLite after" - " initialization.\n"); - } -} - -/* -** Initialize the state information in data -*/ -static void main_init(ShellState *data) { - memset(data, 0, sizeof(*data)); - data->normalMode = data->cMode = data->mode = MODE_List; - data->autoExplain = 1; -#ifdef _WIN32 - data->crlfMode = 1; -#endif - data->pAuxDb = &data->aAuxDb[0]; - memcpy(data->colSeparator,SEP_Column, 2); - memcpy(data->rowSeparator,SEP_Row, 2); - data->showHeader = 0; - data->shellFlgs = SHFLG_Lookaside; - sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); -#if !defined(SQLITE_SHELL_FIDDLE) - verify_uninitialized(); -#endif - sqlite3_config(SQLITE_CONFIG_URI, 1); - sqlite3_config(SQLITE_CONFIG_MULTITHREAD); - sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); - sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); -} - -/* -** Output text to the console in a font that attracts extra attention. -*/ -#if defined(_WIN32) || defined(WIN32) -static void printBold(const char *zText){ -#if !SQLITE_OS_WINRT - HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); - CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; - GetConsoleScreenBufferInfo(out, &defaultScreenInfo); - SetConsoleTextAttribute(out, - FOREGROUND_RED|FOREGROUND_INTENSITY - ); -#endif - sputz(stdout, zText); -#if !SQLITE_OS_WINRT - SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); -#endif -} -#else -static void printBold(const char *zText){ - sqlite3_fprintf(stdout, "\033[1m%s\033[0m", zText); -} -#endif - -/* -** Get the argument to an --option. Throw an error and die if no argument -** is available. -*/ -static char *cmdline_option_value(int argc, char **argv, int i){ - if( i==argc ){ - sqlite3_fprintf(stderr, - "%s: Error: missing argument to %s\n", argv[0], argv[argc-1]); - exit(1); - } - return argv[i]; -} - -static void sayAbnormalExit(void){ - if( seenInterrupt ) eputz("Program interrupted.\n"); -} - -#ifndef SQLITE_SHELL_IS_UTF8 -# if (defined(_WIN32) || defined(WIN32)) \ - && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__))) -# define SQLITE_SHELL_IS_UTF8 (0) -# else -# define SQLITE_SHELL_IS_UTF8 (1) -# endif -#endif - -#ifdef SQLITE_SHELL_FIDDLE -# define main fiddle_main -#endif - -#if SQLITE_SHELL_IS_UTF8 -int SQLITE_CDECL main(int argc, char **argv){ -#else -int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ - char **argv; -#endif -#ifdef SQLITE_DEBUG - sqlite3_int64 mem_main_enter = 0; -#endif - char *zErrMsg = 0; -#ifdef SQLITE_SHELL_FIDDLE -# define data shellState -#else - ShellState data; -#endif - const char *zInitFile = 0; - int i; - int rc = 0; - int warnInmemoryDb = 0; - int readStdin = 1; - int nCmd = 0; - int nOptsEnd = argc; - int bEnableVfstrace = 0; - char **azCmd = 0; - const char *zVfs = 0; /* Value of -vfs command-line option */ -#if !SQLITE_SHELL_IS_UTF8 - char **argvToFree = 0; - int argcToFree = 0; -#endif - setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ - -#ifdef SQLITE_SHELL_FIDDLE - stdin_is_interactive = 0; - stdout_is_console = 1; - data.wasm.zDefaultDbName = "/fiddle.sqlite3"; -#else - stdin_is_interactive = isatty(0); - stdout_is_console = isatty(1); -#endif - atexit(sayAbnormalExit); -#ifdef SQLITE_DEBUG - mem_main_enter = sqlite3_memory_used(); -#endif -#if !defined(_WIN32_WCE) - if( getenv("SQLITE_DEBUG_BREAK") ){ - if( isatty(0) && isatty(2) ){ - char zLine[100]; - sqlite3_fprintf(stderr, - "attach debugger to process %d and press ENTER to continue...", - GETPID()); - if( sqlite3_fgets(zLine, sizeof(zLine), stdin)!=0 - && cli_strcmp(zLine,"stop")==0 - ){ - exit(1); - } - }else{ -#if defined(_WIN32) || defined(WIN32) -#if SQLITE_OS_WINRT - __debugbreak(); -#else - DebugBreak(); -#endif -#elif defined(SIGTRAP) - raise(SIGTRAP); -#endif - } - } -#endif - /* Register a valid signal handler early, before much else is done. */ -#ifdef SIGINT - signal(SIGINT, interrupt_handler); -#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) - if( !SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE) ){ - eputz("No ^C handler.\n"); - } -#endif - -#if USE_SYSTEM_SQLITE+0!=1 - if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){ - sqlite3_fprintf(stderr, - "SQLite header and source version mismatch\n%s\n%s\n", - sqlite3_sourceid(), SQLITE_SOURCE_ID); - exit(1); - } -#endif - main_init(&data); - - /* On Windows, we must translate command-line arguments into UTF-8. - ** The SQLite memory allocator subsystem has to be enabled in order to - ** do this. But we want to run an sqlite3_shutdown() afterwards so that - ** subsequent sqlite3_config() calls will work. So copy all results into - ** memory that does not come from the SQLite memory allocator. - */ -#if !SQLITE_SHELL_IS_UTF8 - sqlite3_initialize(); - argvToFree = malloc(sizeof(argv[0])*argc*2); - shell_check_oom(argvToFree); - argcToFree = argc; - argv = argvToFree + argc; - for(i=0; i<argc; i++){ - char *z = sqlite3_win32_unicode_to_utf8(wargv[i]); - i64 n; - shell_check_oom(z); - n = strlen(z); - argv[i] = malloc( n+1 ); - shell_check_oom(argv[i]); - memcpy(argv[i], z, n+1); - argvToFree[i] = argv[i]; - sqlite3_free(z); - } - sqlite3_shutdown(); -#endif - - assert( argc>=1 && argv && argv[0] ); - Argv0 = argv[0]; - -#ifdef SQLITE_SHELL_DBNAME_PROC - { - /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name - ** of a C-function that will provide the name of the database file. Use - ** this compile-time option to embed this shell program in larger - ** applications. */ - extern void SQLITE_SHELL_DBNAME_PROC(const char**); - SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename); - warnInmemoryDb = 0; - } -#endif - - /* Do an initial pass through the command-line argument to locate - ** the name of the database file, the name of the initialization file, - ** the size of the alternative malloc heap, options affecting commands - ** or SQL run from the command line, and the first command to execute. - */ -#ifndef SQLITE_SHELL_FIDDLE - verify_uninitialized(); -#endif - for(i=1; i<argc; i++){ - char *z; - z = argv[i]; - if( z[0]!='-' || i>nOptsEnd ){ - if( data.aAuxDb->zDbFilename==0 ){ - data.aAuxDb->zDbFilename = z; - }else{ - /* Excess arguments are interpreted as SQL (or dot-commands) and - ** mean that nothing is read from stdin */ - readStdin = 0; - nCmd++; - azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd); - shell_check_oom(azCmd); - azCmd[nCmd-1] = z; - } - continue; - } - if( z[1]=='-' ) z++; - if( cli_strcmp(z, "-")==0 ){ - nOptsEnd = i; - continue; - }else if( cli_strcmp(z,"-separator")==0 - || cli_strcmp(z,"-nullvalue")==0 - || cli_strcmp(z,"-newline")==0 - || cli_strcmp(z,"-cmd")==0 - ){ - (void)cmdline_option_value(argc, argv, ++i); - }else if( cli_strcmp(z,"-init")==0 ){ - zInitFile = cmdline_option_value(argc, argv, ++i); - }else if( cli_strcmp(z,"-interactive")==0 ){ - }else if( cli_strcmp(z,"-batch")==0 ){ - /* Need to check for batch mode here to so we can avoid printing - ** informational messages (like from process_sqliterc) before - ** we do the actual processing of arguments later in a second pass. - */ - stdin_is_interactive = 0; - }else if( cli_strcmp(z,"-utf8")==0 ){ - }else if( cli_strcmp(z,"-no-utf8")==0 ){ - }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){ - int val = 0; - sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW, &val); - assert( val==0 ); - }else if( cli_strcmp(z,"-heap")==0 ){ -#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) - const char *zSize; - sqlite3_int64 szHeap; - - zSize = cmdline_option_value(argc, argv, ++i); - szHeap = integerValue(zSize); - if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000; - verify_uninitialized(); - sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); -#else - (void)cmdline_option_value(argc, argv, ++i); -#endif - }else if( cli_strcmp(z,"-pagecache")==0 ){ - sqlite3_int64 n, sz; - sz = integerValue(cmdline_option_value(argc,argv,++i)); - if( sz>70000 ) sz = 70000; - if( sz<0 ) sz = 0; - n = integerValue(cmdline_option_value(argc,argv,++i)); - if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){ - n = 0xffffffffffffLL/sz; - } - verify_uninitialized(); - sqlite3_config(SQLITE_CONFIG_PAGECACHE, - (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); - data.shellFlgs |= SHFLG_Pagecache; - }else if( cli_strcmp(z,"-lookaside")==0 ){ - int n, sz; - sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); - if( sz<0 ) sz = 0; - n = (int)integerValue(cmdline_option_value(argc,argv,++i)); - if( n<0 ) n = 0; - verify_uninitialized(); - sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); - if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; - }else if( cli_strcmp(z,"-threadsafe")==0 ){ - int n; - n = (int)integerValue(cmdline_option_value(argc,argv,++i)); - verify_uninitialized(); - switch( n ){ - case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); break; - case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD); break; - default: sqlite3_config(SQLITE_CONFIG_SERIALIZED); break; - } - }else if( cli_strcmp(z,"-vfstrace")==0 ){ - vfstrace_register("trace",0,(int(*)(const char*,void*))sqlite3_fputs, - stderr,1); - bEnableVfstrace = 1; -#ifdef SQLITE_ENABLE_MULTIPLEX - }else if( cli_strcmp(z,"-multiplex")==0 ){ - extern int sqlite3_multiplex_initialize(const char*,int); - sqlite3_multiplex_initialize(0, 1); -#endif - }else if( cli_strcmp(z,"-mmap")==0 ){ - sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); - verify_uninitialized(); - sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); -#if defined(SQLITE_ENABLE_SORTER_REFERENCES) - }else if( cli_strcmp(z,"-sorterref")==0 ){ - sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); - verify_uninitialized(); - sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz); -#endif - }else if( cli_strcmp(z,"-vfs")==0 ){ - zVfs = cmdline_option_value(argc, argv, ++i); -#ifdef SQLITE_HAVE_ZLIB - }else if( cli_strcmp(z,"-zip")==0 ){ - data.openMode = SHELL_OPEN_ZIPFILE; -#endif - }else if( cli_strcmp(z,"-append")==0 ){ - data.openMode = SHELL_OPEN_APPENDVFS; -#ifndef SQLITE_OMIT_DESERIALIZE - }else if( cli_strcmp(z,"-deserialize")==0 ){ - data.openMode = SHELL_OPEN_DESERIALIZE; - }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){ - data.szMax = integerValue(argv[++i]); -#endif - }else if( cli_strcmp(z,"-readonly")==0 ){ - data.openMode = SHELL_OPEN_READONLY; - }else if( cli_strcmp(z,"-nofollow")==0 ){ - data.openFlags = SQLITE_OPEN_NOFOLLOW; -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) - }else if( cli_strncmp(z, "-A",2)==0 ){ - /* All remaining command-line arguments are passed to the ".archive" - ** command, so ignore them */ - break; -#endif - }else if( cli_strcmp(z, "-memtrace")==0 ){ - sqlite3MemTraceActivate(stderr); - }else if( cli_strcmp(z, "-pcachetrace")==0 ){ - sqlite3PcacheTraceActivate(stderr); - }else if( cli_strcmp(z,"-bail")==0 ){ - bail_on_error = 1; - }else if( cli_strcmp(z,"-nonce")==0 ){ - free(data.zNonce); - data.zNonce = strdup(cmdline_option_value(argc, argv, ++i)); - }else if( cli_strcmp(z,"-unsafe-testing")==0 ){ - ShellSetFlag(&data,SHFLG_TestingMode); - }else if( cli_strcmp(z,"-safe")==0 ){ - /* no-op - catch this on the second pass */ - } - } -#ifndef SQLITE_SHELL_FIDDLE - if( !bEnableVfstrace ) verify_uninitialized(); -#endif - - -#ifdef SQLITE_SHELL_INIT_PROC - { - /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name - ** of a C-function that will perform initialization actions on SQLite that - ** occur just before or after sqlite3_initialize(). Use this compile-time - ** option to embed this shell program in larger applications. */ - extern void SQLITE_SHELL_INIT_PROC(void); - SQLITE_SHELL_INIT_PROC(); - } -#else - /* All the sqlite3_config() calls have now been made. So it is safe - ** to call sqlite3_initialize() and process any command line -vfs option. */ - sqlite3_initialize(); -#endif - - if( zVfs ){ - sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs); - if( pVfs ){ - sqlite3_vfs_register(pVfs, 1); - }else{ - sqlite3_fprintf(stderr,"no such VFS: \"%s\"\n", zVfs); - exit(1); - } - } - - if( data.pAuxDb->zDbFilename==0 ){ -#ifndef SQLITE_OMIT_MEMORYDB - data.pAuxDb->zDbFilename = ":memory:"; - warnInmemoryDb = argc==1; -#else - sqlite3_fprintf(stderr, - "%s: Error: no database filename specified\n", Argv0); - return 1; -#endif - } - data.out = stdout; -#ifndef SQLITE_SHELL_FIDDLE - sqlite3_appendvfs_init(0,0,0); -#endif - - /* Go ahead and open the database file if it already exists. If the - ** file does not exist, delay opening it. This prevents empty database - ** files from being created if a user mistypes the database name argument - ** to the sqlite command-line tool. - */ - if( access(data.pAuxDb->zDbFilename, 0)==0 ){ - open_db(&data, 0); - } - - /* Process the initialization file if there is one. If no -init option - ** is given on the command line, look for a file named ~/.sqliterc and - ** try to process it. - */ - process_sqliterc(&data,zInitFile); - - /* Make a second pass through the command-line argument and set - ** options. This second pass is delayed until after the initialization - ** file is processed so that the command-line arguments will override - ** settings in the initialization file. - */ - for(i=1; i<argc; i++){ - char *z = argv[i]; - if( z[0]!='-' || i>=nOptsEnd ) continue; - if( z[1]=='-' ){ z++; } - if( cli_strcmp(z,"-init")==0 ){ - i++; - }else if( cli_strcmp(z,"-html")==0 ){ - data.mode = MODE_Html; - }else if( cli_strcmp(z,"-list")==0 ){ - data.mode = MODE_List; - }else if( cli_strcmp(z,"-quote")==0 ){ - data.mode = MODE_Quote; - sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma); - sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row); - }else if( cli_strcmp(z,"-line")==0 ){ - data.mode = MODE_Line; - }else if( cli_strcmp(z,"-column")==0 ){ - data.mode = MODE_Column; - }else if( cli_strcmp(z,"-json")==0 ){ - data.mode = MODE_Json; - }else if( cli_strcmp(z,"-markdown")==0 ){ - data.mode = MODE_Markdown; - }else if( cli_strcmp(z,"-table")==0 ){ - data.mode = MODE_Table; - }else if( cli_strcmp(z,"-box")==0 ){ - data.mode = MODE_Box; - }else if( cli_strcmp(z,"-csv")==0 ){ - data.mode = MODE_Csv; - memcpy(data.colSeparator,",",2); -#ifdef SQLITE_HAVE_ZLIB - }else if( cli_strcmp(z,"-zip")==0 ){ - data.openMode = SHELL_OPEN_ZIPFILE; -#endif - }else if( cli_strcmp(z,"-append")==0 ){ - data.openMode = SHELL_OPEN_APPENDVFS; -#ifndef SQLITE_OMIT_DESERIALIZE - }else if( cli_strcmp(z,"-deserialize")==0 ){ - data.openMode = SHELL_OPEN_DESERIALIZE; - }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){ - data.szMax = integerValue(argv[++i]); -#endif - }else if( cli_strcmp(z,"-readonly")==0 ){ - data.openMode = SHELL_OPEN_READONLY; - }else if( cli_strcmp(z,"-nofollow")==0 ){ - data.openFlags |= SQLITE_OPEN_NOFOLLOW; - }else if( cli_strcmp(z,"-ascii")==0 ){ - data.mode = MODE_Ascii; - sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Unit); - sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Record); - }else if( cli_strcmp(z,"-tabs")==0 ){ - data.mode = MODE_List; - sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,SEP_Tab); - sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,SEP_Row); - }else if( cli_strcmp(z,"-separator")==0 ){ - sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, - "%s",cmdline_option_value(argc,argv,++i)); - }else if( cli_strcmp(z,"-newline")==0 ){ - sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, - "%s",cmdline_option_value(argc,argv,++i)); - }else if( cli_strcmp(z,"-nullvalue")==0 ){ - sqlite3_snprintf(sizeof(data.nullValue), data.nullValue, - "%s",cmdline_option_value(argc,argv,++i)); - }else if( cli_strcmp(z,"-header")==0 ){ - data.showHeader = 1; - ShellSetFlag(&data, SHFLG_HeaderSet); - }else if( cli_strcmp(z,"-noheader")==0 ){ - data.showHeader = 0; - ShellSetFlag(&data, SHFLG_HeaderSet); - }else if( cli_strcmp(z,"-echo")==0 ){ - ShellSetFlag(&data, SHFLG_Echo); - }else if( cli_strcmp(z,"-eqp")==0 ){ - data.autoEQP = AUTOEQP_on; - }else if( cli_strcmp(z,"-eqpfull")==0 ){ - data.autoEQP = AUTOEQP_full; - }else if( cli_strcmp(z,"-stats")==0 ){ - data.statsOn = 1; - }else if( cli_strcmp(z,"-scanstats")==0 ){ - data.scanstatsOn = 1; - }else if( cli_strcmp(z,"-backslash")==0 ){ - /* Undocumented command-line option: -backslash - ** Causes C-style backslash escapes to be evaluated in SQL statements - ** prior to sending the SQL into SQLite. Useful for injecting - ** crazy bytes in the middle of SQL statements for testing and debugging. - */ - ShellSetFlag(&data, SHFLG_Backslash); - }else if( cli_strcmp(z,"-bail")==0 ){ - /* No-op. The bail_on_error flag should already be set. */ - }else if( cli_strcmp(z,"-version")==0 ){ - sqlite3_fprintf(stdout, "%s %s (%d-bit)\n", - sqlite3_libversion(), sqlite3_sourceid(), 8*(int)sizeof(char*)); - return 0; - }else if( cli_strcmp(z,"-interactive")==0 ){ - /* Need to check for interactive override here to so that it can - ** affect console setup (for Windows only) and testing thereof. - */ - stdin_is_interactive = 1; - }else if( cli_strcmp(z,"-batch")==0 ){ - /* already handled */ - }else if( cli_strcmp(z,"-utf8")==0 ){ - /* already handled */ - }else if( cli_strcmp(z,"-no-utf8")==0 ){ - /* already handled */ - }else if( cli_strcmp(z,"-no-rowid-in-view")==0 ){ - /* already handled */ - }else if( cli_strcmp(z,"-heap")==0 ){ - i++; - }else if( cli_strcmp(z,"-pagecache")==0 ){ - i+=2; - }else if( cli_strcmp(z,"-lookaside")==0 ){ - i+=2; - }else if( cli_strcmp(z,"-threadsafe")==0 ){ - i+=2; - }else if( cli_strcmp(z,"-nonce")==0 ){ - i += 2; - }else if( cli_strcmp(z,"-mmap")==0 ){ - i++; - }else if( cli_strcmp(z,"-memtrace")==0 ){ - i++; - }else if( cli_strcmp(z,"-pcachetrace")==0 ){ - i++; -#ifdef SQLITE_ENABLE_SORTER_REFERENCES - }else if( cli_strcmp(z,"-sorterref")==0 ){ - i++; -#endif - }else if( cli_strcmp(z,"-vfs")==0 ){ - i++; - }else if( cli_strcmp(z,"-vfstrace")==0 ){ - i++; -#ifdef SQLITE_ENABLE_MULTIPLEX - }else if( cli_strcmp(z,"-multiplex")==0 ){ - i++; -#endif - }else if( cli_strcmp(z,"-help")==0 ){ - usage(1); - }else if( cli_strcmp(z,"-cmd")==0 ){ - /* Run commands that follow -cmd first and separately from commands - ** that simply appear on the command-line. This seems goofy. It would - ** be better if all commands ran in the order that they appear. But - ** we retain the goofy behavior for historical compatibility. */ - if( i==argc-1 ) break; - z = cmdline_option_value(argc,argv,++i); - if( z[0]=='.' ){ - rc = do_meta_command(z, &data); - if( rc && bail_on_error ) return rc==2 ? 0 : rc; - }else{ - open_db(&data, 0); - rc = shell_exec(&data, z, &zErrMsg); - if( zErrMsg!=0 ){ - shellEmitError(zErrMsg); - if( bail_on_error ) return rc!=0 ? rc : 1; - }else if( rc!=0 ){ - sqlite3_fprintf(stderr,"Error: unable to process SQL \"%s\"\n", z); - if( bail_on_error ) return rc; - } - } -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) - }else if( cli_strncmp(z, "-A", 2)==0 ){ - if( nCmd>0 ){ - sqlite3_fprintf(stderr,"Error: cannot mix regular SQL or dot-commands" - " with \"%s\"\n", z); - return 1; - } - open_db(&data, OPEN_DB_ZIPFILE); - if( z[2] ){ - argv[i] = &z[2]; - arDotCommand(&data, 1, argv+(i-1), argc-(i-1)); - }else{ - arDotCommand(&data, 1, argv+i, argc-i); - } - readStdin = 0; - break; -#endif - }else if( cli_strcmp(z,"-safe")==0 ){ - data.bSafeMode = data.bSafeModePersist = 1; - }else if( cli_strcmp(z,"-unsafe-testing")==0 ){ - /* Acted upon in first pass. */ - }else{ - sqlite3_fprintf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); - eputz("Use -help for a list of options.\n"); - return 1; - } - data.cMode = data.mode; - } - - if( !readStdin ){ - /* Run all arguments that do not begin with '-' as if they were separate - ** command-line inputs, except for the argToSkip argument which contains - ** the database filename. - */ - for(i=0; i<nCmd; i++){ - if( azCmd[i][0]=='.' ){ - rc = do_meta_command(azCmd[i], &data); - if( rc ){ - if( rc==2 ) rc = 0; - goto shell_main_exit; - } - }else{ - open_db(&data, 0); - echo_group_input(&data, azCmd[i]); - rc = shell_exec(&data, azCmd[i], &zErrMsg); - if( zErrMsg || rc ){ - if( zErrMsg!=0 ){ - shellEmitError(zErrMsg); - }else{ - sqlite3_fprintf(stderr, - "Error: unable to process SQL: %s\n", azCmd[i]); - } - sqlite3_free(zErrMsg); - if( rc==0 ) rc = 1; - goto shell_main_exit; - } - } - } - }else{ - /* Run commands received from standard input - */ - if( stdin_is_interactive ){ - char *zHome; - char *zHistory; - int nHistory; -#if CIO_WIN_WC_XLATE -# define SHELL_CIO_CHAR_SET (stdout_is_console? " (UTF-16 console I/O)" : "") -#else -# define SHELL_CIO_CHAR_SET "" -#endif - sqlite3_fprintf(stdout, - "SQLite version %s %.19s%s\n" /*extra-version-info*/ - "Enter \".help\" for usage hints.\n", - sqlite3_libversion(), sqlite3_sourceid(), SHELL_CIO_CHAR_SET); - if( warnInmemoryDb ){ - sputz(stdout, "Connected to a "); - printBold("transient in-memory database"); - sputz(stdout, ".\nUse \".open FILENAME\" to reopen on a" - " persistent database.\n"); - } - zHistory = getenv("SQLITE_HISTORY"); - if( zHistory ){ - zHistory = strdup(zHistory); - }else if( (zHome = find_home_dir(0))!=0 ){ - nHistory = strlen30(zHome) + 20; - if( (zHistory = malloc(nHistory))!=0 ){ - sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); - } - } - if( zHistory ){ shell_read_history(zHistory); } -#if HAVE_READLINE || HAVE_EDITLINE - rl_attempted_completion_function = readline_completion; -#elif HAVE_LINENOISE - linenoiseSetCompletionCallback(linenoise_completion, NULL); -#endif - data.in = 0; - rc = process_input(&data); - if( zHistory ){ - shell_stifle_history(2000); - shell_write_history(zHistory); - free(zHistory); - } - }else{ - data.in = stdin; - rc = process_input(&data); - } - } -#ifndef SQLITE_SHELL_FIDDLE - /* In WASM mode we have to leave the db state in place so that - ** client code can "push" SQL into it after this call returns. */ -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( data.expert.pExpert ){ - expertFinish(&data, 1, 0); - } -#endif - shell_main_exit: - free(azCmd); - set_table_name(&data, 0); - if( data.db ){ - session_close_all(&data, -1); - close_db(data.db); - } - for(i=0; i<ArraySize(data.aAuxDb); i++){ - sqlite3_free(data.aAuxDb[i].zFreeOnClose); - if( data.aAuxDb[i].db ){ - session_close_all(&data, i); - close_db(data.aAuxDb[i].db); - } - } - find_home_dir(1); - output_reset(&data); - data.doXdgOpen = 0; - clearTempFile(&data); -#if !SQLITE_SHELL_IS_UTF8 - for(i=0; i<argcToFree; i++) free(argvToFree[i]); - free(argvToFree); -#endif - free(data.colWidth); - free(data.zNonce); - /* Clear the global data structure so that valgrind will detect memory - ** leaks */ - memset(&data, 0, sizeof(data)); - if( bEnableVfstrace ){ - vfstrace_unregister("trace"); - } -#ifdef SQLITE_DEBUG - if( sqlite3_memory_used()>mem_main_enter ){ - sqlite3_fprintf(stderr,"Memory leaked: %u bytes\n", - (unsigned int)(sqlite3_memory_used()-mem_main_enter)); - } -#endif -#else /* SQLITE_SHELL_FIDDLE... */ - shell_main_exit: -#endif - return rc; -} - - -#ifdef SQLITE_SHELL_FIDDLE -/* Only for emcc experimentation purposes. */ -int fiddle_experiment(int a,int b){ - return a + b; -} - -/* -** Returns a pointer to the current DB handle. -*/ -sqlite3 * fiddle_db_handle(){ - return globalDb; -} - -/* -** Returns a pointer to the given DB name's VFS. If zDbName is 0 then -** "main" is assumed. Returns 0 if no db with the given name is -** open. -*/ -sqlite3_vfs * fiddle_db_vfs(const char *zDbName){ - sqlite3_vfs * pVfs = 0; - if(globalDb){ - sqlite3_file_control(globalDb, zDbName ? zDbName : "main", - SQLITE_FCNTL_VFS_POINTER, &pVfs); - } - return pVfs; -} - -/* Only for emcc experimentation purposes. */ -sqlite3 * fiddle_db_arg(sqlite3 *arg){ - sqlite3_fprintf(stdout, "fiddle_db_arg(%p)\n", (const void*)arg); - return arg; -} - -/* -** Intended to be called via a SharedWorker() while a separate -** SharedWorker() (which manages the wasm module) is performing work -** which should be interrupted. Unfortunately, SharedWorker is not -** portable enough to make real use of. -*/ -void fiddle_interrupt(void){ - if( globalDb ) sqlite3_interrupt(globalDb); -} - -/* -** Returns the filename of the given db name, assuming "main" if -** zDbName is NULL. Returns NULL if globalDb is not opened. -*/ -const char * fiddle_db_filename(const char * zDbName){ - return globalDb - ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main") - : NULL; -} - -/* -** Completely wipes out the contents of the currently-opened database -** but leaves its storage intact for reuse. If any transactions are -** active, they are forcibly rolled back. -*/ -void fiddle_reset_db(void){ - if( globalDb ){ - int rc; - while( sqlite3_txn_state(globalDb,0)>0 ){ - /* - ** Resolve problem reported in - ** https://sqlite.org/forum/forumpost/0b41a25d65 - */ - sqlite3_fputs("Rolling back in-progress transaction.\n", stdout); - sqlite3_exec(globalDb,"ROLLBACK", 0, 0, 0); - } - rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0); - if( 0==rc ) sqlite3_exec(globalDb, "VACUUM", 0, 0, 0); - sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0); - } -} - -/* -** Uses the current database's VFS xRead to stream the db file's -** contents out to the given callback. The callback gets a single -** chunk of size n (its 2nd argument) on each call and must return 0 -** on success, non-0 on error. This function returns 0 on success, -** SQLITE_NOTFOUND if no db is open, or propagates any other non-0 -** code from the callback. Note that this is not thread-friendly: it -** expects that it will be the only thread reading the db file and -** takes no measures to ensure that is the case. -*/ -int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){ - sqlite3_int64 nSize = 0; - sqlite3_int64 nPos = 0; - sqlite3_file * pFile = 0; - unsigned char buf[1024 * 8]; - int nBuf = (int)sizeof(buf); - int rc = shellState.db - ? sqlite3_file_control(shellState.db, "main", - SQLITE_FCNTL_FILE_POINTER, &pFile) - : SQLITE_NOTFOUND; - if( rc ) return rc; - rc = pFile->pMethods->xFileSize(pFile, &nSize); - if( rc ) return rc; - if(nSize % nBuf){ - /* DB size is not an even multiple of the buffer size. Reduce - ** buffer size so that we do not unduly inflate the db size when - ** exporting. */ - if(0 == nSize % 4096) nBuf = 4096; - else if(0 == nSize % 2048) nBuf = 2048; - else if(0 == nSize % 1024) nBuf = 1024; - else nBuf = 512; - } - for( ; 0==rc && nPos<nSize; nPos += nBuf ){ - rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos); - if(SQLITE_IOERR_SHORT_READ == rc){ - rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/; - } - if( 0==rc ) rc = xCallback(buf, nBuf); - } - return rc; -} - -/* -** Trivial exportable function for emscripten. It processes zSql as if -** it were input to the sqlite3 shell and redirects all output to the -** wasm binding. fiddle_main() must have been called before this -** is called, or results are undefined. -*/ -void fiddle_exec(const char * zSql){ - if(zSql && *zSql){ - if('.'==*zSql) puts(zSql); - shellState.wasm.zInput = zSql; - shellState.wasm.zPos = zSql; - process_input(&shellState); - shellState.wasm.zInput = shellState.wasm.zPos = 0; - } -} -#endif /* SQLITE_SHELL_FIDDLE */ diff --git a/SQLite/sqlite3.c b/SQLite/sqlite3.c index 2886d04..ac75490 100644 --- a/SQLite/sqlite3.c +++ b/SQLite/sqlite3.c @@ -1,6 +1,6 @@ /****************************************************************************** ** This file is an amalgamation of many separate C source files from SQLite -** version 3.47.0. By combining all the individual C code files into this +** version 3.54.1. By combining all the individual C code files into this ** single large file, the entire code can be compiled as a single translation ** unit. This allows many compilers to do optimizations that would not be ** possible if the files were compiled separately. Performance improvements @@ -18,8 +18,11 @@ ** separate file. This file contains only code for the core SQLite library. ** ** The content in this amalgamation comes from Fossil check-in -** 03a9703e27c44437c39363d0baf82db4ebc9. +** 555e07ef33f69a0957d24d8e555b702464a1 with changes in files: +** +** */ +#ifndef SQLITE_AMALGAMATION #define SQLITE_CORE 1 #define SQLITE_AMALGAMATION 1 #ifndef SQLITE_PRIVATE @@ -167,7 +170,9 @@ #define HAVE_UTIME 1 #else /* This is not VxWorks. */ -#define OS_VXWORKS 0 +#ifndef OS_VXWORKS +# define OS_VXWORKS 0 +#endif #define HAVE_FCHOWN 1 #define HAVE_READLINK 1 #define HAVE_LSTAT 1 @@ -449,7 +454,7 @@ extern "C" { ** ** Since [version 3.6.18] ([dateof:3.6.18]), ** SQLite source code has been stored in the -** <a href="http://www.fossil-scm.org/">Fossil configuration management +** <a href="http://fossil-scm.org/">Fossil configuration management ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to ** a string which identifies a particular check-in of SQLite ** within its configuration management system. ^The SQLITE_SOURCE_ID @@ -462,9 +467,12 @@ extern "C" { ** [sqlite3_libversion_number()], [sqlite3_sourceid()], ** [sqlite_version()] and [sqlite_source_id()]. */ -#define SQLITE_VERSION "3.47.0" -#define SQLITE_VERSION_NUMBER 3047000 -#define SQLITE_SOURCE_ID "2024-10-21 16:30:22 03a9703e27c44437c39363d0baf82db4ebc94538a0f28411c85dda156f82636e" +#define SQLITE_VERSION "3.54.1" +#define SQLITE_VERSION_NUMBER 3054001 +#define SQLITE_SOURCE_ID "2026-10-16 14:45:20 555e07ef33f69a0957d24d8e555b702464a131d6f1607f4c3c1e4551e8e6ca76" +#define SQLITE_SCM_BRANCH "branch-3.54" +#define SQLITE_SCM_TAGS "release version-3.54.1" +#define SQLITE_SCM_DATETIME "2026-10-16T14:45:20.546Z" /* ** CAPI3REF: Run-Time Library Version Numbers @@ -484,9 +492,9 @@ extern "C" { ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 ); ** </pre></blockquote>)^ ** -** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] -** macro. ^The sqlite3_libversion() function returns a pointer to the -** to the sqlite3_version[] string constant. The sqlite3_libversion() +** ^The sqlite3_version[] string constant contains the text of the +** [SQLITE_VERSION] macro. ^The sqlite3_libversion() function returns a +** pointer to the sqlite3_version[] string constant. The sqlite3_libversion() ** function is provided for use in DLLs since DLL users usually do not have ** direct access to string constants within the DLL. ^The ** sqlite3_libversion_number() function returns an integer equal to @@ -686,7 +694,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**); ** without having to use a lot of C code. ** ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, -** semicolon-separate SQL statements passed into its 2nd argument, +** semicolon-separated SQL statements passed into its 2nd argument, ** in the context of the [database connection] passed in as its 1st ** argument. ^If the callback function of the 3rd argument to ** sqlite3_exec() is not NULL, then it is invoked for each result row @@ -719,7 +727,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**); ** result row is NULL then the corresponding string pointer for the ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the ** sqlite3_exec() callback is an array of pointers to strings where each -** entry represents the name of corresponding result column as obtained +** entry represents the name of a corresponding result column as obtained ** from [sqlite3_column_name()]. ** ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer @@ -776,7 +784,7 @@ SQLITE_API int sqlite3_exec( #define SQLITE_FULL 13 /* Insertion failed because database is full */ #define SQLITE_CANTOPEN 14 /* Unable to open the database file */ #define SQLITE_PROTOCOL 15 /* Database lock protocol error */ -#define SQLITE_EMPTY 16 /* Internal use only */ +#define SQLITE_EMPTY 16 /* No content */ #define SQLITE_SCHEMA 17 /* The database schema changed */ #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ @@ -813,6 +821,9 @@ SQLITE_API int sqlite3_exec( #define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8)) #define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8)) #define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8)) +#define SQLITE_ERROR_RESERVESIZE (SQLITE_ERROR | (4<<8)) +#define SQLITE_ERROR_KEY (SQLITE_ERROR | (5<<8)) +#define SQLITE_ERROR_UNABLE (SQLITE_ERROR | (6<<8)) #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) @@ -847,6 +858,8 @@ SQLITE_API int sqlite3_exec( #define SQLITE_IOERR_DATA (SQLITE_IOERR | (32<<8)) #define SQLITE_IOERR_CORRUPTFS (SQLITE_IOERR | (33<<8)) #define SQLITE_IOERR_IN_PAGE (SQLITE_IOERR | (34<<8)) +#define SQLITE_IOERR_BADKEY (SQLITE_IOERR | (35<<8)) +#define SQLITE_IOERR_CODEC (SQLITE_IOERR | (36<<8)) #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) #define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8)) #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) @@ -886,7 +899,7 @@ SQLITE_API int sqlite3_exec( #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8)) #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8)) -#define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8)) /* internal use only */ +#define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8)) /* internal only */ /* ** CAPI3REF: Flags For File Open Operations @@ -905,7 +918,7 @@ SQLITE_API int sqlite3_exec( ** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into ** [sqlite3_open_v2()] does *not* cause the underlying database file ** to be opened using O_EXCL. Passing SQLITE_OPEN_EXCLUSIVE into -** [sqlite3_open_v2()] has historically be a no-op and might become an +** [sqlite3_open_v2()] has historically been a no-op and might become an ** error in future versions of SQLite. */ #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ @@ -968,6 +981,13 @@ SQLITE_API int sqlite3_exec( ** filesystem supports doing multiple write operations atomically when those ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. +** +** The SQLITE_IOCAP_SUBPAGE_READ property means that it is ok to read +** from the database file in amounts that are not a multiple of the +** page size and that do not begin at a page boundary. Without this +** property, SQLite is careful to only do full-page reads and write +** on aligned pages, with the one exception that it will do a sub-page +** read of the first page to access the database header. */ #define SQLITE_IOCAP_ATOMIC 0x00000001 #define SQLITE_IOCAP_ATOMIC512 0x00000002 @@ -984,6 +1004,7 @@ SQLITE_API int sqlite3_exec( #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 #define SQLITE_IOCAP_IMMUTABLE 0x00002000 #define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000 +#define SQLITE_IOCAP_SUBPAGE_READ 0x00008000 /* ** CAPI3REF: File Locking Levels @@ -991,7 +1012,7 @@ SQLITE_API int sqlite3_exec( ** SQLite uses one of these integer values as the second ** argument to calls it makes to the xLock() and xUnlock() methods ** of an [sqlite3_io_methods] object. These values are ordered from -** lest restrictive to most restrictive. +** least restrictive to most restrictive. ** ** The argument to xLock() is always SHARED or higher. The argument to ** xUnlock is either SHARED or NONE. @@ -1130,6 +1151,7 @@ struct sqlite3_file { ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE] ** <li> [SQLITE_IOCAP_IMMUTABLE] ** <li> [SQLITE_IOCAP_BATCH_ATOMIC] +** <li> [SQLITE_IOCAP_SUBPAGE_READ] ** </ul> ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of @@ -1231,7 +1253,7 @@ struct sqlite3_io_methods { ** connection. See also [SQLITE_FCNTL_FILE_POINTER]. ** ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]] -** No longer in use. +** The SQLITE_FCNTL_SYNC_OMITTED file-control is no longer used. ** ** <li>[[SQLITE_FCNTL_SYNC]] ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and @@ -1306,7 +1328,7 @@ struct sqlite3_io_methods { ** ** <li>[[SQLITE_FCNTL_VFSNAME]] ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of -** all [VFSes] in the VFS stack. The names are of all VFS shims and the +** all [VFSes] in the VFS stack. The names of all VFS shims and the ** final bottom-level VFS are written into memory obtained from ** [sqlite3_malloc()] and the result is stored in the char* variable ** that the fourth parameter of [sqlite3_file_control()] points to. @@ -1320,7 +1342,7 @@ struct sqlite3_io_methods { ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level ** [VFSes] currently in use. ^(The argument X in ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be -** of type "[sqlite3_vfs] **". This opcodes will set *X +** of type "[sqlite3_vfs] **". This opcode will set *X ** to a pointer to the top-level VFS.)^ ** ^When there are multiple VFS shims in the stack, this opcode finds the ** upper-most shim only. @@ -1407,6 +1429,11 @@ struct sqlite3_io_methods { ** pointed to by the pArg argument. This capability is used during testing ** and only needs to be supported when SQLITE_TEST is defined. ** +** <li>[[SQLITE_FCNTL_NULL_IO]] +** The [SQLITE_FCNTL_NULL_IO] opcode sets the low-level file descriptor +** or file handle for the [sqlite3_file] object such that it will no longer +** read or write to the database file. +** ** <li>[[SQLITE_FCNTL_WAL_BLOCK]] ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might ** be advantageous to block on the next WAL lock if the lock is not immediately @@ -1465,6 +1492,12 @@ struct sqlite3_io_methods { ** the value that M is to be set to. Before returning, the 32-bit signed ** integer is overwritten with the previous value of M. ** +** <li>[[SQLITE_FCNTL_BLOCK_ON_CONNECT]] +** The [SQLITE_FCNTL_BLOCK_ON_CONNECT] opcode is used to configure the +** VFS to block when taking a SHARED lock to connect to a wal mode database. +** This is used to implement the functionality associated with +** SQLITE_SETLK_BLOCK_ON_CONNECT. +** ** <li>[[SQLITE_FCNTL_DATA_VERSION]] ** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to ** a database file. The argument is a pointer to a 32-bit unsigned integer. @@ -1499,7 +1532,7 @@ struct sqlite3_io_methods { ** <li>[[SQLITE_FCNTL_EXTERNAL_READER]] ** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect ** whether or not there is a database client in another process with a wal-mode -** transaction open on the database or not. It is only available on unix.The +** transaction open on the database or not. It is only available on unix. The ** (void*) argument passed with this file-control should be a pointer to a ** value of type (int). The integer value is set to 1 if the database is a wal ** mode database and there exists at least one client in another process that @@ -1517,6 +1550,15 @@ struct sqlite3_io_methods { ** database is not a temp db, then the [SQLITE_FCNTL_RESET_CACHE] file-control ** purges the contents of the in-memory page cache. If there is an open ** transaction, or if the db is a temp-db, this opcode is a no-op, not an error. +** +** <li>[[SQLITE_FCNTL_FILESTAT]] +** The [SQLITE_FCNTL_FILESTAT] opcode returns low-level diagnostic information +** about the [sqlite3_file] objects used access the database and journal files +** for the given schema. The fourth parameter to [sqlite3_file_control()] +** should be an initialized [sqlite3_str] pointer. JSON text describing +** various aspects of the sqlite3_file object is appended to the sqlite3_str. +** The SQLITE_FCNTL_FILESTAT opcode is usually a no-op, unless compile-time +** options are used to enable it. ** </ul> */ #define SQLITE_FCNTL_LOCKSTATE 1 @@ -1560,12 +1602,21 @@ struct sqlite3_io_methods { #define SQLITE_FCNTL_EXTERNAL_READER 40 #define SQLITE_FCNTL_CKSM_FILE 41 #define SQLITE_FCNTL_RESET_CACHE 42 +#define SQLITE_FCNTL_NULL_IO 43 +#define SQLITE_FCNTL_BLOCK_ON_CONNECT 44 +#define SQLITE_FCNTL_FILESTAT 45 /* deprecated names */ #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO +/* reserved file-control numbers: +** 101 +** 102 +** 103 +*/ + /* ** CAPI3REF: Mutex Handle @@ -1766,7 +1817,7 @@ typedef const char *sqlite3_filename; ** greater and the function pointer is not NULL) and will fall back ** to xCurrentTime() if xCurrentTimeInt64() is unavailable. ** -** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces +** ^The xSetSystemCall(), xGetSystemCall(), and xNextSystemCall() interfaces ** are not used by the SQLite core. These optional interfaces are provided ** by some VFSes to facilitate testing of the VFS code. By overriding ** system calls with functions under its control, a test program can @@ -1922,7 +1973,7 @@ struct sqlite3_vfs { ** SQLite interfaces so that an application usually does not need to ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] ** calls sqlite3_initialize() so the SQLite library will be automatically -** initialized when [sqlite3_open()] is called if it has not be initialized +** initialized when [sqlite3_open()] is called if it has not been initialized ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] ** compile-time option, then the automatic calls to sqlite3_initialize() ** are omitted and the application must call sqlite3_initialize() directly @@ -1987,7 +2038,8 @@ SQLITE_API int sqlite3_os_end(void); ** are called "anytime configuration options". ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before ** [sqlite3_shutdown()] with a first argument that is not an anytime -** configuration option, then the sqlite3_config() call will return SQLITE_MISUSE. +** configuration option, then the sqlite3_config() call will +** return SQLITE_MISUSE. ** Note, however, that ^sqlite3_config() can be called as part of the ** implementation of an application-defined [sqlite3_os_init()]. ** @@ -2179,21 +2231,21 @@ struct sqlite3_mem_methods { ** The [sqlite3_mem_methods] ** structure is filled with the currently defined memory allocation routines.)^ ** This option can be used to overload the default memory allocation -** routines with a wrapper that simulations memory allocation failure or +** routines with a wrapper that simulates memory allocation failure or ** tracks memory usage, for example. </dd> ** ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt> -** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of +** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes a single argument of ** type int, interpreted as a boolean, which if true provides a hint to ** SQLite that it should avoid large memory allocations if possible. ** SQLite will run faster if it is free to make large memory allocations, -** but some application might prefer to run slower in exchange for +** but some applications might prefer to run slower in exchange for ** guarantees about memory fragmentation that are possible if large ** allocations are avoided. This hint is normally off. ** </dd> ** ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt> -** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int, +** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes a single argument of type int, ** interpreted as a boolean, which enables or disables the collection of ** memory allocation statistics. ^(When memory allocation statistics are ** disabled, the following SQLite interfaces become non-operational: @@ -2238,7 +2290,7 @@ struct sqlite3_mem_methods { ** ^If pMem is NULL and N is non-zero, then each database connection ** does an initial bulk allocation for page cache memory ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or -** of -1024*N bytes if N is negative, . ^If additional +** of -1024*N bytes if N is negative. ^If additional ** page cache memory is needed beyond what is provided by the initial ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each ** additional cache line. </dd> @@ -2267,7 +2319,7 @@ struct sqlite3_mem_methods { ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a ** pointer to an instance of the [sqlite3_mutex_methods] structure. ** The argument specifies alternative low-level mutex routines to be used -** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of +** in place of the mutex routines built into SQLite.)^ ^SQLite makes a copy of ** the content of the [sqlite3_mutex_methods] structure before the call to ** [sqlite3_config()] returns. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then @@ -2290,13 +2342,16 @@ struct sqlite3_mem_methods { ** ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt> ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine -** the default size of lookaside memory on each [database connection]. +** the default size of [lookaside memory] on each [database connection]. ** The first argument is the -** size of each lookaside buffer slot and the second is the number of -** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE -** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] -** option to [sqlite3_db_config()] can be used to change the lookaside -** configuration on individual connections.)^ </dd> +** size of each lookaside buffer slot ("sz") and the second is the number of +** slots allocated to each database connection ("cnt").)^ +** ^(SQLITE_CONFIG_LOOKASIDE sets the <i>default</i> lookaside size. +** The [SQLITE_DBCONFIG_LOOKASIDE] option to [sqlite3_db_config()] can +** be used to change the lookaside configuration on individual connections.)^ +** The [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to change the +** default lookaside configuration at compile-time. +** </dd> ** ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt> ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is @@ -2306,7 +2361,7 @@ struct sqlite3_mem_methods { ** ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt> ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which -** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of +** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies off ** the current page cache implementation into that object.)^ </dd> ** ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt> @@ -2323,7 +2378,7 @@ struct sqlite3_mem_methods { ** the logger function is a copy of the first parameter to the corresponding ** [sqlite3_log()] call and is intended to be a [result code] or an ** [extended result code]. ^The third parameter passed to the logger is -** log message after formatting via [sqlite3_snprintf()]. +** a log message after formatting via [sqlite3_snprintf()]. ** The SQLite logging interface is not reentrant; the logger function ** supplied by the application must not invoke any SQLite interface. ** In a multi-threaded application, the application-defined logger @@ -2512,7 +2567,15 @@ struct sqlite3_mem_methods { ** CAPI3REF: Database Connection Configuration Options ** ** These constants are the available integer configuration options that -** can be passed as the second argument to the [sqlite3_db_config()] interface. +** can be passed as the second parameter to the [sqlite3_db_config()] interface. +** +** The [sqlite3_db_config()] interface is a var-args function. It takes a +** variable number of parameters, though always at least two. The number of +** parameters passed into sqlite3_db_config() depends on which of these +** constants is given as the second parameter. This documentation page +** refers to parameters beyond the second as "arguments". Thus, when this +** page says "the N-th argument" it means "the N-th parameter past the +** configuration option" or "the (N+2)-th parameter to sqlite3_db_config()". ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications @@ -2524,31 +2587,58 @@ struct sqlite3_mem_methods { ** <dl> ** [[SQLITE_DBCONFIG_LOOKASIDE]] ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt> -** <dd> ^This option takes three additional arguments that determine the -** [lookaside memory allocator] configuration for the [database connection]. -** ^The first argument (the third parameter to [sqlite3_db_config()] is a +** <dd> The SQLITE_DBCONFIG_LOOKASIDE option is used to adjust the +** configuration of the [lookaside memory allocator] within a database +** connection. +** The arguments to the SQLITE_DBCONFIG_LOOKASIDE option are <i>not</i> +** in the [DBCONFIG arguments|usual format]. +** The SQLITE_DBCONFIG_LOOKASIDE option takes three arguments, not two, +** so that a call to [sqlite3_db_config()] that uses SQLITE_DBCONFIG_LOOKASIDE +** should have a total of five parameters. +** <ol> +** <li><p>The first argument ("buf") is a ** pointer to a memory buffer to use for lookaside memory. -** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb -** may be NULL in which case SQLite will allocate the -** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the -** size of each lookaside buffer slot. ^The third argument is the number of -** slots. The size of the buffer in the first argument must be greater than -** or equal to the product of the second and third arguments. The buffer -** must be aligned to an 8-byte boundary. ^If the second argument to -** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally -** rounded down to the next smaller multiple of 8. ^(The lookaside memory +** The first argument may be NULL in which case SQLite will allocate the +** lookaside buffer itself using [sqlite3_malloc()]. +** <li><P>The second argument ("sz") is the +** size of each lookaside buffer slot. Lookaside is disabled if "sz" +** is less than 8. The "sz" argument should be a multiple of 8 less than +** 65536. If "sz" does not meet this constraint, it is reduced in size until +** it does. +** <li><p>The third argument ("cnt") is the number of slots. +** Lookaside is disabled if "cnt"is less than 1. +* The "cnt" value will be reduced, if necessary, so +** that the product of "sz" and "cnt" does not exceed 2,147,418,112. The "cnt" +** parameter is usually chosen so that the product of "sz" and "cnt" is less +** than 1,000,000. +** </ol> +** <p>If the "buf" argument is not NULL, then it must +** point to a memory buffer with a size that is greater than +** or equal to the product of "sz" and "cnt". +** The buffer must be aligned to an 8-byte boundary. +** The lookaside memory ** configuration for a database connection can only be changed when that ** connection is not currently using lookaside memory, or in other words -** when the "current value" returned by -** [sqlite3_db_status](D,[SQLITE_DBSTATUS_LOOKASIDE_USED],...) is zero. +** when the value returned by [SQLITE_DBSTATUS_LOOKASIDE_USED] is zero. ** Any attempt to change the lookaside memory configuration when lookaside ** memory is in use leaves the configuration unchanged and returns -** [SQLITE_BUSY].)^</dd> +** [SQLITE_BUSY]. +** If the "buf" argument is NULL and an attempt +** to allocate memory based on "sz" and "cnt" fails, then +** lookaside is silently disabled. +** <p> +** The [SQLITE_CONFIG_LOOKASIDE] configuration option can be used to set the +** default lookaside configuration at initialization. The +** [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to set the default lookaside +** configuration at compile-time. Typical values for lookaside are 1200 for +** "sz" and 40 to 100 for "cnt". +** </dd> ** ** [[SQLITE_DBCONFIG_ENABLE_FKEY]] ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt> ** <dd> ^This option is used to enable or disable the enforcement of -** [foreign key constraints]. There should be two additional arguments. +** [foreign key constraints]. This is the same setting that is +** enabled or disabled by the [PRAGMA foreign_keys] statement. ** The first argument is an integer which is 0 to disable FK enforcement, ** positive to enable FK enforcement or negative to leave FK enforcement ** unchanged. The second parameter is a pointer to an integer into which @@ -2570,13 +2660,13 @@ struct sqlite3_mem_methods { ** <p>Originally this option disabled all triggers. ^(However, since ** SQLite version 3.35.0, TEMP triggers are still allowed even if ** this option is off. So, in other words, this option now only disables -** triggers in the main database schema or in the schemas of ATTACH-ed +** triggers in the main database schema or in the schemas of [ATTACH]-ed ** databases.)^ </dd> ** ** [[SQLITE_DBCONFIG_ENABLE_VIEW]] ** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt> ** <dd> ^This option is used to enable or disable [CREATE VIEW | views]. -** There should be two additional arguments. +** There must be two additional arguments. ** The first argument is an integer which is 0 to disable views, ** positive to enable views or negative to leave the setting unchanged. ** The second parameter is a pointer to an integer into which @@ -2592,17 +2682,20 @@ struct sqlite3_mem_methods { ** ** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]] ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt> -** <dd> ^This option is used to enable or disable the -** [fts3_tokenizer()] function which is part of the -** [FTS3] full-text search engine extension. -** There should be two additional arguments. -** The first argument is an integer which is 0 to disable fts3_tokenizer() or -** positive to enable fts3_tokenizer() or negative to leave the setting -** unchanged. -** The second parameter is a pointer to an integer into which -** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled -** following this call. The second parameter may be a NULL pointer, in -** which case the new setting is not reported back. </dd> +** <dd> ^This option is used to enable or disable using the +** [fts3_tokenizer()] function - part of the [FTS3] full-text search engine +** extension - without using bound parameters as the parameters. Doing so +** is disabled by default. There must be two additional arguments. The first +** argument is an integer. If it is passed 0, then using fts3_tokenizer() +** without bound parameters is disabled. If it is passed a positive value, +** then calling fts3_tokenizer without bound parameters is enabled. If it +** is passed a negative value, this setting is not modified - this can be +** used to query for the current setting. The second parameter is a pointer +** to an integer into which is written 0 or 1 to indicate the current value +** of this setting (after it is modified, if applicable). The second +** parameter may be a NULL pointer, in which case the value of the setting +** is not reported back. Refer to [FTS3] documentation for further details. +** </dd> ** ** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]] ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt> @@ -2610,12 +2703,12 @@ struct sqlite3_mem_methods { ** interface independently of the [load_extension()] SQL function. ** The [sqlite3_enable_load_extension()] API enables or disables both the ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()]. -** There should be two additional arguments. +** There must be two additional arguments. ** When the first argument to this interface is 1, then only the C-API is ** enabled and the SQL function remains disabled. If the first argument to ** this interface is 0, then both the C-API and the SQL function are disabled. -** If the first argument is -1, then no changes are made to state of either the -** C-API or the SQL function. +** If the first argument is -1, then no changes are made to the state of either +** the C-API or the SQL function. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface ** is disabled or enabled following this call. The second parameter may @@ -2624,23 +2717,30 @@ struct sqlite3_mem_methods { ** ** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt> ** <dd> ^This option is used to change the name of the "main" database -** schema. ^The sole argument is a pointer to a constant UTF8 string -** which will become the new schema name in place of "main". ^SQLite -** does not make a copy of the new main schema name string, so the application -** must ensure that the argument passed into this DBCONFIG option is unchanged -** until after the database connection closes. +** schema. This option does not follow the +** [DBCONFIG arguments|usual SQLITE_DBCONFIG argument format]. +** This option takes exactly one additional argument so that the +** [sqlite3_db_config()] call has a total of three parameters. The +** extra argument must be a pointer to a constant UTF8 string which +** will become the new schema name in place of "main". ^SQLite does +** not make a copy of the new main schema name string, so the application +** must ensure that the argument passed into SQLITE_DBCONFIG MAINDBNAME +** is unchanged until after the database connection closes. ** </dd> ** ** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]] ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt> -** <dd> Usually, when a database in wal mode is closed or detached from a -** database handle, SQLite checks if this will mean that there are now no -** connections at all to the database. If so, it performs a checkpoint -** operation before closing the connection. This option may be used to -** override this behavior. The first parameter passed to this operation -** is an integer - positive to disable checkpoints-on-close, or zero (the -** default) to enable them, and negative to leave the setting unchanged. -** The second parameter is a pointer to an integer +** <dd> Usually, when a database in [WAL mode] is closed or detached from a +** database handle, SQLite checks if if there are other connections to the +** same database, and if there are no other database connection (if the +** connection being closed is the last open connection to the database), +** then SQLite performs a [checkpoint] before closing the connection and +** deletes the WAL file. The SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE option can +** be used to override that behavior. The first argument passed to this +** operation (the third parameter to [sqlite3_db_config()]) is an integer +** which is positive to disable checkpoints-on-close, or zero (the default) +** to enable them, and negative to leave the setting unchanged. +** The second argument (the fourth parameter) is a pointer to an integer ** into which is written 0 or 1 to indicate whether checkpoints-on-close ** have been disabled - 0 if they are not disabled, 1 if they are. ** </dd> @@ -2726,7 +2826,7 @@ struct sqlite3_mem_methods { ** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]] ** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt> ** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates -** the legacy behavior of the [ALTER TABLE RENAME] command such it +** the legacy behavior of the [ALTER TABLE RENAME] command such that it ** behaves as it did prior to [version 3.24.0] (2018-06-04). See the ** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for ** additional information. This feature can also be turned on and off @@ -2775,7 +2875,7 @@ struct sqlite3_mem_methods { ** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</dt> ** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates ** the legacy file format flag. When activated, this flag causes all newly -** created database file to have a schema format version number (the 4-byte +** created database files to have a schema format version number (the 4-byte ** integer found at offset 44 into the database header) of 1. This in turn ** means that the resulting database file will be readable and writable by ** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting, @@ -2796,13 +2896,16 @@ struct sqlite3_mem_methods { ** [[SQLITE_DBCONFIG_STMT_SCANSTATUS]] ** <dt>SQLITE_DBCONFIG_STMT_SCANSTATUS</dt> ** <dd>The SQLITE_DBCONFIG_STMT_SCANSTATUS option is only useful in -** SQLITE_ENABLE_STMT_SCANSTATUS builds. In this case, it sets or clears -** a flag that enables collection of the sqlite3_stmt_scanstatus_v2() -** statistics. For statistics to be collected, the flag must be set on -** the database handle both when the SQL statement is prepared and when it -** is stepped. The flag is set (collection of statistics is enabled) -** by default. This option takes two arguments: an integer and a pointer to -** an integer.. The first argument is 1, 0, or -1 to enable, disable, or +** [SQLITE_ENABLE_STMT_SCANSTATUS] builds. In this case, it sets or clears +** a flag that enables collection of run-time performance statistics +** used by [sqlite3_stmt_scanstatus_v2()] and the [nexec and ncycle] +** columns of the [bytecode virtual table]. +** For statistics to be collected, the flag must be set on +** the database handle both when the SQL statement is +** [sqlite3_prepare|prepared] and when it is [sqlite3_step|stepped]. +** The flag is set (collection of statistics is enabled) by default. +** <p>This option takes two arguments: an integer and a pointer to +** an integer. The first argument is 1, 0, or -1 to enable, disable, or ** leave unchanged the statement scanstatus option. If the second argument ** is not NULL, then the value of the statement scanstatus setting after ** processing the first argument is written into the integer that the second @@ -2815,7 +2918,7 @@ struct sqlite3_mem_methods { ** in which tables and indexes are scanned so that the scans start at the end ** and work toward the beginning rather than starting at the beginning and ** working toward the end. Setting SQLITE_DBCONFIG_REVERSE_SCANORDER is the -** same as setting [PRAGMA reverse_unordered_selects]. This option takes +** same as setting [PRAGMA reverse_unordered_selects]. <p>This option takes ** two arguments which are an integer and a pointer to an integer. The first ** argument is 1, 0, or -1 to enable, disable, or leave unchanged the ** reverse scan order flag, respectively. If the second argument is not NULL, @@ -2824,7 +2927,95 @@ struct sqlite3_mem_methods { ** first argument. ** </dd> ** +** [[SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE]] +** <dt>SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE</dt> +** <dd>The SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE option enables or disables +** the ability of the [ATTACH DATABASE] SQL command to create a new database +** file if the database filed named in the ATTACH command does not already +** exist. This ability of ATTACH to create a new database is enabled by +** default. Applications can disable or reenable the ability for ATTACH to +** create new database files using this DBCONFIG option.<p> +** This option takes two arguments which are an integer and a pointer +** to an integer. The first argument is 1, 0, or -1 to enable, disable, or +** leave unchanged the attach-create flag, respectively. If the second +** argument is not NULL, then 0 or 1 is written into the integer that the +** second argument points to depending on if the attach-create flag is set +** after processing the first argument. +** </dd> +** +** [[SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE]] +** <dt>SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE</dt> +** <dd>The SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE option enables or disables the +** ability of the [ATTACH DATABASE] SQL command to open a database for writing. +** This capability is enabled by default. Applications can disable or +** reenable this capability using the current DBCONFIG option. If +** this capability is disabled, the [ATTACH] command will still work, +** but the database will be opened read-only. If this option is disabled, +** then the ability to create a new database using [ATTACH] is also disabled, +** regardless of the value of the [SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE] +** option.<p> +** This option takes two arguments which are an integer and a pointer +** to an integer. The first argument is 1, 0, or -1 to enable, disable, or +** leave unchanged the ability to ATTACH another database for writing, +** respectively. If the second argument is not NULL, then 0 or 1 is written +** into the integer to which the second argument points, depending on whether +** the ability to ATTACH a read/write database is enabled or disabled +** after processing the first argument. +** </dd> +** +** [[SQLITE_DBCONFIG_ENABLE_COMMENTS]] +** <dt>SQLITE_DBCONFIG_ENABLE_COMMENTS</dt> +** <dd>The SQLITE_DBCONFIG_ENABLE_COMMENTS option enables or disables the +** ability to include comments in SQL text. Comments are enabled by default. +** An application can disable or reenable comments in SQL text using this +** DBCONFIG option.<p> +** This option takes two arguments which are an integer and a pointer +** to an integer. The first argument is 1, 0, or -1 to enable, disable, or +** leave unchanged the ability to use comments in SQL text, +** respectively. If the second argument is not NULL, then 0 or 1 is written +** into the integer that the second argument points to depending on if +** comments are allowed in SQL text after processing the first argument. +** </dd> +** +** [[SQLITE_DBCONFIG_FP_DIGITS]] +** <dt>SQLITE_DBCONFIG_FP_DIGITS</dt> +** <dd>The SQLITE_DBCONFIG_FP_DIGITS setting is a small integer that determines +** the number of significant digits that SQLite will attempt to preserve when +** converting floating point numbers (IEEE 754 "doubles") into text. The +** default value 17, as of SQLite version 3.52.0. The value was 15 in all +** prior versions.<p> +** This option takes two arguments which are an integer and a pointer +** to an integer. The first argument is a small integer, between 3 and 23, or +** zero. The FP_DIGITS setting is changed to that small integer, or left +** unaltered if the first argument is zero or out of range. The second argument +** is a pointer to an integer. If the pointer is not NULL, then the value of +** the FP_DIGITS setting, after possibly being modified by the first +** arguments, is written into the integer to which the second argument points. +** </dd> +** ** </dl> +** +** [[DBCONFIG arguments]] <h3>Arguments To SQLITE_DBCONFIG Options</h3> +** +** <p>Most of the SQLITE_DBCONFIG options take two arguments, so that the +** overall call to [sqlite3_db_config()] has a total of four parameters. +** The first argument (the third parameter to sqlite3_db_config()) is +** an integer. +** The second argument is a pointer to an integer. If the first argument is 1, +** then the option becomes enabled. If the first integer argument is 0, +** then the option is disabled. +** If the first argument is -1, then the option setting +** is unchanged. The second argument, the pointer to an integer, may be NULL. +** If the second argument is not NULL, then a value of 0 or 1 is written into +** the integer to which the second argument points, depending on whether the +** setting is disabled or enabled after applying any changes specified by +** the first argument. +** +** <p>While most SQLITE_DBCONFIG options use the argument format +** described in the previous paragraph, the [SQLITE_DBCONFIG_MAINDBNAME], +** [SQLITE_DBCONFIG_LOOKASIDE], and [SQLITE_DBCONFIG_FP_DIGITS] options +** are different. See the documentation of those exceptional options for +** details. */ #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */ #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ @@ -2846,7 +3037,11 @@ struct sqlite3_mem_methods { #define SQLITE_DBCONFIG_TRUSTED_SCHEMA 1017 /* int int* */ #define SQLITE_DBCONFIG_STMT_SCANSTATUS 1018 /* int int* */ #define SQLITE_DBCONFIG_REVERSE_SCANORDER 1019 /* int int* */ -#define SQLITE_DBCONFIG_MAX 1019 /* Largest DBCONFIG */ +#define SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE 1020 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE 1021 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_COMMENTS 1022 /* int int* */ +#define SQLITE_DBCONFIG_FP_DIGITS 1023 /* int int* */ +#define SQLITE_DBCONFIG_MAX 1023 /* Largest DBCONFIG */ /* ** CAPI3REF: Enable Or Disable Extended Result Codes @@ -2938,10 +3133,14 @@ SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64); ** deleted by the most recently completed INSERT, UPDATE or DELETE ** statement on the database connection specified by the only parameter. ** The two functions are identical except for the type of the return value -** and that if the number of rows modified by the most recent INSERT, UPDATE +** and that if the number of rows modified by the most recent INSERT, UPDATE, ** or DELETE is greater than the maximum value supported by type "int", then ** the return value of sqlite3_changes() is undefined. ^Executing any other ** type of SQL statement does not modify the value returned by these functions. +** For the purposes of this interface, a CREATE TABLE AS SELECT statement +** does not count as an INSERT, UPDATE or DELETE statement and hence the rows +** added to the new table by the CREATE TABLE AS SELECT statement are not +** counted. ** ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], @@ -3082,8 +3281,9 @@ SQLITE_API int sqlite3_is_interrupted(sqlite3*); ** These routines are useful during command-line input to determine if the ** currently entered text seems to form a complete SQL statement or ** if additional input is needed before sending the text into -** SQLite for parsing. ^These routines return 1 if the input string -** appears to be a complete SQL statement. ^A statement is judged to be +** SQLite for parsing. ^The sqlite3_complete(X) and sqlite3_complete16(X) +** routines return 1 if the input string X appears to be a complete SQL +** statement. ^A statement is judged to be ** complete if it ends with a semicolon token and is not a prefix of a ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within ** string literals or quoted identifier names or comments are not @@ -3091,11 +3291,25 @@ SQLITE_API int sqlite3_is_interrupted(sqlite3*); ** embedded) and thus do not count as a statement terminator. ^Whitespace ** and comments that follow the final semicolon are ignored. ** -** ^These routines return 0 if the statement is incomplete. ^If a -** memory allocation fails, then SQLITE_NOMEM is returned. +** ^The sqlite3_complete(X) and sqlite3_complete16(X) routines return 0 +** if the statement is incomplete. ^If a memory allocation fails, then +** SQLITE_NOMEM is returned. ** -** ^These routines do not parse the SQL statements thus -** will not detect syntactically incorrect SQL. +** The [sqlite3_incomplete(X)] routine is similar to [sqlite3_complete(X)] +** except that sqlite3_incomplete(X) returns SQLITE_OK if the input X is +** complete, SQLITE_EMPTY if input X consists entirely of whitespace and/or +** comments, SQLITE_MISUSE if X is a NULL pointer, and some other non-zero +** value if X is incomplete. The non-zero return from +** sqlite3_incomplete(X) contains additional information about what is +** needed to complete the input X. See the header comment on the +** implemenation of the sqlite3_incomplete() routine for a full description +** of its non-zero return values. The sqlite3_incomplete(X) interface +** is only available for UTF-8 text. +** +** ^None of these routines do a full parse the SQL statements and thus +** will not detect syntactically incorrect SQL. They only determine if +** input text has properly terminated comments, string literals, and +** quoted identifiers, and if the statement ends with a semicolon. ** ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked @@ -3103,14 +3317,15 @@ SQLITE_API int sqlite3_is_interrupted(sqlite3*); ** then the return value from sqlite3_complete16() will be non-zero ** regardless of whether or not the input SQL is complete.)^ ** -** The input to [sqlite3_complete()] must be a zero-terminated -** UTF-8 string. +** The X input to [sqlite3_complete(X)] and [sqlite3_incomplete(X)] +** must be a zero-terminated UTF-8 string. ** ** The input to [sqlite3_complete16()] must be a zero-terminated ** UTF-16 string in native byte order. */ SQLITE_API int sqlite3_complete(const char *sql); SQLITE_API int sqlite3_complete16(const void *sql); +SQLITE_API sqlite3_int64 sqlite3_incomplete(const char *sql); /* ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors @@ -3196,6 +3411,44 @@ SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*); */ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); +/* +** CAPI3REF: Set the Setlk Timeout +** METHOD: sqlite3 +** +** This routine is only useful in SQLITE_ENABLE_SETLK_TIMEOUT builds. If +** the VFS supports blocking locks, it sets the timeout in ms used by +** eligible locks taken on wal mode databases by the specified database +** handle. In non-SQLITE_ENABLE_SETLK_TIMEOUT builds, or if the VFS does +** not support blocking locks, this function is a no-op. +** +** Passing 0 to this function disables blocking locks altogether. Passing +** -1 to this function requests that the VFS blocks for a long time - +** indefinitely if possible. The results of passing any other negative value +** are undefined. +** +** Internally, each SQLite database handle stores two timeout values - the +** busy-timeout (used for rollback mode databases, or if the VFS does not +** support blocking locks) and the setlk-timeout (used for blocking locks +** on wal-mode databases). The sqlite3_busy_timeout() method sets both +** values, this function sets only the setlk-timeout value. Therefore, +** to configure separate busy-timeout and setlk-timeout values for a single +** database handle, call sqlite3_busy_timeout() followed by this function. +** +** Whenever the number of connections to a wal mode database falls from +** 1 to 0, the last connection takes an exclusive lock on the database, +** then checkpoints and deletes the wal file. While it is doing this, any +** new connection that tries to read from the database fails with an +** SQLITE_BUSY error. Or, if the SQLITE_SETLK_BLOCK_ON_CONNECT flag is +** passed to this API, the new connection blocks until the exclusive lock +** has been released. +*/ +SQLITE_API int sqlite3_setlk_timeout(sqlite3*, int ms, int flags); + +/* +** CAPI3REF: Flags for sqlite3_setlk_timeout() +*/ +#define SQLITE_SETLK_BLOCK_ON_CONNECT 0x01 + /* ** CAPI3REF: Convenience Routines For Running Queries ** METHOD: sqlite3 @@ -3203,7 +3456,7 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); ** This is a legacy interface that is preserved for backwards compatibility. ** Use of this interface is not recommended. ** -** Definition: A <b>result table</b> is memory data structure created by the +** Definition: A <b>result table</b> is a memory data structure created by the ** [sqlite3_get_table()] interface. A result table records the ** complete query results from one or more queries. ** @@ -3346,7 +3599,7 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); ** ^Calling sqlite3_free() with a pointer previously returned ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so ** that it might be reused. ^The sqlite3_free() routine is -** a no-op if is called with a NULL pointer. Passing a NULL pointer +** a no-op if it is called with a NULL pointer. Passing a NULL pointer ** to sqlite3_free() is harmless. After being freed, memory ** should neither be read nor written. Even reading previously freed ** memory might result in a segmentation fault or other severe error. @@ -3364,13 +3617,13 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); ** sqlite3_free(X). ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation ** of at least N bytes in size or NULL if insufficient memory is available. -** ^If M is the size of the prior allocation, then min(N,M) bytes -** of the prior allocation are copied into the beginning of buffer returned +** ^If M is the size of the prior allocation, then min(N,M) bytes of the +** prior allocation are copied into the beginning of the buffer returned ** by sqlite3_realloc(X,N) and the prior allocation is freed. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the ** prior allocation is not freed. ** -** ^The sqlite3_realloc64(X,N) interfaces works the same as +** ^The sqlite3_realloc64(X,N) interface works the same as ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead ** of a 32-bit signed integer. ** @@ -3420,7 +3673,7 @@ SQLITE_API sqlite3_uint64 sqlite3_msize(void*); ** was last reset. ^The values returned by [sqlite3_memory_used()] and ** [sqlite3_memory_highwater()] include any overhead ** added by SQLite in its implementation of [sqlite3_malloc()], -** but not overhead added by the any underlying system library +** but not overhead added by any underlying system library ** routines that [sqlite3_malloc()] may call. ** ** ^The memory high-water mark is reset to the current value of @@ -3485,7 +3738,7 @@ SQLITE_API void sqlite3_randomness(int N, void *P); ** ** ^The first parameter to the authorizer callback is a copy of the third ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter -** to the callback is an integer [SQLITE_COPY | action code] that specifies +** to the callback is an integer [SQLITE_READ | action code] that specifies ** the particular action to be authorized. ^The third through sixth parameters ** to the callback are either NULL pointers or zero-terminated strings ** that contain additional details about the action to be authorized. @@ -3528,21 +3781,33 @@ SQLITE_API void sqlite3_randomness(int N, void *P); ** previous call.)^ ^Disable the authorizer by installing a NULL callback. ** The authorizer is disabled by default. ** -** The authorizer callback must not do anything that will modify +** <h3>Limitations And Caveats</h3><ul> +** +** <li>The authorizer callback must not do anything that will modify ** the database connection that invoked the authorizer callback. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** -** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the +** <li>^When [sqlite3_prepare_v2()] is used to prepare a statement, the ** statement might be re-prepared during [sqlite3_step()] due to a ** schema change. Hence, the application should ensure that the ** correct authorizer callback remains in place during the [sqlite3_step()]. ** -** ^Note that the authorizer callback is invoked only during +** <li>^The authorizer callback is invoked only during ** [sqlite3_prepare()] or its variants. Authorization is not ** performed during statement evaluation in [sqlite3_step()], unless ** as stated in the previous paragraph, sqlite3_step() invokes ** sqlite3_prepare_v2() to reprepare a statement after a schema change. +** +** <li>Authorizer callbacks for the expressions of a +** [generated column] are invoked when the schema is parsed (and specifically +** when the [CREATE TABLE] statement that contains the generated column is +** parsed) not when the generated column is used in a DML statement. +** This is deliberate, as one of the purposes of generated columns +** is to give schema designers the ability to provide gated access +** to privileged columns and/or functions. +** +** </ul> */ SQLITE_API int sqlite3_set_authorizer( sqlite3*, @@ -3583,6 +3848,11 @@ SQLITE_API int sqlite3_set_authorizer( ** is the name of the inner-most trigger or view that is responsible for ** the access attempt or NULL if this access attempt is directly from ** top-level SQL code. +** +** The case of strings in the 3rd through the 6th argument to the +** authorization callback is arbitrary. Authorization callbacks +** implementations should use [sqlite3_stricmp()] or similar when +** doing comparisons against those values. */ /******************************************* 3rd ************ 4th ***********/ #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ @@ -3617,9 +3887,14 @@ SQLITE_API int sqlite3_set_authorizer( #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ #define SQLITE_FUNCTION 31 /* NULL Function Name */ #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ -#define SQLITE_COPY 0 /* No longer used */ #define SQLITE_RECURSIVE 33 /* NULL NULL */ +/* +** Note: The SQLITE_COPY macro (with value 0) used to be one of the +** action codes above. That macro has now been repurposed as a possible +** value to the 3rd argument to sqlite3_result_str(). +*/ + /* ** CAPI3REF: Deprecated Tracing And Profiling Functions ** DEPRECATED @@ -3872,7 +4147,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** there is no harm in trying.) ** ** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt> -** <dd>The database is opened [shared cache] enabled, overriding +** <dd>The database is opened with [shared cache] enabled, overriding ** the default shared cache setting provided by ** [sqlite3_enable_shared_cache()].)^ ** The [use of shared cache mode is discouraged] and hence shared cache @@ -3880,7 +4155,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** this option is a no-op. ** ** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt> -** <dd>The database is opened [shared cache] disabled, overriding +** <dd>The database is opened with [shared cache] disabled, overriding ** the default shared cache setting provided by ** [sqlite3_enable_shared_cache()].)^ ** @@ -4126,8 +4401,7 @@ SQLITE_API int sqlite3_open_v2( ** ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a ** 64-bit signed integer and returns that integer, or D if P does not -** exist. If the value of P is something other than an integer, then -** zero is returned. +** exist or if the value of P is something other than an integer. ** ** The sqlite3_uri_key(F,N) returns a pointer to the name (not ** the value) of the N-th query parameter for filename F, or a NULL @@ -4215,7 +4489,7 @@ SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*); ** ** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of ** database filename D with corresponding journal file J and WAL file W and -** with N URI parameters key/values pairs in the array P. The result from +** an array P of N URI Key/Value pairs. The result from ** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that ** is safe to pass to routines like: ** <ul> @@ -4286,6 +4560,7 @@ SQLITE_API void sqlite3_free_filename(sqlite3_filename); ** <li> sqlite3_errmsg() ** <li> sqlite3_errmsg16() ** <li> sqlite3_error_offset() +** <li> sqlite3_db_handle() ** </ul> ** ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language @@ -4298,7 +4573,7 @@ SQLITE_API void sqlite3_free_filename(sqlite3_filename); ** subsequent calls to other SQLite interface functions.)^ ** ** ^The sqlite3_errstr(E) interface returns the English-language text -** that describes the [result code] E, as UTF-8, or NULL if E is not an +** that describes the [result code] E, as UTF-8, or NULL if E is not a ** result code for which a text error message is available. ** ^(Memory to hold the error message string is managed internally ** and must not be freed by the application)^. @@ -4306,7 +4581,7 @@ SQLITE_API void sqlite3_free_filename(sqlite3_filename); ** ^If the most recent error references a specific token in the input ** SQL, the sqlite3_error_offset() interface returns the byte offset ** of the start of that token. ^The byte offset returned by -** sqlite3_error_offset() assumes that the input SQL is UTF8. +** sqlite3_error_offset() assumes that the input SQL is UTF-8. ** ^If the most recent error does not reference a specific token in the input ** SQL, then the sqlite3_error_offset() function returns -1. ** @@ -4331,6 +4606,34 @@ SQLITE_API const void *sqlite3_errmsg16(sqlite3*); SQLITE_API const char *sqlite3_errstr(int); SQLITE_API int sqlite3_error_offset(sqlite3 *db); +/* +** CAPI3REF: Set Error Code And Message +** METHOD: sqlite3 +** +** Set the error code of the database handle passed as the first argument +** to errcode, and the error message to a copy of nul-terminated string +** zErrMsg. If zErrMsg is passed NULL, then the error message is set to +** the default message associated with the supplied error code. Subsequent +** calls to [sqlite3_errcode()] and [sqlite3_errmsg()] and similar will +** return the values set by this routine in place of what was previously +** set by SQLite itself. +** +** This function returns SQLITE_OK if the error code and error message are +** successfully set, SQLITE_NOMEM if an OOM occurs, and SQLITE_MISUSE if +** the database handle is NULL or invalid. +** +** The error code and message set by this routine remains in effect until +** they are changed, either by another call to this routine or until they are +** changed to by SQLite itself to reflect the result of some subsquent +** API call. +** +** This function is intended for use by SQLite extensions or wrappers. The +** idea is that an extension or wrapper can use this routine to set error +** messages and error codes and thus behave more like a core SQLite +** feature from the point of view of an application. +*/ +SQLITE_API int sqlite3_set_errmsg(sqlite3 *db, int errcode, const char *zErrMsg); + /* ** CAPI3REF: Prepared Statement Object ** KEYWORDS: {prepared statement} {prepared statements} @@ -4405,8 +4708,8 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** ** These constants define various performance limits ** that can be lowered at run-time using [sqlite3_limit()]. -** The synopsis of the meanings of the various limits is shown below. -** Additional information is available at [limits | Limits in SQLite]. +** A concise description of these limits follows, and additional information +** is available at [limits | Limits in SQLite]. ** ** <dl> ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt> @@ -4421,7 +4724,12 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** or in an ORDER BY or GROUP BY clause.</dd>)^ ** ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt> -** <dd>The maximum depth of the parse tree on any expression.</dd>)^ +** <dd>The maximum depth of the parse tree on any expression and +** the maximum nesting depth for subqueries and VIEWs</dd>)^ +** +** [[SQLITE_LIMIT_PARSER_DEPTH]] ^(<dt>SQLITE_LIMIT_PARSER_DEPTH</dt> +** <dd>The maximum depth of the LALR(1) parser stack used to analyze +** input SQL statements.</dd>)^ ** ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt> ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^ @@ -4448,11 +4756,20 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** <dd>The maximum index number of any [parameter] in an SQL statement.)^ ** ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt> -** <dd>The maximum depth of recursion for triggers.</dd>)^ +** <dd>The maximum depth of recursion for triggers, and the maximum +** nesting depth for separate triggers.</dd>)^ ** ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt> ** <dd>The maximum number of auxiliary worker threads that a single ** [prepared statement] may start.</dd>)^ +** +** [[SQLITE_LIMIT_SCHEMA]] ^(<dt>SQLITE_LIMIT_SCHEMA</dt> +** <dd>The maximum number of objects (tables, indexes, triggers, and views) +** defined by the database schema.</dd>)^ +** +** [[SQLITE_LIMIT_TRIGGER_STEPS]] ^(<dt>SQLITE_LIMIT_TRIGGER_STEPS</dt> +** <dd>The maximum number of SQL statements that can be contained within +** a single trigger.</dd>)^ ** </dl> */ #define SQLITE_LIMIT_LENGTH 0 @@ -4467,11 +4784,14 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); #define SQLITE_LIMIT_VARIABLE_NUMBER 9 #define SQLITE_LIMIT_TRIGGER_DEPTH 10 #define SQLITE_LIMIT_WORKER_THREADS 11 +#define SQLITE_LIMIT_PARSER_DEPTH 12 +#define SQLITE_LIMIT_SCHEMA 13 +#define SQLITE_LIMIT_TRIGGER_STEPS 14 /* ** CAPI3REF: Prepare Flags ** -** These constants define various flags that can be passed into +** These constants define various flags that can be passed into the ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and ** [sqlite3_prepare16_v3()] interfaces. ** @@ -4501,11 +4821,39 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler ** to return an error (error code SQLITE_ERROR) if the statement uses ** any virtual tables. +** +** [[SQLITE_PREPARE_DONT_LOG]] <dt>SQLITE_PREPARE_DONT_LOG</dt> +** <dd>The SQLITE_PREPARE_DONT_LOG flag prevents SQL compiler +** errors from being sent to the error log defined by +** [SQLITE_CONFIG_LOG]. This can be used, for example, to do test +** compiles to see if some SQL syntax is well-formed, without generating +** messages on the global error log when it is not. If the test compile +** fails, the sqlite3_prepare_v3() call returns the same error indications +** with or without this flag; it just omits the call to [sqlite3_log()] that +** logs the error. +** +** [[SQLITE_PREPARE_FROM_DDL]] <dt>SQLITE_PREPARE_FROM_DDL</dt> +** <dd>The SQLITE_PREPARE_FROM_DDL flag causes the SQL compiler to enforce +** security constraints that would otherwise only be enforced when parsing +** the database schema. In other words, the SQLITE_PREPARE_FROM_DDL flag +** causes the SQL compiler to treat the SQL statement being prepared as if +** it had come from an attacker. When SQLITE_PREPARE_FROM_DDL is used and +** [SQLITE_DBCONFIG_TRUSTED_SCHEMA] is off, SQL functions may only be called +** if they are tagged with [SQLITE_INNOCUOUS] and virtual tables may only +** be used if they are tagged with [SQLITE_VTAB_INNOCUOUS]. Best practice +** is to use the SQLITE_PREPARE_FROM_DDL option when preparing any SQL that +** is derived from parts of the database schema. In particular, virtual +** table implementations that run SQL statements that are derived from +** arguments to their CREATE VIRTUAL TABLE statement should always use +** [sqlite3_prepare_v3()] and set the SQLITE_PREPARE_FROM_DDL flag to +** prevent bypass of the [SQLITE_DBCONFIG_TRUSTED_SCHEMA] security checks. ** </dl> */ #define SQLITE_PREPARE_PERSISTENT 0x01 #define SQLITE_PREPARE_NORMALIZE 0x02 #define SQLITE_PREPARE_NO_VTAB 0x04 +#define SQLITE_PREPARE_DONT_LOG 0x10 +#define SQLITE_PREPARE_FROM_DDL 0x20 /* ** CAPI3REF: Compiling An SQL Statement @@ -4519,8 +4867,9 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** ** The preferred routine to use is [sqlite3_prepare_v2()]. The ** [sqlite3_prepare()] interface is legacy and should be avoided. -** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used -** for special purposes. +** [sqlite3_prepare_v3()] has an extra +** [SQLITE_PREPARE_FROM_DDL|"prepFlags" option] that is sometimes +** needed for special purpose or to pass along security restrictions. ** ** The use of the UTF-8 interfaces is preferred, as SQLite currently ** does all parsing using UTF-8. The UTF-16 interfaces are provided @@ -4547,8 +4896,10 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** there is a small performance advantage to passing an nByte parameter that ** is the number of bytes in the input string <i>including</i> ** the nul-terminator. -** Note that nByte measure the length of the input in bytes, not +** Note that nByte measures the length of the input in bytes, not ** characters, even for the UTF-16 interfaces. +** For the sqlite3_prepare16() and sqlite3_prepare16_v2() interfaces, +** the nByte value must be even or undefined behavior can result. ** ** ^If pzTail is not NULL then *pzTail is made to point to the first byte ** past the end of the first SQL statement in zSql. These routines only @@ -4681,7 +5032,7 @@ SQLITE_API int sqlite3_prepare16_v3( ** ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory ** is available to hold the result, or if the result would exceed the -** the maximum string length determined by the [SQLITE_LIMIT_LENGTH]. +** maximum string length determined by the [SQLITE_LIMIT_LENGTH]. ** ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time @@ -4869,7 +5220,7 @@ typedef struct sqlite3_value sqlite3_value; ** ** The context in which an SQL function executes is stored in an ** sqlite3_context object. ^A pointer to an sqlite3_context object -** is always first parameter to [application-defined SQL functions]. +** is always the first parameter to [application-defined SQL functions]. ** The application-defined SQL function implementation will pass this ** pointer through into calls to [sqlite3_result_int | sqlite3_result()], ** [sqlite3_aggregate_context()], [sqlite3_user_data()], @@ -4885,7 +5236,7 @@ typedef struct sqlite3_context sqlite3_context; ** METHOD: sqlite3_stmt ** ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, -** literals may be replaced by a [parameter] that matches one of following +** literals may be replaced by a [parameter] that matches one of the following ** templates: ** ** <ul> @@ -4925,12 +5276,12 @@ typedef struct sqlite3_context sqlite3_context; ** it should be a pointer to well-formed UTF16 text. ** ^If the third parameter to sqlite3_bind_text64() is not NULL, then ** it should be a pointer to a well-formed unicode string that is -** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16 -** otherwise. +** either UTF8 if the sixth parameter is SQLITE_UTF8 or SQLITE_UTF8_ZT, +** or UTF16 otherwise. ** ** [[byte-order determination rules]] ^The byte-order of ** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF) -** found in first character, which is removed, or in the absence of a BOM +** found in the first character, which is removed, or in the absence of a BOM ** the byte order is the native byte order of the host ** machine for sqlite3_bind_text16() or the byte order specified in ** the 6th parameter for sqlite3_bind_text64().)^ @@ -4950,7 +5301,7 @@ typedef struct sqlite3_context sqlite3_context; ** or sqlite3_bind_text16() or sqlite3_bind_text64() then ** that parameter must be the byte offset ** where the NUL terminator would occur assuming the string were NUL -** terminated. If any NUL characters occurs at byte offsets less than +** terminated. If any NUL characters occur at byte offsets less than ** the value of the fourth parameter then the resulting string value will ** contain embedded NULs. The result of expressions involving strings ** with embedded NULs is undefined. @@ -4972,10 +5323,15 @@ typedef struct sqlite3_context sqlite3_context; ** object and pointer to it must remain valid until then. ^SQLite will then ** manage the lifetime of its private copy. ** -** ^The sixth argument to sqlite3_bind_text64() must be one of -** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE] -** to specify the encoding of the text in the third parameter. If -** the sixth argument to sqlite3_bind_text64() is not one of the +** ^The sixth argument (the E argument) +** to sqlite3_bind_text64(S,K,Z,N,D,E) must be one of +** [SQLITE_UTF8], [SQLITE_UTF8_ZT], [SQLITE_UTF16], [SQLITE_UTF16BE], +** or [SQLITE_UTF16LE] to specify the encoding of the text in the +** third parameter, Z. The special value [SQLITE_UTF8_ZT] means that the +** string argument is both UTF-8 encoded and is zero-terminated. In other +** words, SQLITE_UTF8_ZT means that the Z array is allocated to hold at +** least N+1 bytes and that the Z&#91;N&#93; byte is zero. If +** the E argument to sqlite3_bind_text64(S,K,Z,N,D,E) is not one of the ** allowed values shown above, or if the text encoding is different ** from the encoding specified by the sixth parameter, then the behavior ** is undefined. @@ -4993,9 +5349,11 @@ typedef struct sqlite3_context sqlite3_context; ** associated with the pointer P of type T. ^D is either a NULL pointer or ** a pointer to a destructor function for P. ^SQLite will invoke the ** destructor D with a single argument of P when it is finished using -** P. The T parameter should be a static string, preferably a string -** literal. The sqlite3_bind_pointer() routine is part of the -** [pointer passing interface] added for SQLite 3.20.0. +** P, even if the call to sqlite3_bind_pointer() fails. Due to a +** historical design quirk, results are undefined if D is +** SQLITE_TRANSIENT. The T parameter should be a static string, +** preferably a string literal. The sqlite3_bind_pointer() routine is +** part of the [pointer passing interface] added for SQLite 3.20.0. ** ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer ** for the [prepared statement] or with a prepared statement for which @@ -5162,7 +5520,7 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); ** METHOD: sqlite3_stmt ** ** ^These routines provide a means to determine the database, table, and -** table column that is the origin of a particular result column in +** table column that is the origin of a particular result column in a ** [SELECT] statement. ** ^The name of the database or table or column can be returned as ** either a UTF-8 or UTF-16 string. ^The _database_ routines return @@ -5288,7 +5646,7 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); ** [prepared statement]. ^In the "v2" interface, ** the more specific error code is returned directly by sqlite3_step(). ** -** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** [SQLITE_MISUSE] means that this routine was called inappropriately. ** Perhaps it was called on a [prepared statement] that has ** already been [sqlite3_finalize | finalized] or on one that had ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could @@ -5300,7 +5658,7 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); ** other than [SQLITE_ROW] before any subsequent invocation of ** sqlite3_step(). Failure to reset the prepared statement using ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from -** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1], +** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1]), ** sqlite3_step() began ** calling [sqlite3_reset()] automatically in this circumstance rather ** than returning [SQLITE_MISUSE]. This is not considered a compatibility @@ -5606,7 +5964,7 @@ SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); ** ** ^The sqlite3_finalize() function is called to delete a [prepared statement]. ** ^If the most recent evaluation of the statement encountered no errors -** or if the statement is never been evaluated, then sqlite3_finalize() returns +** or if the statement has never been evaluated, then sqlite3_finalize() returns ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then ** sqlite3_finalize(S) returns the appropriate [error code] or ** [extended error code]. @@ -5731,8 +6089,8 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** ** For best security, the [SQLITE_DIRECTONLY] flag is recommended for ** all application-defined SQL functions that do not need to be -** used inside of triggers, view, CHECK constraints, or other elements of -** the database schema. This flags is especially recommended for SQL +** used inside of triggers, views, CHECK constraints, or other elements of +** the database schema. This flag is especially recommended for SQL ** functions that have side effects or reveal internal application state. ** Without this flag, an attacker might be able to modify the schema of ** a database file to include invocations of the function with parameters @@ -5763,7 +6121,7 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** [user-defined window functions|available here]. ** ** ^(If the final parameter to sqlite3_create_function_v2() or -** sqlite3_create_window_function() is not NULL, then it is destructor for +** sqlite3_create_window_function() is not NULL, then it is the destructor for ** the application data pointer. The destructor is invoked when the function ** is deleted, either by being overloaded or when the database connection ** closes.)^ ^The destructor is also invoked if the call to @@ -5838,8 +6196,54 @@ SQLITE_API int sqlite3_create_window_function( /* ** CAPI3REF: Text Encodings ** -** These constant define integer codes that represent the various +** These constants define integer codes that represent the various ** text encodings supported by SQLite. +** +** <dl> +** [[SQLITE_UTF8]] <dt>SQLITE_UTF8</dt><dd>Text is encoding as UTF-8</dd> +** +** [[SQLITE_UTF16LE]] <dt>SQLITE_UTF16LE</dt><dd>Text is encoding as UTF-16 +** with each code point being expressed "little endian" - the least significant +** byte first. This is the usual encoding, for example on Windows.</dd> +** +** [[SQLITE_UTF16BE]] <dt>SQLITE_UTF16BE</dt><dd>Text is encoding as UTF-16 +** with each code point being expressed "big endian" - the most significant +** byte first. This encoding is less common, but is still sometimes seen, +** specially on older systems. +** +** [[SQLITE_UTF16]] <dt>SQLITE_UTF16</dt><dd>Text is encoding as UTF-16 +** with each code point being expressed either little endian or as big +** endian, according to the native endianness of the host computer. +** +** [[SQLITE_ANY]] <dt>SQLITE_ANY</dt><dd>This encoding value may only be used +** to declare the preferred text for [application-defined SQL functions] +** created using [sqlite3_create_function()] and similar. If the preferred +** encoding (the 4th parameter to sqlite3_create_function() - the eTextRep +** parameter) is SQLITE_ANY, that indicates that the function does not have +** a preference regarding the text encoding of its parameters and can take +** any text encoding that the SQLite core find convenient to supply. This +** option is deprecated. Please do not use it in new applications. +** +** [[SQLITE_UTF16_ALIGNED]] <dt>SQLITE_UTF16_ALIGNED</dt><dd>This encoding +** value may be used as the 3rd parameter (the eTextRep parameter) to +** [sqlite3_create_collation()] and similar. This encoding value means +** that the application-defined collating sequence created expects its +** input strings to be in UTF16 in native byte order, and that the start +** of the strings must be aligned to a 2-byte boundary. +** +** [[SQLITE_UTF8_ZT]] <dt>SQLITE_UTF8_ZT</dt><dd>This option can only be +** used to specify the text encoding to strings input to +** [sqlite3_result_text64()] and [sqlite3_bind_text64()]. +** The SQLITE_UTF8_ZT encoding means that the input string (call it "z") +** is UTF-8 encoded and that it is zero-terminated. If the length parameter +** (call it "n") is non-negative, this encoding option means that the caller +** guarantees that z array contains at least n+1 bytes and that the z&#91;n&#93; +** byte has a value of zero. +** This option gives the same output as SQLITE_UTF8, but can be more efficient +** by avoiding the need to make a copy of the input string, in some cases. +** However, if z is allocated to hold fewer than n+1 bytes or if the +** z&#91;n&#93; byte is not zero, undefined behavior may result. +** </dl> */ #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */ #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */ @@ -5847,6 +6251,7 @@ SQLITE_API int sqlite3_create_window_function( #define SQLITE_UTF16 4 /* Use native byte order */ #define SQLITE_ANY 5 /* Deprecated */ #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ +#define SQLITE_UTF8_ZT 16 /* Zero-terminated UTF8 */ /* ** CAPI3REF: Function Flags @@ -5930,7 +6335,7 @@ SQLITE_API int sqlite3_create_window_function( ** result. ** Every function that invokes [sqlite3_result_subtype()] should have this ** property. If it does not, then the call to [sqlite3_result_subtype()] -** might become a no-op if the function is used as term in an +** might become a no-op if the function is used as a term in an ** [expression index]. On the other hand, SQL functions that never invoke ** [sqlite3_result_subtype()] should avoid setting this property, as the ** purpose of this property is to disable certain optimizations that are @@ -6057,7 +6462,7 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6 ** sqlite3_value_nochange(X) interface returns true if and only if ** the column corresponding to X is unchanged by the UPDATE operation ** that the xUpdate method call was invoked to implement and if -** and the prior [xColumn] method call that was invoked to extracted +** the prior [xColumn] method call that was invoked to extract ** the value for that column returned without setting a result (probably ** because it queried [sqlite3_vtab_nochange()] and found that the column ** was unchanging). ^Within an [xUpdate] method, any value for which @@ -6081,26 +6486,22 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6 ** the SQL function that supplied the [sqlite3_value*] parameters. ** ** As long as the input parameter is correct, these routines can only -** fail if an out-of-memory error occurs during a format conversion. -** Only the following subset of interfaces are subject to out-of-memory -** errors: -** -** <ul> -** <li> sqlite3_value_blob() -** <li> sqlite3_value_text() -** <li> sqlite3_value_text16() -** <li> sqlite3_value_text16le() -** <li> sqlite3_value_text16be() -** <li> sqlite3_value_bytes() -** <li> sqlite3_value_bytes16() -** </ul> -** +** fail if an out-of-memory error occurs while trying to do a +** UTF8&rarr;UTF16 or UTF16&rarr;UTF8 conversion. ** If an out-of-memory error occurs, then the return value from these ** routines is the same as if the column had contained an SQL NULL value. -** Valid SQL NULL returns can be distinguished from out-of-memory errors -** by invoking the [sqlite3_errcode()] immediately after the suspect +** If the input sqlite3_value was not obtained from [sqlite3_value_dup()], +** then valid SQL NULL returns can also be distinguished from +** out-of-memory errors after extracting the value +** by invoking the [sqlite3_errcode()] immediately after the suspicious ** return value is obtained and before any ** other SQLite interface is called on the same [database connection]. +** If the input sqlite3_value was obtained from sqlite3_value_dup() then +** it is disconnected from the database connection and so sqlite3_errcode() +** will not work. +** In that case, the only way to distinguish an out-of-memory +** condition from a true SQL NULL is to invoke sqlite3_value_type() on the +** input to see if it is NULL prior to trying to extract the value. */ SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); SQLITE_API double sqlite3_value_double(sqlite3_value*); @@ -6127,7 +6528,8 @@ SQLITE_API int sqlite3_value_frombind(sqlite3_value*); ** of the value X, assuming that X has type TEXT.)^ If sqlite3_value_type(X) ** returns something other than SQLITE_TEXT, then the return value from ** sqlite3_value_encoding(X) is meaningless. ^Calls to -** [sqlite3_value_text(X)], [sqlite3_value_text16(X)], [sqlite3_value_text16be(X)], +** [sqlite3_value_text(X)], [sqlite3_value_text16(X)], +** [sqlite3_value_text16be(X)], ** [sqlite3_value_text16le(X)], [sqlite3_value_bytes(X)], or ** [sqlite3_value_bytes16(X)] might change the encoding of the value X and ** thus change the return from subsequent calls to sqlite3_value_encoding(X). @@ -6163,7 +6565,7 @@ SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*); ** METHOD: sqlite3_value ** ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value] -** object D and returns a pointer to that copy. ^The [sqlite3_value] returned +** object V and returns a pointer to that copy. ^The [sqlite3_value] returned ** is a [protected sqlite3_value] object even if the input is not. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a ** memory allocation fails. ^If V is a [pointer value], then the result @@ -6201,7 +6603,7 @@ SQLITE_API void sqlite3_value_free(sqlite3_value*); ** allocation error occurs. ** ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is -** determined by the N parameter on first successful call. Changing the +** determined by the N parameter on the first successful call. Changing the ** value of N in any subsequent call to sqlite3_aggregate_context() within ** the same aggregate function instance will not resize the memory ** allocation.)^ Within the xFinal callback, it is customary to set @@ -6258,17 +6660,17 @@ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); ** query execution, under some circumstances the associated auxiliary data ** might be preserved. An example of where this might be useful is in a ** regular-expression matching function. The compiled version of the regular -** expression can be stored as auxiliary data associated with the pattern string. -** Then as long as the pattern string remains the same, +** expression can be stored as auxiliary data associated with the pattern +** string. Then as long as the pattern string remains the same, ** the compiled regular expression can be reused on multiple ** invocations of the same function. ** -** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the auxiliary data -** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument -** value to the application-defined function. ^N is zero for the left-most -** function argument. ^If there is no auxiliary data -** associated with the function argument, the sqlite3_get_auxdata(C,N) interface -** returns a NULL pointer. +** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the auxiliary +** data associated by the sqlite3_set_auxdata(C,N,P,X) function with the +** Nth argument value to the application-defined function. ^N is zero +** for the left-most function argument. ^If there is no auxiliary data +** associated with the function argument, the sqlite3_get_auxdata(C,N) +** interface returns a NULL pointer. ** ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as auxiliary data for the ** N-th argument of the application-defined function. ^Subsequent @@ -6330,6 +6732,7 @@ SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(voi ** or a NULL pointer if there were no prior calls to ** sqlite3_set_clientdata() with the same values of D and N. ** Names are compared using strcmp() and are thus case sensitive. +** It returns 0 on success and SQLITE_NOMEM on allocation failure. ** ** If P and X are both non-NULL, then the destructor X is invoked with ** argument P on the first of the following occurrences: @@ -6351,10 +6754,14 @@ SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(voi ** ** There is no limit (other than available memory) on the number of different ** client data pointers (with different names) that can be attached to a -** single database connection. However, the implementation is optimized -** for the case of having only one or two different client data names. -** Applications and wrapper libraries are discouraged from using more than -** one client data name each. +** single database connection. However, the current implementation stores +** the content on a linked list. Insert and retrieval performance will +** be proportional to the number of entries. The design use case, and +** the use case for which the implementation is optimized, is +** that an application will store only small number of client data names, +** typically just one or two. This interface is not intended to be a +** generalized key/value store for thousands or millions of keys. It +** will work for that, but performance might be disappointing. ** ** There is no way to enumerate the client data pointers ** associated with a database connection. The N parameter can be thought @@ -6363,7 +6770,7 @@ SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(voi ** ** Security Warning: These interfaces should not be exposed in scripting ** languages or in other circumstances where it might be possible for an -** an attacker to invoke them. Any agent that can invoke these interfaces +** attacker to invoke them. Any agent that can invoke these interfaces ** can probably also take control of the process. ** ** Database connection client data is only available for SQLite @@ -6412,7 +6819,11 @@ typedef void (*sqlite3_destructor_type)(void*); ** ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N) ** interfaces set the result of the application-defined function to be -** a BLOB containing all zero bytes and N bytes in size. +** a BLOB containing all zero bytes and N bytes in size. The +** zeroblob64(C,N) interface returns a [result code], which is normally +** [SQLITE_OK] but might be some other value if the requested operation +** could not be complete, for example if insufficient memory is available +** or if the value of N is out of range. ** ** ^The sqlite3_result_double() interface sets the result from ** an application-defined function to be a floating point value specified @@ -6462,10 +6873,14 @@ typedef void (*sqlite3_destructor_type)(void*); ** set the return value of the application-defined function to be ** a text string which is represented as UTF-8, UTF-16 native byte order, ** UTF-16 little endian, or UTF-16 big endian, respectively. -** ^The sqlite3_result_text64() interface sets the return value of an +** ^The sqlite3_result_text64(C,Z,N,D,E) interface sets the return value of an ** application-defined function to be a text string in an encoding -** specified by the fifth (and last) parameter, which must be one -** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]. +** specified the E parameter, which must be one +** of [SQLITE_UTF8], [SQLITE_UTF8_ZT], [SQLITE_UTF16], [SQLITE_UTF16BE], +** or [SQLITE_UTF16LE]. ^The special value [SQLITE_UTF8_ZT] means that +** the result text is both UTF-8 and zero-terminated. In other words, +** SQLITE_UTF8_ZT means that the Z array holds at least N+1 bytes and that +** the Z&#91;N&#93; is zero. ** ^SQLite takes the text result from the application from ** the 2nd parameter of the sqlite3_result_text* interfaces. ** ^If the 3rd parameter to any of the sqlite3_result_text* interfaces @@ -6477,7 +6892,7 @@ typedef void (*sqlite3_destructor_type)(void*); ** pointed to by the 2nd parameter are taken as the application-defined ** function result. If the 3rd parameter is non-negative, then it ** must be the byte offset into the string where the NUL terminator would -** appear if the string where NUL terminated. If any NUL characters occur +** appear if the string were NUL terminated. If any NUL characters occur ** in the string at a byte offset that is less than the value of the 3rd ** parameter, then the resulting string will contain embedded NULs and the ** result of expressions operating on strings with embedded NULs is undefined. @@ -6535,7 +6950,7 @@ typedef void (*sqlite3_destructor_type)(void*); ** string and preferably a string literal. The sqlite3_result_pointer() ** routine is part of the [pointer passing interface] added for SQLite 3.20.0. ** -** If these routines are called from within the different thread +** If these routines are called from within a different thread ** than the one containing the application-defined function that received ** the [sqlite3_context] pointer, the results are undefined. */ @@ -6552,7 +6967,7 @@ SQLITE_API void sqlite3_result_int(sqlite3_context*, int); SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); SQLITE_API void sqlite3_result_null(sqlite3_context*); SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64, +SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char *z, sqlite3_uint64 n, void(*)(void*), unsigned char encoding); SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); @@ -6941,7 +7356,7 @@ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); ** METHOD: sqlite3 ** ** ^The sqlite3_db_name(D,N) interface returns a pointer to the schema name -** for the N-th database on database connection D, or a NULL pointer of N is +** for the N-th database on database connection D, or a NULL pointer if N is ** out of range. An N value of 0 means the main database file. An N of 1 is ** the "temp" schema. Larger values of N correspond to various ATTACH-ed ** databases. @@ -7036,7 +7451,7 @@ SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema); ** <dd>The SQLITE_TXN_READ state means that the database is currently ** in a read transaction. Content has been read from the database file ** but nothing in the database file has changed. The transaction state -** will advanced to SQLITE_TXN_WRITE if any changes occur and there are +** will be advanced to SQLITE_TXN_WRITE if any changes occur and there are ** no other conflicting concurrent write transactions. The transaction ** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or ** [COMMIT].</dd> @@ -7045,7 +7460,7 @@ SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema); ** <dd>The SQLITE_TXN_WRITE state means that the database is currently ** in a write transaction. Content has been written to the database file ** but has not yet committed. The transaction state will change to -** to SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd> +** SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd> */ #define SQLITE_TXN_NONE 0 #define SQLITE_TXN_READ 1 @@ -7196,6 +7611,8 @@ SQLITE_API int sqlite3_autovacuum_pages( ** ** ^The second argument is a pointer to the function to invoke when a ** row is updated, inserted or deleted in a rowid table. +** ^The update hook is disabled by invoking sqlite3_update_hook() +** with a NULL pointer as the second parameter. ** ^The first argument to the callback is a copy of the third argument ** to sqlite3_update_hook(). ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], @@ -7324,7 +7741,7 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*); ** CAPI3REF: Impose A Limit On Heap Size ** ** These interfaces impose limits on the amount of heap memory that will be -** by all database connections within a single process. +** used by all database connections within a single process. ** ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the ** soft limit on the amount of heap memory that may be allocated by SQLite. @@ -7382,7 +7799,7 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*); ** </ul>)^ ** ** The circumstances under which SQLite will enforce the heap limits may -** changes in future releases of SQLite. +** change in future releases of SQLite. */ SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N); @@ -7489,7 +7906,7 @@ SQLITE_API int sqlite3_table_column_metadata( ** ^The sqlite3_load_extension() interface attempts to load an ** [SQLite extension] library contained in the file zFile. If ** the file cannot be loaded directly, attempts are made to load -** with various operating-system specific extensions added. +** with various operating-system specific filename extensions added. ** So for example, if "samplelib" cannot be loaded, then names like ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might ** be tried also. @@ -7497,10 +7914,10 @@ SQLITE_API int sqlite3_table_column_metadata( ** ^The entry point is zProc. ** ^(zProc may be 0, in which case SQLite will try to come up with an ** entry point name on its own. It first tries "sqlite3_extension_init". -** If that does not work, it constructs a name "sqlite3_X_init" where the -** X is consists of the lower-case equivalent of all ASCII alphabetic -** characters in the filename from the last "/" to the first following -** "." and omitting any initial "lib".)^ +** If that does not work, it tries names of the form "sqlite3_X_init" +** where X consists of the lower-case equivalent of all ASCII alphabetic +** characters or all ASCII alphanumeric characters in the filename from +** the last "/" to the first following "." and omitting any initial "lib".)^ ** ^The sqlite3_load_extension() interface returns ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. ** ^If an error occurs and pzErrMsg is not 0, then the @@ -7569,12 +7986,12 @@ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); ** ^(Even though the function prototype shows that xEntryPoint() takes ** no arguments and returns void, SQLite invokes xEntryPoint() with three ** arguments and expects an integer result as if the signature of the -** entry point where as follows: +** entry point were as follows: ** ** <blockquote><pre> ** &nbsp; int xEntryPoint( ** &nbsp; sqlite3 *db, -** &nbsp; const char **pzErrMsg, +** &nbsp; char **pzErrMsg, ** &nbsp; const struct sqlite3_api_routines *pThunk ** &nbsp; ); ** </pre></blockquote>)^ @@ -7733,7 +8150,7 @@ struct sqlite3_module { ** virtual table and might not be checked again by the byte code.)^ ^(The ** aConstraintUsage[].omit flag is an optimization hint. When the omit flag ** is left in its default setting of false, the constraint will always be -** checked separately in byte code. If the omit flag is change to true, then +** checked separately in byte code. If the omit flag is changed to true, then ** the constraint may or may not be checked in byte code. In other words, ** when the omit flag is true there is no guarantee that the constraint will ** not be checked again using byte code.)^ @@ -7759,7 +8176,7 @@ struct sqlite3_module { ** The xBestIndex method may optionally populate the idxFlags field with a ** mask of SQLITE_INDEX_SCAN_* flags. One such flag is ** [SQLITE_INDEX_SCAN_HEX], which if set causes the [EXPLAIN QUERY PLAN] -** output to show the idxNum has hex instead of as decimal. Another flag is +** output to show the idxNum as hex instead of as decimal. Another flag is ** SQLITE_INDEX_SCAN_UNIQUE, which if set indicates that the query plan will ** return at most one row. ** @@ -7900,7 +8317,7 @@ struct sqlite3_index_info { ** the implementation of the [virtual table module]. ^The fourth ** parameter is an arbitrary client data pointer that is passed through ** into the [xCreate] and [xConnect] methods of the virtual table module -** when a new virtual table is be being created or reinitialized. +** when a new virtual table is being created or reinitialized. ** ** ^The sqlite3_create_module_v2() interface has a fifth parameter which ** is a pointer to a destructor for the pClientData. ^SQLite will @@ -8065,7 +8482,7 @@ typedef struct sqlite3_blob sqlite3_blob; ** in *ppBlob. Otherwise an [error code] is returned and, unless the error ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided ** the API is not misused, it is always safe to call [sqlite3_blob_close()] -** on *ppBlob after this function it returns. +** on *ppBlob after this function returns. ** ** This function fails with SQLITE_ERROR if any of the following are true: ** <ul> @@ -8185,7 +8602,7 @@ SQLITE_API int sqlite3_blob_close(sqlite3_blob *); ** ** ^Returns the size in bytes of the BLOB accessible via the ** successfully opened [BLOB handle] in its only argument. ^The -** incremental blob I/O routines can only read or overwriting existing +** incremental blob I/O routines can only read or overwrite existing ** blob content; they cannot change the size of a blob. ** ** This routine only works on a [BLOB handle] which has been created @@ -8324,18 +8741,11 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix ** and Windows. ** -** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor -** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex -** implementation is included with the library. In this case the -** application must supply a custom mutex implementation using the -** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function -** before calling sqlite3_initialize() or any other public sqlite3_ -** function that calls sqlite3_initialize(). ** ** ^The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc() ** routine returns NULL if it is unable to allocate the requested -** mutex. The argument to sqlite3_mutex_alloc() must one of these +** mutex. The argument to sqlite3_mutex_alloc() must be one of these ** integer constants: ** ** <ul> @@ -8568,7 +8978,7 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); ** CAPI3REF: Retrieve the mutex for a database connection ** METHOD: sqlite3 ** -** ^This interface returns a pointer the [sqlite3_mutex] object that +** ^This interface returns a pointer to the [sqlite3_mutex] object that ** serializes access to the [database connection] given in the argument ** when the [threading mode] is Serialized. ** ^If the [threading mode] is Single-thread or Multi-thread then this @@ -8685,13 +9095,14 @@ SQLITE_API int sqlite3_test_control(int op, ...); #define SQLITE_TESTCTRL_TUNE 32 #define SQLITE_TESTCTRL_LOGEST 33 #define SQLITE_TESTCTRL_USELONGDOUBLE 34 /* NOT USED */ +#define SQLITE_TESTCTRL_ATOF 34 #define SQLITE_TESTCTRL_LAST 34 /* Largest TESTCTRL */ /* ** CAPI3REF: SQL Keyword Checking ** ** These routines provide access to the set of SQL language keywords -** recognized by SQLite. Applications can uses these routines to determine +** recognized by SQLite. Applications can use these routines to determine ** whether or not a specific identifier needs to be escaped (for example, ** by enclosing in double-quotes) so as not to confuse the parser. ** @@ -8750,8 +9161,8 @@ SQLITE_API int sqlite3_keyword_check(const char*,int); ** <li> ^The sqlite3_str object is created using [sqlite3_str_new()]. ** <li> ^Text is appended to the sqlite3_str object using various ** methods, such as [sqlite3_str_appendf()]. -** <li> ^The sqlite3_str object is destroyed and the string it created -** is returned using the [sqlite3_str_finish()] interface. +** <li> The sqlite3_str object is destroyed and the string it created +** is returned using [sqlite3_str_finish()] or [sqlite3_result_str()]. ** </ol> */ typedef struct sqlite3_str sqlite3_str; @@ -8793,17 +9204,56 @@ SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*); ** pass the returned value to [sqlite3_free()] to avoid a memory leak. ** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any ** errors were encountered during construction of the string. ^The -** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the +** [sqlite3_str_finish(X)] interface might also return a NULL pointer if the ** string in [sqlite3_str] object X is zero bytes long. +** +** ^The [sqlite3_str_free(X)] interface destroys both the sqlite3_str object +** X and the string content it contains. Calling sqlite3_str_free(X) is +** the equivalent of calling [sqlite3_free](sqlite3_str_finish(X)). */ SQLITE_API char *sqlite3_str_finish(sqlite3_str*); +SQLITE_API void sqlite3_str_free(sqlite3_str*); + +/* +** CAPI3REF: Return A Dynamic String From an SQL Function +** +** The [sqlite3_result_str(C,S,F)] interface causes the +** [sqlite3_str|dynamic string] S to become the return value for the +** application-defined function or virtual table that uses +** [sqlite3_context] C. The F flag can be one of [SQLITE_COPY] +** or [SQLITE_XFER] or [SQLITE_FINISH]. +** +** If the dynamic string is invalid or incomplete due to an out-of-memory +** or string-too-large error, then this routine transfers that error +** over to the SQL function. +** +** If the F argument is SQLITE_COPY, then a copy of the dynamic string +** content is made and the dynamic string object is unchanged. +** If the F argument is SQLITE_XFER, then ownership of the content +** in the dynamic is transferred to the SQL function (via a pointer copy +** rather than a string copy) and the dynamic string is reset to an +** empty string. The SQLITE_FINISH value for F works like SQLITE_RESET +** except that it also invokes the [sqlite3_str_free(S)] destructor +** on the dynamic string object. +*/ +SQLITE_API void sqlite3_result_str(sqlite3_context*, sqlite3_str*, int); + +/* +** CAPI3REF: Control Flags For sqlite3_result_str() +** +** The following integers can be used as the third "F" argument +** to [sqlite3_result_str(C,S,F)]. +*/ +#define SQLITE_COPY 0 /* Results copied. Dynamic string unchanged */ +#define SQLITE_XFER 1 /* Results transfered. Dynamic string reset */ +#define SQLITE_FINISH 2 /* Like SQLITE_XFER, plus dynamic string freed */ /* ** CAPI3REF: Add Content To A Dynamic String ** METHOD: sqlite3_str ** -** These interfaces add content to an sqlite3_str object previously obtained -** from [sqlite3_str_new()]. +** These interfaces add or remove content to an sqlite3_str object +** previously obtained from [sqlite3_str_new()]. ** ** ^The [sqlite3_str_appendf(X,F,...)] and ** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf] @@ -8826,6 +9276,10 @@ SQLITE_API char *sqlite3_str_finish(sqlite3_str*); ** ^The [sqlite3_str_reset(X)] method resets the string under construction ** inside [sqlite3_str] object X back to zero bytes in length. ** +** ^The [sqlite3_str_truncate(X,N)] method changes the length of the string +** under construction to be N bytes or less. This routine is a no-op if +** N is negative or if the string is already N bytes or smaller in size. +** ** These methods do not return a result code. ^If an error occurs, that fact ** is recorded in the [sqlite3_str] object and can be recovered by a ** subsequent call to [sqlite3_str_errcode(X)]. @@ -8836,6 +9290,7 @@ SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N); SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn); SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C); SQLITE_API void sqlite3_str_reset(sqlite3_str*); +SQLITE_API void sqlite3_str_truncate(sqlite3_str*,int N); /* ** CAPI3REF: Status Of A Dynamic String @@ -8859,7 +9314,7 @@ SQLITE_API void sqlite3_str_reset(sqlite3_str*); ** content of the dynamic string under construction in X. The value ** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X ** and might be freed or altered by any subsequent method on the same -** [sqlite3_str] object. Applications must not used the pointer returned +** [sqlite3_str] object. Applications must not use the pointer returned by ** [sqlite3_str_value(X)] after any subsequent method call on the same ** object. ^Applications may change the content of the string returned ** by [sqlite3_str_value(X)] as long as they do not write into any bytes @@ -8945,7 +9400,7 @@ SQLITE_API int sqlite3_status64( ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] ** buffer and where forced to overflow to [sqlite3_malloc()]. The ** returned value includes allocations that overflowed because they -** where too large (they were larger than the "sz" parameter to +** were too large (they were larger than the "sz" parameter to ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because ** no space was left in the page cache.</dd>)^ ** @@ -9004,9 +9459,18 @@ SQLITE_API int sqlite3_status64( ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a ** non-zero [error code] on failure. ** +** ^The sqlite3_db_status64(D,O,C,H,R) routine works exactly the same +** way as sqlite3_db_status(D,O,C,H,R) routine except that the C and H +** parameters are pointer to 64-bit integers (type: sqlite3_int64) instead +** of pointers to 32-bit integers, which allows larger status values +** to be returned. If a status value exceeds 2,147,483,647 then +** sqlite3_db_status() will truncate the value whereas sqlite3_db_status64() +** will return the full value. +** ** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. */ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); +SQLITE_API int sqlite3_db_status64(sqlite3*,int,sqlite3_int64*,sqlite3_int64*,int); /* ** CAPI3REF: Status Parameters for database connections @@ -9029,28 +9493,29 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt> ** <dd>This parameter returns the number of malloc attempts that were ** satisfied using lookaside memory. Only the high-water value is meaningful; -** the current value is always zero.)^ +** the current value is always zero.</dd>)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt> -** <dd>This parameter returns the number malloc attempts that might have +** <dd>This parameter returns the number of malloc attempts that might have ** been satisfied using lookaside memory but failed due to the amount of ** memory requested being larger than the lookaside slot size. ** Only the high-water value is meaningful; -** the current value is always zero.)^ +** the current value is always zero.</dd>)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt> -** <dd>This parameter returns the number malloc attempts that might have +** <dd>This parameter returns the number of malloc attempts that might have ** been satisfied using lookaside memory but failed due to all lookaside ** memory already being in use. ** Only the high-water value is meaningful; -** the current value is always zero.)^ +** the current value is always zero.</dd>)^ ** ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt> ** <dd>This parameter returns the approximate number of bytes of heap ** memory used by all pager caches associated with the database connection.)^ ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. +** </dd> ** ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt> @@ -9059,10 +9524,10 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** memory used by that pager cache is divided evenly between the attached ** connections.)^ In other words, if none of the pager caches associated ** with the database connection are shared, this request returns the same -** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are +** value as DBSTATUS_CACHE_USED. Or, if one or more of the pager caches are ** shared, the value returned by this call will be smaller than that returned ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with -** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0. +** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.</dd> ** ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt> ** <dd>This parameter returns the approximate number of bytes of heap @@ -9072,6 +9537,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** schema memory is shared with other database connections due to ** [shared cache mode] being enabled. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. +** </dd> ** ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt> ** <dd>This parameter returns the approximate number of bytes of heap @@ -9101,6 +9567,10 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** If an IO or other error occurs while writing a page to disk, the effect ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. +** <p> +** ^(There is overlap between the quantities measured by this parameter +** (SQLITE_DBSTATUS_CACHE_WRITE) and SQLITE_DBSTATUS_TEMPBUF_SPILL. +** Resetting one will reduce the other.)^ ** </dd> ** ** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt> @@ -9108,7 +9578,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** been written to disk in the middle of a transaction due to the page ** cache overflowing. Transactions are more efficient if they are written ** to disk all at once. When pages spill mid-transaction, that introduces -** additional overhead. This parameter can be used help identify +** additional overhead. This parameter can be used to help identify ** inefficiencies that can be resolved by increasing the cache size. ** </dd> ** @@ -9116,6 +9586,18 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** <dd>This parameter returns zero for the current value if and only if ** all foreign key constraints (deferred or immediate) have been ** resolved.)^ ^The highwater mark is always 0. +** +** [[SQLITE_DBSTATUS_TEMPBUF_SPILL] ^(<dt>SQLITE_DBSTATUS_TEMPBUF_SPILL</dt> +** <dd>^(This parameter returns the number of bytes written to temporary +** files on disk that could have been kept in memory had sufficient memory +** been available. This value includes writes to intermediate tables that +** are part of complex queries, external sorts that spill to disk, and +** writes to TEMP tables.)^ +** ^The highwater mark is always 0. +** <p> +** ^(There is overlap between the quantities measured by this parameter +** (SQLITE_DBSTATUS_TEMPBUF_SPILL) and SQLITE_DBSTATUS_CACHE_WRITE. +** Resetting one will reduce the other.)^ ** </dd> ** </dl> */ @@ -9132,7 +9614,8 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r #define SQLITE_DBSTATUS_DEFERRED_FKS 10 #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11 #define SQLITE_DBSTATUS_CACHE_SPILL 12 -#define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */ +#define SQLITE_DBSTATUS_TEMPBUF_SPILL 13 +#define SQLITE_DBSTATUS_MAX 13 /* Largest defined DBSTATUS */ /* @@ -9179,13 +9662,13 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt> ** <dd>^This is the number of sort operations that have occurred. ** A non-zero value in this counter may indicate an opportunity to -** improvement performance through careful use of indices.</dd> +** improve performance through careful use of indices.</dd> ** ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt> ** <dd>^This is the number of rows inserted into transient indices that ** were created automatically in order to help joins run faster. ** A non-zero value in this counter may indicate an opportunity to -** improvement performance by adding permanent indices that do not +** improve performance by adding permanent indices that do not ** need to be reinitialized each time the statement is run.</dd> ** ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt> @@ -9194,19 +9677,19 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); ** to 2147483647. The number of virtual machine operations can be ** used as a proxy for the total work done by the prepared statement. ** If the number of virtual machine operations exceeds 2147483647 -** then the value returned by this statement status code is undefined. +** then the value returned by this statement status code is undefined.</dd> ** ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt> ** <dd>^This is the number of times that the prepare statement has been ** automatically regenerated due to schema changes or changes to -** [bound parameters] that might affect the query plan. +** [bound parameters] that might affect the query plan.</dd> ** ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt> ** <dd>^This is the number of times that the prepared statement has ** been run. A single "run" for the purposes of this counter is one ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()]. ** The counter is incremented on the first [sqlite3_step()] call of each -** cycle. +** cycle.</dd> ** ** [[SQLITE_STMTSTATUS_FILTER_MISS]] ** [[SQLITE_STMTSTATUS_FILTER HIT]] @@ -9216,7 +9699,7 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); ** step was bypassed because a Bloom filter returned not-found. The ** corresponding SQLITE_STMTSTATUS_FILTER_MISS value is the number of ** times that the Bloom filter returned a find, and thus the join step -** had to be processed as normal. +** had to be processed as normal.</dd> ** ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt> ** <dd>^This is the approximate number of bytes of heap memory @@ -9321,9 +9804,9 @@ struct sqlite3_pcache_page { ** SQLite will typically create one cache instance for each open database file, ** though this is not guaranteed. ^The ** first parameter, szPage, is the size in bytes of the pages that must -** be allocated by the cache. ^szPage will always a power of two. ^The +** be allocated by the cache. ^szPage will always be a power of two. ^The ** second parameter szExtra is a number of bytes of extra storage -** associated with each page cache entry. ^The szExtra parameter will +** associated with each page cache entry. ^The szExtra parameter will be ** a number less than 250. SQLite will use the ** extra szExtra bytes on each page to store metadata about the underlying ** database page on disk. The value passed into szExtra depends @@ -9331,17 +9814,17 @@ struct sqlite3_pcache_page { ** ^The third argument to xCreate(), bPurgeable, is true if the cache being ** created will be used to cache database pages of a file stored on disk, or ** false if it is used for an in-memory database. The cache implementation -** does not have to do anything special based with the value of bPurgeable; +** does not have to do anything special based upon the value of bPurgeable; ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will ** never invoke xUnpin() except to deliberately delete a page. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to ** false will always have the "discard" flag set to true. -** ^Hence, a cache created with bPurgeable false will +** ^Hence, a cache created with bPurgeable set to false will ** never contain any unpinned pages. ** ** [[the xCachesize() page cache method]] ** ^(The xCachesize() method may be called at any time by SQLite to set the -** suggested maximum cache-size (number of pages stored by) the cache +** suggested maximum cache-size (number of pages stored) for the cache ** instance passed as the first argument. This is the value configured using ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable ** parameter, the implementation is not required to do anything with this @@ -9368,12 +9851,12 @@ struct sqlite3_pcache_page { ** implementation must return a pointer to the page buffer with its content ** intact. If the requested page is not already in the cache, then the ** cache implementation should use the value of the createFlag -** parameter to help it determined what action to take: +** parameter to help it determine what action to take: ** ** <table border=1 width=85% align=center> ** <tr><th> createFlag <th> Behavior when page is not already in cache ** <tr><td> 0 <td> Do not allocate a new page. Return NULL. -** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so. +** <tr><td> 1 <td> Allocate a new page if it is easy and convenient to do so. ** Otherwise return NULL. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return ** NULL if allocating a new page is effectively impossible. @@ -9390,7 +9873,7 @@ struct sqlite3_pcache_page { ** as its second argument. If the third parameter, discard, is non-zero, ** then the page must be evicted from the cache. ** ^If the discard parameter is -** zero, then the page may be discarded or retained at the discretion of +** zero, then the page may be discarded or retained at the discretion of the ** page cache implementation. ^The page cache implementation ** may choose to evict unpinned pages at any time. ** @@ -9408,7 +9891,7 @@ struct sqlite3_pcache_page { ** When SQLite calls the xTruncate() method, the cache must discard all ** existing cache entries with page numbers (keys) greater than or equal ** to the value of the iLimit parameter passed to xTruncate(). If any -** of these pages are pinned, they are implicitly unpinned, meaning that +** of these pages are pinned, they become implicitly unpinned, meaning that ** they can be safely discarded. ** ** [[the xDestroy() page cache method]] @@ -9588,7 +10071,7 @@ typedef struct sqlite3_backup sqlite3_backup; ** external process or via a database connection other than the one being ** used by the backup operation, then the backup will be automatically ** restarted by the next call to sqlite3_backup_step(). ^If the source -** database is modified by the using the same database connection as is used +** database is modified by using the same database connection as is used ** by the backup operation, then the backup database is automatically ** updated at the same time. ** @@ -9605,7 +10088,7 @@ typedef struct sqlite3_backup sqlite3_backup; ** and may not be used following a call to sqlite3_backup_finish(). ** ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no -** sqlite3_backup_step() errors occurred, regardless or whether or not +** sqlite3_backup_step() errors occurred, regardless of whether or not ** sqlite3_backup_step() completed. ** ^If an out-of-memory condition or IO error occurred during any prior ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then @@ -9707,7 +10190,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** application receives an SQLITE_LOCKED error, it may call the ** sqlite3_unlock_notify() method with the blocked connection handle as ** the first argument to register for a callback that will be invoked -** when the blocking connections current transaction is concluded. ^The +** when the blocking connection's current transaction is concluded. ^The ** callback is invoked from within the [sqlite3_step] or [sqlite3_close] ** call that concludes the blocking connection's transaction. ** @@ -9727,7 +10210,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** blocked connection already has a registered unlock-notify callback, ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is ** called with a NULL pointer as its second argument, then any existing -** unlock-notify callback is canceled. ^The blocked connections +** unlock-notify callback is canceled. ^The blocked connection's ** unlock-notify callback may also be canceled by closing the blocked ** connection using [sqlite3_close()]. ** @@ -9897,7 +10380,7 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); ** is the number of pages currently in the write-ahead log file, ** including those that were just committed. ** -** The callback function should normally return [SQLITE_OK]. ^If an error +** ^The callback function should normally return [SQLITE_OK]. ^If an error ** code is returned, that error will propagate back up through the ** SQLite code base to cause the statement that provoked the callback ** to report an error, though the commit will have still occurred. If the @@ -9905,13 +10388,26 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); ** that does not correspond to any valid SQLite error code, the results ** are undefined. ** -** A single database handle may have at most a single write-ahead log callback -** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any -** previously registered write-ahead log callback. ^The return value is -** a copy of the third parameter from the previous call, if any, or 0. -** ^Note that the [sqlite3_wal_autocheckpoint()] interface and the -** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will -** overwrite any prior [sqlite3_wal_hook()] settings. +** ^A single database handle may have at most a single write-ahead log +** callback registered at one time. ^Calling [sqlite3_wal_hook()] +** replaces the default behavior or previously registered write-ahead +** log callback. +** +** ^The return value is a copy of the third parameter from the +** previous call, if any, or 0. +** +** ^The [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and +** will overwrite any prior [sqlite3_wal_hook()] settings. +** +** ^If a write-ahead log callback is set using this function then +** [sqlite3_wal_checkpoint_v2()] or [PRAGMA wal_checkpoint] +** should be invoked periodically to keep the write-ahead log file +** from growing without bound. +** +** ^Passing a NULL pointer for the callback disables automatic +** checkpointing entirely. To re-enable the default behavior, call +** sqlite3_wal_autocheckpoint(db,1000) or use [PRAGMA wal_checkpoint]. */ SQLITE_API void *sqlite3_wal_hook( sqlite3*, @@ -9928,7 +10424,7 @@ SQLITE_API void *sqlite3_wal_hook( ** to automatically [checkpoint] ** after committing a transaction if there are N or ** more frames in the [write-ahead log] file. ^Passing zero or -** a negative value as the nFrame parameter disables automatic +** a negative value as the N parameter disables automatic ** checkpoints entirely. ** ** ^The callback registered by this function replaces any existing callback @@ -9944,9 +10440,10 @@ SQLITE_API void *sqlite3_wal_hook( ** ** ^Every new [database connection] defaults to having the auto-checkpoint ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] -** pages. The use of this interface -** is only necessary if the default setting is found to be suboptimal -** for a particular application. +** pages. +** +** ^The use of this interface is only necessary if the default setting +** is found to be suboptimal for a particular application. */ SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); @@ -10011,6 +10508,11 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the ** addition that it also truncates the log file to zero bytes just prior ** to a successful return. +** +** <dt>SQLITE_CHECKPOINT_NOOP<dd> +** ^This mode always checkpoints zero frames. The only reason to invoke +** a NOOP checkpoint is to access the values returned by +** sqlite3_wal_checkpoint_v2() via output parameters *pnLog and *pnCkpt. ** </dl> ** ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in @@ -10081,6 +10583,7 @@ SQLITE_API int sqlite3_wal_checkpoint_v2( ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the ** meaning of each of these checkpoint modes. */ +#define SQLITE_CHECKPOINT_NOOP -1 /* Do no work at all */ #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */ #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */ #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for readers */ @@ -10125,7 +10628,7 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); ** support constraints. In this configuration (which is the default) if ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been -** specified as part of the users SQL statement, regardless of the actual +** specified as part of the user's SQL statement, regardless of the actual ** ON CONFLICT mode specified. ** ** If X is non-zero, then the virtual table implementation guarantees @@ -10159,7 +10662,7 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); ** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt> ** <dd>Calls of the form ** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the -** the [xConnect] or [xCreate] methods of a [virtual table] implementation +** [xConnect] or [xCreate] methods of a [virtual table] implementation ** identify that virtual table as being safe to use from within triggers ** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the ** virtual table can do no serious harm even if it is controlled by a @@ -10318,7 +10821,8 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int); ** <tr> ** <td valign="top">sqlite3_vtab_distinct() return value ** <td valign="top">Rows are returned in aOrderBy order -** <td valign="top">Rows with the same value in all aOrderBy columns are adjacent +** <td valign="top">Rows with the same value in all aOrderBy columns are +** adjacent ** <td valign="top">Duplicates over all colUsed columns may be omitted ** <tr><td>0<td>yes<td>yes<td>no ** <tr><td>1<td>no<td>yes<td>no @@ -10327,8 +10831,8 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int); ** </table> ** ** ^For the purposes of comparing virtual table output values to see if the -** values are same value for sorting purposes, two NULL values are considered -** to be the same. In other words, the comparison operator is "IS" +** values are the same value for sorting purposes, two NULL values are +** considered to be the same. In other words, the comparison operator is "IS" ** (or "IS NOT DISTINCT FROM") and not "==". ** ** If a virtual table implementation is unable to meet the requirements @@ -10337,7 +10841,7 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int); ** ** ^A virtual table implementation is always free to return rows in any order ** it wants, as long as the "orderByConsumed" flag is not set. ^When the -** the "orderByConsumed" flag is unset, the query planner will add extra +** "orderByConsumed" flag is unset, the query planner will add extra ** [bytecode] to ensure that the final results returned by the SQL query are ** ordered correctly. The use of the "orderByConsumed" flag and the ** sqlite3_vtab_distinct() interface is merely an optimization. ^Careful @@ -10434,7 +10938,7 @@ SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle); ** sqlite3_vtab_in_next(X,P) should be one of the parameters to the ** xFilter method which invokes these routines, and specifically ** a parameter that was previously selected for all-at-once IN constraint -** processing use the [sqlite3_vtab_in()] interface in the +** processing using the [sqlite3_vtab_in()] interface in the ** [xBestIndex|xBestIndex method]. ^(If the X parameter is not ** an xFilter argument that was selected for all-at-once IN constraint ** processing, then these routines return [SQLITE_ERROR].)^ @@ -10449,7 +10953,7 @@ SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle); ** &nbsp; ){ ** &nbsp; // do something with pVal ** &nbsp; } -** &nbsp; if( rc!=SQLITE_OK ){ +** &nbsp; if( rc!=SQLITE_DONE ){ ** &nbsp; // an error has occurred ** &nbsp; } ** </pre></blockquote>)^ @@ -10489,7 +10993,7 @@ SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut); ** and only if *V is set to a value. ^The sqlite3_vtab_rhs_value(P,J,V) ** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th ** constraint is not available. ^The sqlite3_vtab_rhs_value() interface -** can return an result code other than SQLITE_OK or SQLITE_NOTFOUND if +** can return a result code other than SQLITE_OK or SQLITE_NOTFOUND if ** something goes wrong. ** ** The sqlite3_vtab_rhs_value() interface is usually only successful if @@ -10517,8 +11021,8 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value ** ** KEYWORDS: {conflict resolution mode} ** ** These constants are returned by [sqlite3_vtab_on_conflict()] to -** inform a [virtual table] implementation what the [ON CONFLICT] mode -** is for the SQL statement being evaluated. +** inform a [virtual table] implementation of the [ON CONFLICT] mode +** for the SQL statement being evaluated. ** ** Note that the [SQLITE_IGNORE] constant is also used as a potential ** return value from the [sqlite3_set_authorizer()] callback and that @@ -10558,39 +11062,39 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value ** ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt> ** <dd>^The "double" variable pointed to by the V parameter will be set to the ** query planner's estimate for the average number of rows output from each -** iteration of the X-th loop. If the query planner's estimates was accurate, +** iteration of the X-th loop. If the query planner's estimate was accurate, ** then this value will approximate the quotient NVISIT/NLOOP and the ** product of this value for all prior loops with the same SELECTID will -** be the NLOOP value for the current loop. +** be the NLOOP value for the current loop.</dd> ** ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt> ** <dd>^The "const char *" variable pointed to by the V parameter will be set ** to a zero-terminated UTF-8 string containing the name of the index or table -** used for the X-th loop. +** used for the X-th loop.</dd> ** ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt> ** <dd>^The "const char *" variable pointed to by the V parameter will be set ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN] -** description for the X-th loop. +** description for the X-th loop.</dd> ** ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECTID</dt> ** <dd>^The "int" variable pointed to by the V parameter will be set to the ** id for the X-th query plan element. The id value is unique within the ** statement. The select-id is the same value as is output in the first -** column of an [EXPLAIN QUERY PLAN] query. +** column of an [EXPLAIN QUERY PLAN] query.</dd> ** ** [[SQLITE_SCANSTAT_PARENTID]] <dt>SQLITE_SCANSTAT_PARENTID</dt> ** <dd>The "int" variable pointed to by the V parameter will be set to the -** the id of the parent of the current query element, if applicable, or +** id of the parent of the current query element, if applicable, or ** to zero if the query element has no parent. This is the same value as -** returned in the second column of an [EXPLAIN QUERY PLAN] query. +** returned in the second column of an [EXPLAIN QUERY PLAN] query.</dd> ** ** [[SQLITE_SCANSTAT_NCYCLE]] <dt>SQLITE_SCANSTAT_NCYCLE</dt> ** <dd>The sqlite3_int64 output value is set to the number of cycles, ** according to the processor time-stamp counter, that elapsed while the ** query element was being processed. This value is not available for ** all query elements - if it is unavailable the output variable is -** set to -1. +** set to -1.</dd> ** </dl> */ #define SQLITE_SCANSTAT_NLOOP 0 @@ -10621,9 +11125,9 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value ** ** a variable pointed to by the "pOut" parameter. ** ** The "flags" parameter must be passed a mask of flags. At present only -** one flag is defined - SQLITE_SCANSTAT_COMPLEX. If SQLITE_SCANSTAT_COMPLEX +** one flag is defined - [SQLITE_SCANSTAT_COMPLEX]. If SQLITE_SCANSTAT_COMPLEX ** is specified, then status information is available for all elements -** of a query plan that are reported by "EXPLAIN QUERY PLAN" output. If +** of a query plan that are reported by "[EXPLAIN QUERY PLAN]" output. If ** SQLITE_SCANSTAT_COMPLEX is not specified, then only query plan elements ** that correspond to query loops (the "SCAN..." and "SEARCH..." elements of ** the EXPLAIN QUERY PLAN output) are available. Invoking API @@ -10631,13 +11135,14 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value ** ** sqlite3_stmt_scanstatus_v2() with a zeroed flags parameter. ** ** Parameter "idx" identifies the specific query element to retrieve statistics -** for. Query elements are numbered starting from zero. A value of -1 may be -** to query for statistics regarding the entire query. ^If idx is out of range +** for. Query elements are numbered starting from zero. A value of -1 may +** retrieve statistics for the entire query. ^If idx is out of range ** - less than -1 or greater than or equal to the total number of query ** elements used to implement the statement - a non-zero value is returned and ** the variable that pOut points to is unchanged. ** -** See also: [sqlite3_stmt_scanstatus_reset()] +** See also: [sqlite3_stmt_scanstatus_reset()] and the +** [nexec and ncycle] columns of the [bytecode virtual table]. */ SQLITE_API int sqlite3_stmt_scanstatus( sqlite3_stmt *pStmt, /* Prepared statement for which info desired */ @@ -10675,7 +11180,7 @@ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); ** METHOD: sqlite3 ** ** ^If a write-transaction is open on [database connection] D when the -** [sqlite3_db_cacheflush(D)] interface invoked, any dirty +** [sqlite3_db_cacheflush(D)] interface is invoked, any dirty ** pages in the pager-cache that are not currently in use are written out ** to disk. A dirty page may be in use if a database cursor created by an ** active SQL statement is reading from it, or if it is page 1 of a database @@ -10789,8 +11294,8 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*); ** triggers; and so forth. ** ** When the [sqlite3_blob_write()] API is used to update a blob column, -** the pre-update hook is invoked with SQLITE_DELETE. This is because the -** in this case the new values are not available. In this case, when a +** the pre-update hook is invoked with SQLITE_DELETE, because +** the new values are not yet available. In this case, when a ** callback made with op==SQLITE_DELETE is actually a write using the ** sqlite3_blob_write() API, the [sqlite3_preupdate_blobwrite()] returns ** the index of the column being written. In other cases, where the @@ -10908,7 +11413,7 @@ typedef struct sqlite3_snapshot { ** The [sqlite3_snapshot_get()] interface is only available when the ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( +SQLITE_API int sqlite3_snapshot_get( sqlite3 *db, const char *zSchema, sqlite3_snapshot **ppSnapshot @@ -10957,7 +11462,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( ** The [sqlite3_snapshot_open()] interface is only available when the ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( +SQLITE_API int sqlite3_snapshot_open( sqlite3 *db, const char *zSchema, sqlite3_snapshot *pSnapshot @@ -10974,7 +11479,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( ** The [sqlite3_snapshot_free()] interface is only available when the ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. */ -SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); +SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot*); /* ** CAPI3REF: Compare the ages of two snapshot handles. @@ -11001,7 +11506,7 @@ SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); ** This interface is only available if SQLite is compiled with the ** [SQLITE_ENABLE_SNAPSHOT] option. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( +SQLITE_API int sqlite3_snapshot_cmp( sqlite3_snapshot *p1, sqlite3_snapshot *p2 ); @@ -11029,20 +11534,21 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( ** This interface is only available if SQLite is compiled with the ** [SQLITE_ENABLE_SNAPSHOT] option. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); +SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); /* ** CAPI3REF: Serialize a database ** -** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory -** that is a serialization of the S database on [database connection] D. +** The sqlite3_serialize(D,S,P,F) interface returns a pointer to +** memory that is a serialization of the S database on +** [database connection] D. If S is a NULL pointer, the main database is used. ** If P is not a NULL pointer, then the size of the database in bytes ** is written into *P. ** ** For an ordinary on-disk database file, the serialization is just a ** copy of the disk file. For an in-memory database or a "TEMP" database, ** the serialization is the same sequence of bytes which would be written -** to disk if that database where backed up to disk. +** to disk if that database were backed up to disk. ** ** The usual case is that sqlite3_serialize() copies the serialization of ** the database into memory obtained from [sqlite3_malloc64()] and returns @@ -11051,7 +11557,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const c ** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations ** are made, and the sqlite3_serialize() function will return a pointer ** to the contiguous memory representation of the database that SQLite -** is currently using for that database, or NULL if the no such contiguous +** is currently using for that database, or NULL if no such contiguous ** memory representation of the database exists. A contiguous memory ** representation of the database will usually only exist if there has ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same @@ -11102,12 +11608,24 @@ SQLITE_API unsigned char *sqlite3_serialize( ** ** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the ** [database connection] D to disconnect from database S and then -** reopen S as an in-memory database based on the serialization contained -** in P. The serialized database P is N bytes in size. M is the size of -** the buffer P, which might be larger than N. If M is larger than N, and -** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is -** permitted to add content to the in-memory database as long as the total -** size does not exceed M bytes. +** reopen S as an in-memory database based on the serialization +** contained in P. If S is a NULL pointer, the main database is +** used. The serialized database P is N bytes in size. M is the size +** of the buffer P, which might be larger than N. If M is larger than +** N, and the SQLITE_DESERIALIZE_READONLY bit is not set in F, then +** SQLite is permitted to add content to the in-memory database, in +** page-sized chunks, as long as the total size does not exceed M bytes. +** +** The parameter M must be greater than or equal to N. Ideally, M +** should have a value which is N+(512&times;K)+20 where K determines how +** must extra space is available to hold new content as the database +** grows. K can be 0 if the database is read-only. +** +** If the database content in P is malformed in a malicious way then +** it is possible that SQLite might try to read a few more than N bytes +** from P. If the veracity of the database content P is uncertain, +** then applications are advised to allocate about 20 extra bytes on +** the end of the P buffer to avoid a memory error. ** ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will ** invoke sqlite3_free() on the serialization buffer when the database @@ -11122,7 +11640,7 @@ SQLITE_API unsigned char *sqlite3_serialize( ** database is currently in a read transaction or is involved in a backup ** operation. ** -** It is not possible to deserialized into the TEMP database. If the +** It is not possible to deserialize into the TEMP database. If the ** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the ** function returns SQLITE_ERROR. ** @@ -11144,7 +11662,7 @@ SQLITE_API int sqlite3_deserialize( sqlite3 *db, /* The database connection */ const char *zSchema, /* Which DB to reopen with the deserialization */ unsigned char *pData, /* The serialized database content */ - sqlite3_int64 szDb, /* Number bytes in the deserialization */ + sqlite3_int64 szDb, /* Number of bytes in the deserialization */ sqlite3_int64 szBuf, /* Total size of buffer pData[] */ unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */ ); @@ -11152,7 +11670,7 @@ SQLITE_API int sqlite3_deserialize( /* ** CAPI3REF: Flags for sqlite3_deserialize() ** -** The following are allowed values for 6th argument (the F argument) to +** The following are allowed values for the 6th argument (the F argument) to ** the [sqlite3_deserialize(D,S,P,N,M,F)] interface. ** ** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization @@ -11174,6 +11692,77 @@ SQLITE_API int sqlite3_deserialize( #define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */ #define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */ +/* +** CAPI3REF: Bind array values to the CARRAY table-valued function +** +** The sqlite3_carray_bind_v2(S,I,P,N,F,X,D) interface binds an array value to +** parameter that is the first argument of the [carray() table-valued function]. +** The S parameter is a pointer to the [prepared statement] that uses the +** carray() functions. I is the parameter index to be bound. I must be the +** index of the parameter that is the first argument to the carray() +** table-valued function. P is a pointer to the array to be bound, and N +** is the number of elements in the array. The F argument is one of +** constants [SQLITE_CARRAY_INT32], [SQLITE_CARRAY_INT64], +** [SQLITE_CARRAY_DOUBLE], [SQLITE_CARRAY_TEXT], +** or [SQLITE_CARRAY_BLOB] to indicate the datatype of the array P. +** +** If the X argument is not a NULL pointer or one of the special +** values [SQLITE_STATIC] or [SQLITE_TRANSIENT], then SQLite will invoke +** the function X with argument D when it is finished using the data in P. +** The call to X(D) is a destructor for the array P. The destructor X(D) +** is invoked even if the call to sqlite3_carray_bind_v2() fails. If the X +** parameter is the special-case value [SQLITE_STATIC], then SQLite assumes +** that the data static and the destructor is never invoked. If the X +** parameter is the special-case value [SQLITE_TRANSIENT], then +** sqlite3_carray_bind_v2() makes its own private copy of the data prior +** to returning and never invokes the destructor X. +** +** The sqlite3_carray_bind() function works the same as sqlite3_carray_bind_v2() +** with a D parameter set to P. In other words, +** sqlite3_carray_bind(S,I,P,N,F,X) is same as +** sqlite3_carray_bind_v2(S,I,P,N,F,X,P). +*/ +SQLITE_API int sqlite3_carray_bind_v2( + sqlite3_stmt *pStmt, /* Statement to be bound */ + int i, /* Parameter index */ + void *aData, /* Pointer to array data */ + int nData, /* Number of data elements */ + int mFlags, /* CARRAY flags */ + void (*xDel)(void*), /* Destructor for aData */ + void *pDel /* Optional argument to xDel() */ +); +SQLITE_API int sqlite3_carray_bind( + sqlite3_stmt *pStmt, /* Statement to be bound */ + int i, /* Parameter index */ + void *aData, /* Pointer to array data */ + int nData, /* Number of data elements */ + int mFlags, /* CARRAY flags */ + void (*xDel)(void*) /* Destructor for aData */ +); + +/* +** CAPI3REF: Datatypes for the CARRAY table-valued function +** +** The fifth argument to the [sqlite3_carray_bind()] interface musts be +** one of the following constants, to specify the datatype of the array +** that is being bound into the [carray table-valued function]. +*/ +#define SQLITE_CARRAY_INT32 0 /* Data is 32-bit signed integers */ +#define SQLITE_CARRAY_INT64 1 /* Data is 64-bit signed integers */ +#define SQLITE_CARRAY_DOUBLE 2 /* Data is doubles */ +#define SQLITE_CARRAY_TEXT 3 /* Data is char* */ +#define SQLITE_CARRAY_BLOB 4 /* Data is struct iovec */ + +/* +** Versions of the above #defines that omit the initial SQLITE_, for +** legacy compatibility. +*/ +#define CARRAY_INT32 0 /* Data is 32-bit signed integers */ +#define CARRAY_INT64 1 /* Data is 64-bit signed integers */ +#define CARRAY_DOUBLE 2 /* Data is doubles */ +#define CARRAY_TEXT 3 /* Data is char* */ +#define CARRAY_BLOB 4 /* Data is struct iovec */ + /* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. @@ -11196,7 +11785,7 @@ SQLITE_API int sqlite3_deserialize( #if 0 } /* End of the 'extern "C"' block */ #endif -#endif /* SQLITE3_H */ +/* #endif for SQLITE3_H will be added by mksqlite3.tcl */ /******** Begin file sqlite3rtree.h *********/ /* @@ -11677,9 +12266,10 @@ SQLITE_API void sqlite3session_table_filter( ** is inserted while a session object is enabled, then later deleted while ** the same session object is disabled, no INSERT record will appear in the ** changeset, even though the delete took place while the session was disabled. -** Or, if one field of a row is updated while a session is disabled, and -** another field of the same row is updated while the session is enabled, the -** resulting changeset will contain an UPDATE change that updates both fields. +** Or, if one field of a row is updated while a session is enabled, and +** then another field of the same row is updated while the session is disabled, +** the resulting changeset will contain an UPDATE change that updates both +** fields. */ SQLITE_API int sqlite3session_changeset( sqlite3_session *pSession, /* Session object */ @@ -11751,8 +12341,9 @@ SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession ** database zFrom the contents of the two compatible tables would be ** identical. ** -** It an error if database zFrom does not exist or does not contain the -** required compatible table. +** Unless the call to this function is a no-op as described above, it is an +** error if database zFrom does not exist or does not contain the required +** compatible table. ** ** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg @@ -11887,7 +12478,7 @@ SQLITE_API int sqlite3changeset_start_v2( ** The following flags may passed via the 4th parameter to ** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]: ** -** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd> +** <dt>SQLITE_CHANGESETSTART_INVERT <dd> ** Invert the changeset while iterating through it. This is equivalent to ** inverting a changeset using sqlite3changeset_invert() before applying it. ** It is an error to specify this flag with a patchset. @@ -12202,19 +12793,6 @@ SQLITE_API int sqlite3changeset_concat( void **ppOut /* OUT: Buffer containing output changeset */ ); - -/* -** CAPI3REF: Upgrade the Schema of a Changeset/Patchset -*/ -SQLITE_API int sqlite3changeset_upgrade( - sqlite3 *db, - const char *zDb, - int nIn, const void *pIn, /* Input changeset */ - int *pnOut, void **ppOut /* OUT: Inverse of input */ -); - - - /* ** CAPI3REF: Changegroup Handle ** @@ -12444,14 +13022,32 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*); ** update the "main" database attached to handle db with the changes found in ** the changeset passed via the second and third arguments. ** +** All changes made by these functions are enclosed in a savepoint transaction. +** If any other error (aside from a constraint failure when attempting to +** write to the target database) occurs, then the savepoint transaction is +** rolled back, restoring the target database to its original state, and an +** SQLite error code returned. Additionally, starting with version 3.51.0, +** an error code and error message that may be accessed using the +** [sqlite3_errcode()] and [sqlite3_errmsg()] APIs are left in the database +** handle. +** ** The fourth argument (xFilter) passed to these functions is the "filter -** callback". If it is not NULL, then for each table affected by at least one -** change in the changeset, the filter callback is invoked with -** the table name as the second argument, and a copy of the context pointer -** passed as the sixth argument as the first. If the "filter callback" -** returns zero, then no attempt is made to apply any changes to the table. -** Otherwise, if the return value is non-zero or the xFilter argument to -** is NULL, all changes related to the table are attempted. +** callback". This may be passed NULL, in which case all changes in the +** changeset are applied to the database. For sqlite3changeset_apply() and +** sqlite3_changeset_apply_v2(), if it is not NULL, then it is invoked once +** for each table affected by at least one change in the changeset. In this +** case the table name is passed as the second argument, and a copy of +** the context pointer passed as the sixth argument to apply() or apply_v2() +** as the first. If the "filter callback" returns zero, then no attempt is +** made to apply any changes to the table. Otherwise, if the return value is +** non-zero, all changes related to the table are attempted. +** +** For sqlite3_changeset_apply_v3(), the xFilter callback is invoked once +** per change. The second argument in this case is an sqlite3_changeset_iter +** that may be queried using the usual APIs for the details of the current +** change. If the "filter callback" returns zero in this case, then no attempt +** is made to apply the current change. If it returns non-zero, the change +** is applied. ** ** For each table that is not excluded by the filter callback, this function ** tests that the target database contains a compatible table. A table is @@ -12472,11 +13068,11 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*); ** one such warning is issued for each table in the changeset. ** ** For each change for which there is a compatible table, an attempt is made -** to modify the table contents according to the UPDATE, INSERT or DELETE -** change. If a change cannot be applied cleanly, the conflict handler -** function passed as the fifth argument to sqlite3changeset_apply() may be -** invoked. A description of exactly when the conflict handler is invoked for -** each type of change is below. +** to modify the table contents according to each UPDATE, INSERT or DELETE +** change that is not excluded by a filter callback. If a change cannot be +** applied cleanly, the conflict handler function passed as the fifth argument +** to sqlite3changeset_apply() may be invoked. A description of exactly when +** the conflict handler is invoked for each type of change is below. ** ** Unlike the xFilter argument, xConflict may not be passed NULL. The results ** of passing anything other than a valid function pointer as the xConflict @@ -12572,12 +13168,6 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*); ** This can be used to further customize the application's conflict ** resolution strategy. ** -** All changes made by these functions are enclosed in a savepoint transaction. -** If any other error (aside from a constraint failure when attempting to -** write to the target database) occurs, then the savepoint transaction is -** rolled back, restoring the target database to its original state, and an -** SQLite error code returned. -** ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and ** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2() ** may set (*ppRebase) to point to a "rebase" that may be used with the @@ -12627,6 +13217,23 @@ SQLITE_API int sqlite3changeset_apply_v2( void **ppRebase, int *pnRebase, /* OUT: Rebase data */ int flags /* SESSION_CHANGESETAPPLY_* flags */ ); +SQLITE_API int sqlite3changeset_apply_v3( + sqlite3 *db, /* Apply change to "main" db of this handle */ + int nChangeset, /* Size of changeset in bytes */ + void *pChangeset, /* Changeset blob */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + sqlite3_changeset_iter *p /* Handle describing change */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, /* OUT: Rebase data */ + int flags /* SESSION_CHANGESETAPPLY_* flags */ +); /* ** CAPI3REF: Flags for sqlite3changeset_apply_v2 @@ -12667,11 +13274,23 @@ SQLITE_API int sqlite3changeset_apply_v2( ** database behave as if they were declared with "ON UPDATE NO ACTION ON ** DELETE NO ACTION", even if they are actually CASCADE, RESTRICT, SET NULL ** or SET DEFAULT. +** +** <dt>SQLITE_CHANGESETAPPLY_NOUPDATELOOP <dd> +** Sometimes, a changeset contains two or more update statements such that +** although after applying all updates the database will contain no +** constraint violations, no single update can be applied before the others. +** The simplest example of this is a pair of UPDATEs that have "swapped" +** two column values with a UNIQUE constraint. +** <p> +** Usually, sqlite3changeset_apply() and similar functions work hard to try +** to find a way to apply such a changeset. However, if this flag is set, +** then all such updates are considered CONSTRAINT conflicts. */ #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001 #define SQLITE_CHANGESETAPPLY_INVERT 0x0002 #define SQLITE_CHANGESETAPPLY_IGNORENOOP 0x0004 #define SQLITE_CHANGESETAPPLY_FKNOACTION 0x0008 +#define SQLITE_CHANGESETAPPLY_NOUPDATELOOP 0x0010 /* ** CAPI3REF: Constants Passed To The Conflict Handler @@ -13046,6 +13665,23 @@ SQLITE_API int sqlite3changeset_apply_v2_strm( void **ppRebase, int *pnRebase, int flags ); +SQLITE_API int sqlite3changeset_apply_v3_strm( + sqlite3 *db, /* Apply change to "main" db of this handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ + void *pIn, /* First arg for xInput */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + sqlite3_changeset_iter *p + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, + int flags +); SQLITE_API int sqlite3changeset_concat_strm( int (*xInputA)(void *pIn, void *pData, int *pnData), void *pInA, @@ -13137,6 +13773,232 @@ SQLITE_API int sqlite3session_config(int op, void *pArg); */ #define SQLITE_SESSION_CONFIG_STRMSIZE 1 +/* +** CAPI3REF: Configure a changegroup object +** +** Configure the changegroup object passed as the first argument. +** At present the only valid value for the second parameter is +** [SQLITE_CHANGEGROUP_CONFIG_PATCHSET]. +*/ +SQLITE_API int sqlite3changegroup_config(sqlite3_changegroup*, int, void *pArg); + +/* +** CAPI3REF: Options for sqlite3changegroup_config(). +** +** The following values may be passed as the 2nd parameter to +** sqlite3changegroup_config(). +** +** <dt>SQLITE_CHANGEGROUP_CONFIG_PATCHSET <dd> +** A changegroup object generates either a changeset or patchset. Usually, +** this is determined by whether the first call to sqlite3changegroup_add() +** is passed a changeset or a patchset. Or, if the first changes are added +** to the changegroup object using the sqlite3changegroup_change_xxx() +** APIs, then this option may be used to configure whether the changegroup +** object generates a changeset or patchset. +** +** When this option is invoked, parameter pArg must point to a value of +** type int. If the changegroup currently contains zero changes, and the +** value of the int variable is zero or greater than zero, then the +** changegroup is configured to generate a changeset or patchset, +** respectively. It is a no-op, not an error, if the changegroup is not +** configured because it has already started accumulating changes. +** +** Before returning, the int variable is set to 0 if the changegroup is +** configured to generate a changeset, or 1 if it is configured to generate +** a patchset. +*/ +#define SQLITE_CHANGEGROUP_CONFIG_PATCHSET 1 + + +/* +** CAPI3REF: Begin adding a change to a changegroup +** +** This API is used, in concert with other sqlite3changegroup_change_xxx() +** APIs, to add changes to a changegroup object one at a time. To add a +** single change, the caller must: +** +** 1. Invoke sqlite3changegroup_change_begin() to indicate the type of +** change (INSERT, UPDATE or DELETE), the affected table and whether +** or not the change should be marked as indirect. +** +** 2. Invoke sqlite3changegroup_change_int64() or one of the other four +** value functions - _null(), _double(), _text() or _blob() - one or +** more times to specify old.* and new.* values for the change being +** constructed. +** +** 3. Invoke sqlite3changegroup_change_finish() to either finish adding +** the change to the group, or to discard the change altogether. +** +** The first argument to this function must be a pointer to the existing +** changegroup object that the change will be added to. The second argument +** must be SQLITE_INSERT, SQLITE_UPDATE or SQLITE_DELETE. The third is the +** name of the table that the change affects, and the fourth is a boolean +** flag specifying whether the change should be marked as "indirect" (if +** bIndirect is non-zero) or not indirect (if bIndirect is zero). +** +** Following a successful call to this function, this function may not be +** called again on the same changegroup object until after +** sqlite3changegroup_change_finish() has been called. Doing so is an +** SQLITE_MISUSE error. +** +** The changegroup object passed as the first argument must be already +** configured with schema data for the specified table. It may be configured +** either by calling sqlite3changegroup_schema() with a database that contains +** the table, or sqlite3changegroup_add() with a changeset that contains the +** table. If the changegroup object has not been configured with a schema for +** the specified table when this function is called, SQLITE_ERROR is returned. +** +** If successful, SQLITE_OK is returned. Otherwise, if an error occurs, an +** SQLite error code is returned. In this case, if argument pzErr is non-NULL, +** then (*pzErr) may be set to point to a buffer containing a utf-8 formated, +** nul-terminated, English language error message. It is the responsibility +** of the caller to eventually free this buffer using sqlite3_free(). +*/ +SQLITE_API int sqlite3changegroup_change_begin( + sqlite3_changegroup*, + int eOp, + const char *zTab, + int bIndirect, + char **pzErr +); + +/* +** CAPI3REF: Add a 64-bit integer to a changegroup +** +** This function may only be called between a successful call to +** sqlite3changegroup_change_begin() and its matching +** sqlite3changegroup_change_finish() call. If it is called at any +** other time, it is an SQLITE_MISUSE error. Calling this function +** specifies a 64-bit integer value to be used in the change currently being +** added to the changegroup object passed as the first argument. +** +** The second parameter, bNew, specifies whether the value is to be part of +** the new.* (if bNew is non-zero) or old.* (if bNew is zero) record of +** the change under construction. If this does not match the type of change +** specified by the preceding call to sqlite3changegroup_change_begin() (i.e. +** an old.* value for an SQLITE_INSERT change, or a new.* value for an +** SQLITE_DELETE), then SQLITE_ERROR is returned. +** +** The third parameter specifies the column of the old.* or new.* record that +** the value will be a part of. If the specified table has an explicit primary +** key, then this is the index of the table column, numbered from 0 in the order +** specified within the CREATE TABLE statement. Or, if the table uses an +** implicit rowid key, then the column 0 is the rowid and the explicit columns +** are numbered starting from 1. If the iCol parameter is less than 0 or greater +** than the index of the last column in the table, SQLITE_RANGE is returned. +** +** The fourth parameter is the integer value to use as part of the old.* or +** new.* record. +** +** If this call is successful, SQLITE_OK is returned. Otherwise, if an +** error occurs, an SQLite error code is returned. +*/ +SQLITE_API int sqlite3changegroup_change_int64( + sqlite3_changegroup*, + int bNew, + int iCol, + sqlite3_int64 iVal +); + +/* +** CAPI3REF: Add a NULL to a changegroup +** +** This function is similar to sqlite3changegroup_change_int64(). Except that +** it configures the change currently under construction with a NULL value +** instead of a 64-bit integer. +*/ +SQLITE_API int sqlite3changegroup_change_null(sqlite3_changegroup*, int, int); + +/* +** CAPI3REF: Add an double to a changegroup +** +** This function is similar to sqlite3changegroup_change_int64(). Except that +** it configures the change currently being constructed with a real value +** instead of a 64-bit integer. +*/ +SQLITE_API int sqlite3changegroup_change_double(sqlite3_changegroup*, int, int, double); + +/* +** CAPI3REF: Add a text value to a changegroup +** +** This function is similar to sqlite3changegroup_change_int64(). It configures +** the currently accumulated change with a text value instead of a 64-bit +** integer. Parameter pVal points to a buffer containing the text encoded using +** utf-8. Parameter nVal may either be the size of the text value in bytes, or +** else a negative value, in which case the buffer pVal points to is assumed to +** be nul-terminated. +*/ +SQLITE_API int sqlite3changegroup_change_text( + sqlite3_changegroup*, int, int, const char *pVal, int nVal +); + +/* +** CAPI3REF: Add a blob to a changegroup +** +** This function is similar to sqlite3changegroup_change_int64(). It configures +** the currently accumulated change with a blob value instead of a 64-bit +** integer. Parameter pVal points to a buffer containing the blob. Parameter +** nVal is the size of the blob in bytes. +*/ +SQLITE_API int sqlite3changegroup_change_blob( + sqlite3_changegroup*, int, int, const void *pVal, int nVal +); + +/* +** CAPI3REF: Finish adding one-at-at-time changes to a changegroup +** +** This function may only be called following a successful call to +** sqlite3changegroup_change_begin(). Otherwise, it is an SQLITE_MISUSE error. +** +** If parameter bDiscard is non-zero, then the current change is simply +** discarded. In this case this function is always successful and SQLITE_OK +** returned. +** +** If parameter bDiscard is zero, then an attempt is made to add the current +** change to the changegroup. Assuming the changegroup is configured to +** produce a changeset (not a patchset), this requires that: +** +** * If the change is an INSERT or DELETE, then a value must be specified +** for all columns of the new.* or old.* record, respectively. +** +** * If the change is an UPDATE record, then values must be provided for +** the PRIMARY KEY columns of the old.* record, but must not be provided +** for PRIMARY KEY columns of the new.* record. +** +** * If the change is an UPDATE record, then for each non-PRIMARY KEY +** column in the old.* record for which a value has been provided, a +** value must also be provided for the same column in the new.* record. +** Similarly, for each non-PK column in the old.* record for which +** a value is not provided, a value must not be provided for the same +** column in the new.* record. +** +** * All values specified for PRIMARY KEY columns must be non-NULL. +** +** Otherwise, it is an error. +** +** If the changegroup already contains a change for the same row (identified +** by PRIMARY KEY columns), then the current change is combined with the +** existing change in the same way as for sqlite3changegroup_add(). +** +** For a patchset, all of the above rules apply except that it doesn't matter +** whether or not values are provided for the non-PK old.* record columns +** for an UPDATE or DELETE change. This means that code used to produce +** a changeset using the sqlite3changegroup_change_xxx() APIs may also +** be used to produce patchsets. +** +** If the call is successful, SQLITE_OK is returned. Otherwise, if an error +** occurs, an SQLite error code is returned. If an error is returned and +** parameter pzErr is not NULL, then (*pzErr) may be set to point to a buffer +** containing a nul-terminated, utf-8 encoded, English language error message. +** It is the responsibility of the caller to eventually free any such error +** message buffer using sqlite3_free(). +*/ +SQLITE_API int sqlite3changegroup_change_finish( + sqlite3_changegroup*, + int bDiscard, + char **pzErr +); + /* ** Make sure we can call this stuff from C++. */ @@ -13447,14 +14309,29 @@ struct Fts5PhraseIter { ** value returned by xInstCount(), SQLITE_RANGE is returned. Otherwise, ** output variable (*ppToken) is set to point to a buffer containing the ** matching document token, and (*pnToken) to the size of that buffer in -** bytes. This API is not available if the specified token matches a -** prefix query term. In that case both output variables are always set -** to 0. +** bytes. ** ** The output text is not a copy of the document text that was tokenized. ** It is the output of the tokenizer module. For tokendata=1 tables, this ** includes any embedded 0x00 and trailing data. ** +** This API may be slow in some cases if the token identified by parameters +** iIdx and iToken matched a prefix token in the query. In most cases, the +** first call to this API for each prefix token in the query is forced +** to scan the portion of the full-text index that matches the prefix +** token to collect the extra data required by this API. If the prefix +** token matches a large number of token instances in the document set, +** this may be a performance problem. +** +** If the user knows in advance that a query may use this API for a +** prefix token, FTS5 may be configured to collect all required data as part +** of the initial querying of the full-text index, avoiding the second scan +** entirely. This also causes prefix queries that do not use this API to +** run more slowly and use more memory. FTS5 may be configured in this way +** either on a per-table basis using the [FTS5 insttoken | 'insttoken'] +** option, or on a per-query basis using the +** [fts5_insttoken | fts5_insttoken()] user function. +** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. ** @@ -13888,12 +14765,13 @@ struct fts5_api { #endif /* _FTS5_H */ /******** End of fts5.h *********/ +#endif /* SQLITE3_H */ /************** End of sqlite3.h *********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /* -** Reuse the STATIC_LRU for mutex access to sqlite3_temp_directory. +** Reuse the STATIC_VFS1 for mutex access to sqlite3_temp_directory. */ #define SQLITE_MUTEX_STATIC_TEMPDIR SQLITE_MUTEX_STATIC_VFS1 @@ -13933,6 +14811,28 @@ struct fts5_api { #ifndef SQLITE_MAX_LENGTH # define SQLITE_MAX_LENGTH 1000000000 #endif +#define SQLITE_MIN_LENGTH 30 /* Minimum value for the length limit */ + +/* +** Maximum size of any single memory allocation. +** +** This is not a limit on the total amount of memory used. This is +** a limit on the size parameter to sqlite3_malloc() and sqlite3_realloc(). +** +** The upper bound is slightly less than 2GiB: 0x7ffffeff == 2,147,483,391 +** This provides a 256-byte safety margin for defense against 32-bit +** signed integer overflow bugs when computing memory allocation sizes. +** Paranoid applications might want to reduce the maximum allocation size +** further for an even larger safety margin. 0x3fffffff or 0x0fffffff +** or even smaller would be reasonable upper bounds on the size of a memory +** allocations for most applications. +*/ +#ifndef SQLITE_MAX_ALLOCATION_SIZE +# define SQLITE_MAX_ALLOCATION_SIZE 2147483391 +#endif +#if SQLITE_MAX_ALLOCATION_SIZE>2147483391 +# error Maximum size for SQLITE_MAX_ALLOCATION_SIZE is 2147483391 +#endif /* ** This is the maximum number of @@ -13945,14 +14845,22 @@ struct fts5_api { ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement. ** * Terms in the VALUES clause of an INSERT statement ** -** The hard upper limit here is 32676. Most database people will +** The hard upper limit here is 32767. Most database people will ** tell you that in a well-normalized database, you usually should ** not have more than a dozen or so columns in any table. And if ** that is the case, there is no point in having more than a few ** dozen values in any of the other situations described above. +** +** An index can only have SQLITE_MAX_COLUMN columns from the user +** point of view, but the underlying b-tree that implements the index +** might have up to twice as many columns in a WITHOUT ROWID table, +** since must also store the primary key at the end. Hence the +** column count for Index is u16 instead of i16. */ -#ifndef SQLITE_MAX_COLUMN +#if !defined(SQLITE_MAX_COLUMN) # define SQLITE_MAX_COLUMN 2000 +#elif SQLITE_MAX_COLUMN>32767 +# error SQLITE_MAX_COLUMN may not exceed 32767 #endif /* @@ -13961,21 +14869,42 @@ struct fts5_api { ** It used to be the case that setting this value to zero would ** turn the limit off. That is no longer true. It is not possible ** to turn this limit off. +** +** The hard limit is the largest possible 32-bit signed integer less +** 1024, or 2147482624. */ #ifndef SQLITE_MAX_SQL_LENGTH # define SQLITE_MAX_SQL_LENGTH 1000000000 #endif /* -** The maximum depth of an expression tree. This is limited to -** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might -** want to place more severe limits on the complexity of an -** expression. A value of 0 means that there is no limit. +** The maximum depth of an expression tree. The expression tree depth +** is also limited indirectly by SQLITE_MAX_SQL_LENGTH and by +** SQLITE_MAX_PARSER_DEPTH. Reducing the maximum complexity of +** expressions can help prevent excess memory usage by hostile SQL. +** +** A value of 0 for this compile-time option causes all expression +** depth limiting code to be omitted. */ #ifndef SQLITE_MAX_EXPR_DEPTH # define SQLITE_MAX_EXPR_DEPTH 1000 #endif +/* +** The maximum depth of the LALR(1) stack used in the parser that +** interprets SQL inputs. The parser stack depth can also be limited +** indirectly by SQLITE_MAX_SQL_LENGTH. Limiting the parser stack +** depth can help prevent excess memory usage and excess CPU stack +** usage when processing hostile SQL. +** +** Prior to version 3.45.0 (2024-01-15), the parser stack was +** hard-coded to 100 entries, and that worked fine for almost all +** applications. So the upper bound on this limit need not be large. +*/ +#ifndef SQLITE_MAX_PARSER_DEPTH +# define SQLITE_MAX_PARSER_DEPTH 2500 +#endif + /* ** The maximum number of terms in a compound SELECT statement. ** The code generator for compound SELECT statements does one @@ -13998,9 +14927,13 @@ struct fts5_api { /* ** The maximum number of arguments to an SQL function. +** +** This value has a hard upper limit of 32767 due to storage +** constraints (it needs to fit inside a i16). We keep it +** lower than that to prevent abuse. */ #ifndef SQLITE_MAX_FUNCTION_ARG -# define SQLITE_MAX_FUNCTION_ARG 127 +# define SQLITE_MAX_FUNCTION_ARG 1000 #endif /* @@ -14087,13 +15020,17 @@ struct fts5_api { # undef SQLITE_MAX_DEFAULT_PAGE_SIZE # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE #endif +#if SQLITE_MAX_DEFAULT_PAGE_SIZE<SQLITE_DEFAULT_PAGE_SIZE +# undef SQLITE_MAX_DEFAULT_PAGE_SIZE +# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_DEFAULT_PAGE_SIZE +#endif /* ** Maximum number of pages in one database file. ** ** This is really just the default value for the max_page_count pragma. -** This value can be lowered (or raised) at run-time using that the +** This value can be lowered (or raised) at run-time using the ** max_page_count macro. */ #ifndef SQLITE_MAX_PAGE_COUNT @@ -14119,6 +15056,41 @@ struct fts5_api { # define SQLITE_MAX_TRIGGER_DEPTH 1000 #endif +/* +** Maximum number of objects defined by a single database schema. +** Objects include: +** +** * tables (including the sqlite_schema table) +** * virtual tables +** * named indexes +** * indexes created automatically by UNIQUE and PRIMARY KEY constraints +** * triggers +** * views +** +** The total of all of the above is the number of objects in the schema, +** and that number may not exceed this value. +** +** The maximum number of objects is restricted to forestall theoretical +** signed integer overflow attacks using databases with billions of +** schema objects. Such attacks are "theoretical" because memory and +** disk space constraints would be reached long before billions of schema +** objects could be created. Even so, it seems good to have a well defined +** upper limit on the complexity of the schema, for defense in depth. +** No real-world application should ever get anywhere close to hitting +** this limit. +*/ +#ifndef SQLITE_MAX_SCHEMA +# define SQLITE_MAX_SCHEMA 10000000 +#endif + +/* +** Maximum number of SQL statements allowed in the body of a single +** trigger. +*/ +#ifndef SQLITE_MAX_TRIGGER_STEPS +# define SQLITE_MAX_TRIGGER_STEPS 65000 +#endif + /************** End of sqliteLimit.h *****************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ @@ -14151,9 +15123,7 @@ struct fts5_api { /* ** Include standard header files as necessary */ -#ifdef HAVE_STDINT_H #include <stdint.h> -#endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif @@ -14189,22 +15159,50 @@ struct fts5_api { #endif /* -** Macros to hint to the compiler that a function should or should not be -** inlined. +** Hint to the compiler that a function should or should not be inlined: +** +** SQLITE_NOINLINE Never in-line this function +** +** SQLITE_INLINE Strive to in-line this function +** +** SQLITE_OPT_INLINE In-line this function if building the +** amalgamation. +** +** SQLITE_USES_INLINE Set to 1 or 0 according to whether or not +** inline functions are supported. */ -#if defined(__GNUC__) -# define SQLITE_NOINLINE __attribute__((noinline)) -# define SQLITE_INLINE __attribute__((always_inline)) inline +#if defined(SQLITE_DISABLE_INLINE) +# define SQLITE_NOINLINE +# define SQLITE_INLINE +# define SQLITE_OPT_INLINE +# define SQLITE_USES_INLINE 0 +#elif defined(__GNUC__) +# define SQLITE_NOINLINE __attribute__((noinline)) +# define SQLITE_INLINE __attribute__((always_inline)) inline +# define SQLITE_OPT_INLINE __attribute__((always_inline)) inline +# define SQLITE_USES_INLINE 1 #elif defined(_MSC_VER) && _MSC_VER>=1310 -# define SQLITE_NOINLINE __declspec(noinline) -# define SQLITE_INLINE __forceinline +# define SQLITE_NOINLINE __declspec(noinline) +# define SQLITE_INLINE __forceinline +# define SQLITE_OPT_INLINE __forceinline +# define SQLITE_USES_INLINE 1 #else # define SQLITE_NOINLINE # define SQLITE_INLINE +# define SQLITE_OPT_INLINE +# define SQLITE_USES_INLINE 0 #endif #if defined(SQLITE_COVERAGE_TEST) || defined(__STRICT_ANSI__) # undef SQLITE_INLINE # define SQLITE_INLINE +# undef SQLITE_OPT_INLINE +# define SQLITE_OPT_INLINE +# undef SQLITE_USES_INLINE +# define SQLITE_USES_INLINE 0 +#endif +#if !defined(SQLITE_AMALGAMATION) +# undef SQLITE_OPT_INLINE +# define SQLITE_OPT_INLINE #endif /* @@ -14379,7 +15377,9 @@ struct fts5_api { ** where multiple cases go to the same block of code, testcase() ** can insure that all cases are evaluated. */ -#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG) +#if defined(SQLITE_MUTATION_TEST) +# define testcase(X) +#elif defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG) # ifndef SQLITE_AMALGAMATION extern unsigned int sqlite3CoverageCounter; # endif @@ -14600,6 +15600,7 @@ struct HashElem { HashElem *next, *prev; /* Next and previous elements in the table */ void *data; /* Data associated with this element */ const char *pKey; /* Key associated with this element */ + unsigned int h; /* hash for pKey */ }; /* @@ -14823,7 +15824,8 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*); #define TK_ERROR 182 #define TK_QNUMBER 183 #define TK_SPACE 184 -#define TK_ILLEGAL 185 +#define TK_COMMENT 185 +#define TK_ILLEGAL 186 /************** End of parse.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ @@ -14855,6 +15857,7 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*); # define float sqlite_int64 # define fabs(X) ((X)<0?-(X):(X)) # define sqlite3IsOverflow(X) 0 +# define INFINITY (9223372036854775807LL) # ifndef SQLITE_BIG_DBL # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50) # endif @@ -14959,7 +15962,24 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*); ** ourselves. */ #ifndef offsetof -#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD)) +# define offsetof(ST,M) ((size_t)((char*)&((ST*)0)->M - (char*)0)) +#endif + +/* +** sizeof64() is like sizeof(), but always returns a 64-bit value, even +** on 32-bit builds. This can help to avoid overflow by ensuring 64-bit +** arithmetic is used consistently in both 32-bit and 64-bit builds. +*/ +#define sizeof64(X) ((sqlite3_int64)sizeof(X)) + +/* +** Work around C99 "flex-array" syntax for pre-C99 compilers, so as +** to avoid complaints from -fsanitize=strict-bounds. +*/ +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) +# define FLEXARRAY +#else +# define FLEXARRAY 1 #endif /* @@ -15037,6 +16057,11 @@ typedef INT16_TYPE i16; /* 2-byte signed integer */ typedef UINT8_TYPE u8; /* 1-byte unsigned integer */ typedef INT8_TYPE i8; /* 1-byte signed integer */ +/* A bitfield type for use inside of structures. Always follow with :N where +** N is the number of bits. +*/ +typedef unsigned bft; /* Bit Field Type */ + /* ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value ** that can be stored in a u32 without loss of data. The value @@ -15075,6 +16100,8 @@ typedef u64 tRowcnt; ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40 */ typedef INT16_TYPE LogEst; +#define LOGEST_MIN (-32768) +#define LOGEST_MAX (32767) /* ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer @@ -15203,6 +16230,14 @@ typedef INT16_TYPE LogEst; #define LARGEST_UINT64 (0xffffffff|(((u64)0xffffffff)<<32)) #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) +/* +** Macro SMXV(n) return the maximum value that can be held in variable n, +** assuming n is a signed integer type. UMXV(n) is similar for unsigned +** integer types. +*/ +#define SMXV(n) ((((i64)1)<<(sizeof(n)*8-1))-1) +#define UMXV(n) ((((i64)1)<<(sizeof(n)*8))-1) + /* ** Round up a number to the next larger multiple of 8. This is used ** to force 8-byte alignment on 64-bit architectures. @@ -15239,6 +16274,7 @@ typedef INT16_TYPE LogEst; #else # define EIGHT_BYTE_ALIGNMENT(X) ((((uptr)(X) - (uptr)0)&7)==0) #endif +#define TWO_BYTE_ALIGNMENT(X) ((((uptr)(X) - (uptr)0)&1)==0) /* ** Disable MMAP on platforms where it is known to not work @@ -15322,6 +16358,8 @@ SQLITE_PRIVATE u32 sqlite3TreeTrace; ** 0x00020000 Transform DISTINCT into GROUP BY ** 0x00040000 SELECT tree dump after all code has been generated ** 0x00080000 NOT NULL strength reduction +** 0x00100000 Pointers are all shown as zero +** 0x00200000 EXISTS-to-JOIN optimization */ /* @@ -15345,7 +16383,7 @@ SQLITE_PRIVATE u32 sqlite3WhereTrace; ** 0xFFFF---- Low-level debug messages ** ** 0x00000001 Code generation -** 0x00000002 Solver +** 0x00000002 Solver (Use 0x40000 for less detail) ** 0x00000004 Solver costs ** 0x00000008 WhereLoop inserts ** @@ -15364,6 +16402,9 @@ SQLITE_PRIVATE u32 sqlite3WhereTrace; ** ** 0x00010000 Show more detail when printing WHERE terms ** 0x00020000 Show WHERE terms returned from whereScanNext() +** 0x00040000 Solver overview messages +** 0x00080000 Star-query heuristic +** 0x00100000 Pointers are all shown as zero */ @@ -15436,7 +16477,7 @@ struct BusyHandler { ** pointer will work here as long as it is distinct from SQLITE_STATIC ** and SQLITE_TRANSIENT. */ -#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3OomClear) +#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3RowSetClear) /* ** When SQLITE_OMIT_WSD is defined, it means that the target platform does @@ -15657,8 +16698,8 @@ typedef int VList; ** must provide its own VFS implementation together with sqlite3_os_init() ** and sqlite3_os_end() routines. */ -#if !defined(SQLITE_OS_KV) && !defined(SQLITE_OS_OTHER) && \ - !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_WIN) +#if SQLITE_OS_KV+1<=1 && SQLITE_OS_OTHER+1<=1 && \ + SQLITE_OS_WIN+1<=1 && SQLITE_OS_UNIX+1<=1 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \ defined(__MINGW32__) || defined(__BORLANDC__) # define SQLITE_OS_WIN 1 @@ -16002,6 +17043,22 @@ typedef struct PgHdr DbPage; #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */ +#define isWalMode(x) ((x)==PAGER_JOURNALMODE_WAL) + +/* +** The argument to this macro is a file descriptor (type sqlite3_file*). +** Return 0 if it is not open, or non-zero (but not 1) if it is. +** +** This is so that expressions can be written as: +** +** if( isOpen(pPager->jfd) ){ ... +** +** instead of +** +** if( pPager->jfd->pMethods ){ ... +*/ +#define isOpen(pFd) ((pFd)->pMethods!=0) + /* ** Flags that make up the mask passed to sqlite3PagerGet(). */ @@ -16163,6 +17220,10 @@ SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*); SQLITE_PRIVATE int sqlite3PagerWalSystemErrno(Pager*); #endif +#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_WALSTAT) +SQLITE_PRIVATE void sqlite3PagerWalStat(Pager*,sqlite3_str*); +#endif + #endif /* SQLITE_PAGER_H */ /************** End of pager.h ***********************************************/ @@ -16276,7 +17337,7 @@ SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *); SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *); -SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *); +SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree*, Btree*); SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *); @@ -16353,12 +17414,19 @@ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p); ** implementations with limits on what needs to be prefetched and thereby ** reduce network bandwidth. ** +** BTREE_HINT_TABLECURSOR (arguments: BtCursor*) +** +** This hint is invoked on a non-covering index cursor soon after it +** is opened. The only argument is a pointer to the table cursor used to +** obtain non-covered fields from the database. +** ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by ** standard SQLite. The other hints are provided for extensions that use ** the SQLite parser and code generator but substitute their own storage ** engine. */ #define BTREE_HINT_RANGE 0 /* Range constraints on queries */ +#define BTREE_HINT_TABLECURSOR 1 /* Table csr associated with this index csr */ /* ** Values that may be OR'd together to form the argument to the @@ -16418,6 +17486,9 @@ SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*); SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned); #ifdef SQLITE_ENABLE_CURSOR_HINTS SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...); + #ifdef SQLITE_DEBUG +SQLITE_PRIVATE BtCursor *sqlite3BtreeCursorHintTblCsr(BtCursor*); + #endif #endif SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*); @@ -16488,6 +17559,7 @@ struct BtreePayload { SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload, int flags, int seekResult); SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes); +SQLITE_PRIVATE int sqlite3BtreeIsEmpty(BtCursor *pCur, int *pRes); SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes); SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags); SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*); @@ -16640,6 +17712,7 @@ typedef struct SubrtnSig SubrtnSig; */ struct SubrtnSig { int selId; /* SELECT-id for the SELECT statement on the RHS */ + u8 bComplete; /* True if fully coded and available for reusable */ char *zAff; /* Affinity of the overall IN expression */ int iTable; /* Ephemeral table generated by the subroutine */ int iAddr; /* Subroutine entry address */ @@ -16662,8 +17735,6 @@ struct VdbeOp { int i; /* Integer value if p4type==P4_INT32 */ void *p; /* Generic pointer */ char *z; /* Pointer to data for string (char array) types */ - i64 *pI64; /* Used when p4type is P4_INT64 */ - double *pReal; /* Used when p4type is P4_REAL */ FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */ CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ @@ -16674,6 +17745,7 @@ struct VdbeOp { SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */ Table *pTab; /* Used when p4type is P4_TABLE */ SubrtnSig *pSubrtnSig; /* Used when p4type is P4_SUBRTNSIG */ + Index *pIdx; /* Used when p4type is P4_INDEX */ #ifdef SQLITE_ENABLE_CURSOR_HINTS Expr *pExpr; /* Used when p4type is P4_EXPR */ #endif @@ -16718,6 +17790,19 @@ struct VdbeOpList { }; typedef struct VdbeOpList VdbeOpList; +/* +** Combine two int32 values into a single int64. The least significant +** term comes first. +*/ +#define INT32_TO_64(a,b) (i64)(((u64)(u32)(b)<<32)|(u32)(a)) + +/* +** Return an int32 that is the lower or upper 32-bits of an int64. +*/ +#define LOWER32(x) (int)(((u64)(x))&0xffffffff) +#define UPPER32(x) (int)(((u64)(x))>>32) + + /* ** Allowed values of VdbeOp.p4type */ @@ -16728,20 +17813,19 @@ typedef struct VdbeOpList VdbeOpList; #define P4_INT32 (-3) /* P4 is a 32-bit signed integer */ #define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */ #define P4_TABLE (-5) /* P4 is a pointer to a Table structure */ +#define P4_INDEX (-6) /* P4 is a pointer to an Index structure */ /* Above do not own any resources. Must free those below */ -#define P4_FREE_IF_LE (-6) -#define P4_DYNAMIC (-6) /* Pointer to memory from sqliteMalloc() */ -#define P4_FUNCDEF (-7) /* P4 is a pointer to a FuncDef structure */ -#define P4_KEYINFO (-8) /* P4 is a pointer to a KeyInfo structure */ -#define P4_EXPR (-9) /* P4 is a pointer to an Expr tree */ -#define P4_MEM (-10) /* P4 is a pointer to a Mem* structure */ -#define P4_VTAB (-11) /* P4 is a pointer to an sqlite3_vtab structure */ -#define P4_REAL (-12) /* P4 is a 64-bit floating point value */ -#define P4_INT64 (-13) /* P4 is a 64-bit signed integer */ -#define P4_INTARRAY (-14) /* P4 is a vector of 32-bit integers */ -#define P4_FUNCCTX (-15) /* P4 is a pointer to an sqlite3_context object */ -#define P4_TABLEREF (-16) /* Like P4_TABLE, but reference counted */ -#define P4_SUBRTNSIG (-17) /* P4 is a SubrtnSig pointer */ +#define P4_FREE_IF_LE (-7) +#define P4_DYNAMIC (-7) /* Pointer to memory from sqliteMalloc() */ +#define P4_FUNCDEF (-8) /* P4 is a pointer to a FuncDef structure */ +#define P4_KEYINFO (-9) /* P4 is a pointer to a KeyInfo structure */ +#define P4_EXPR (-10) /* P4 is a pointer to an Expr tree */ +#define P4_MEM (-11) /* P4 is a pointer to a Mem* structure */ +#define P4_VTAB (-12) /* P4 is a pointer to an sqlite3_vtab structure */ +#define P4_INTARRAY (-13) /* P4 is a vector of 32-bit integers */ +#define P4_FUNCCTX (-14) /* P4 is a pointer to an sqlite3_context object */ +#define P4_TABLEREF (-15) /* Like P4_TABLE, but reference counted */ +#define P4_SUBRTNSIG (-16) /* P4 is a SubrtnSig pointer */ /* Error message codes for OP_Halt */ #define P5_ConstraintNotNull 1 @@ -16808,18 +17892,18 @@ typedef struct VdbeOpList VdbeOpList; #define OP_SeekLE 22 /* jump0, synopsis: key=r[P3@P4] */ #define OP_SeekGE 23 /* jump0, synopsis: key=r[P3@P4] */ #define OP_SeekGT 24 /* jump0, synopsis: key=r[P3@P4] */ -#define OP_IfNotOpen 25 /* jump, synopsis: if( !csr[P1] ) goto P2 */ -#define OP_IfNoHope 26 /* jump, synopsis: key=r[P3@P4] */ -#define OP_NoConflict 27 /* jump, synopsis: key=r[P3@P4] */ -#define OP_NotFound 28 /* jump, synopsis: key=r[P3@P4] */ -#define OP_Found 29 /* jump, synopsis: key=r[P3@P4] */ -#define OP_SeekRowid 30 /* jump0, synopsis: intkey=r[P3] */ -#define OP_NotExists 31 /* jump, synopsis: intkey=r[P3] */ -#define OP_Last 32 /* jump0 */ -#define OP_IfSizeBetween 33 /* jump */ -#define OP_SorterSort 34 /* jump */ -#define OP_Sort 35 /* jump */ -#define OP_Rewind 36 /* jump0 */ +#define OP_IfNoHope 25 /* jump, synopsis: key=r[P3@P4] */ +#define OP_NoConflict 26 /* jump, synopsis: key=r[P3@P4] */ +#define OP_NotFound 27 /* jump, synopsis: key=r[P3@P4] */ +#define OP_Found 28 /* jump, synopsis: key=r[P3@P4] */ +#define OP_SeekRowid 29 /* jump0, synopsis: intkey=r[P3] */ +#define OP_NotExists 30 /* jump, synopsis: intkey=r[P3] */ +#define OP_Last 31 /* jump0 */ +#define OP_IfSizeBetween 32 /* jump */ +#define OP_SorterSort 33 /* jump */ +#define OP_Sort 34 /* jump */ +#define OP_Rewind 35 /* jump0 */ +#define OP_IfEmpty 36 /* jump, synopsis: if( empty(P1) ) goto P2 */ #define OP_SorterNext 37 /* jump */ #define OP_Prev 38 /* jump */ #define OP_Next 39 /* jump */ @@ -16829,11 +17913,11 @@ typedef struct VdbeOpList VdbeOpList; #define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */ #define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */ #define OP_IdxGE 45 /* jump, synopsis: key=r[P3@P4] */ -#define OP_RowSetRead 46 /* jump, synopsis: r[P3]=rowset(P1) */ -#define OP_RowSetTest 47 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */ -#define OP_Program 48 /* jump0 */ -#define OP_FkIfZero 49 /* jump, synopsis: if fkctr[P1]==0 goto P2 */ -#define OP_IfPos 50 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */ +#define OP_IFindKey 46 /* jump */ +#define OP_RowSetRead 47 /* jump, synopsis: r[P3]=rowset(P1) */ +#define OP_RowSetTest 48 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */ +#define OP_Program 49 /* jump0 */ +#define OP_FkIfZero 50 /* jump, synopsis: if fkctr[P1]==0 goto P2 */ #define OP_IsNull 51 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */ #define OP_NotNull 52 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */ #define OP_Ne 53 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */ @@ -16843,49 +17927,49 @@ typedef struct VdbeOpList VdbeOpList; #define OP_Lt 57 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */ #define OP_Ge 58 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */ #define OP_ElseEq 59 /* jump, same as TK_ESCAPE */ -#define OP_IfNotZero 60 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */ -#define OP_DecrJumpZero 61 /* jump, synopsis: if (--r[P1])==0 goto P2 */ -#define OP_IncrVacuum 62 /* jump */ -#define OP_VNext 63 /* jump */ -#define OP_Filter 64 /* jump, synopsis: if key(P3@P4) not in filter(P1) goto P2 */ -#define OP_PureFunc 65 /* synopsis: r[P3]=func(r[P2@NP]) */ -#define OP_Function 66 /* synopsis: r[P3]=func(r[P2@NP]) */ -#define OP_Return 67 -#define OP_EndCoroutine 68 -#define OP_HaltIfNull 69 /* synopsis: if r[P3]=null halt */ -#define OP_Halt 70 -#define OP_Integer 71 /* synopsis: r[P2]=P1 */ -#define OP_Int64 72 /* synopsis: r[P2]=P4 */ -#define OP_String 73 /* synopsis: r[P2]='P4' (len=P1) */ -#define OP_BeginSubrtn 74 /* synopsis: r[P2]=NULL */ -#define OP_Null 75 /* synopsis: r[P2..P3]=NULL */ -#define OP_SoftNull 76 /* synopsis: r[P1]=NULL */ -#define OP_Blob 77 /* synopsis: r[P2]=P4 (len=P1) */ -#define OP_Variable 78 /* synopsis: r[P2]=parameter(P1) */ -#define OP_Move 79 /* synopsis: r[P2@P3]=r[P1@P3] */ -#define OP_Copy 80 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */ -#define OP_SCopy 81 /* synopsis: r[P2]=r[P1] */ -#define OP_IntCopy 82 /* synopsis: r[P2]=r[P1] */ -#define OP_FkCheck 83 -#define OP_ResultRow 84 /* synopsis: output=r[P1@P2] */ -#define OP_CollSeq 85 -#define OP_AddImm 86 /* synopsis: r[P1]=r[P1]+P2 */ -#define OP_RealAffinity 87 -#define OP_Cast 88 /* synopsis: affinity(r[P1]) */ -#define OP_Permutation 89 -#define OP_Compare 90 /* synopsis: r[P1@P3] <-> r[P2@P3] */ -#define OP_IsTrue 91 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */ -#define OP_ZeroOrNull 92 /* synopsis: r[P2] = 0 OR NULL */ -#define OP_Offset 93 /* synopsis: r[P3] = sqlite_offset(P1) */ -#define OP_Column 94 /* synopsis: r[P3]=PX cursor P1 column P2 */ -#define OP_TypeCheck 95 /* synopsis: typecheck(r[P1@P2]) */ -#define OP_Affinity 96 /* synopsis: affinity(r[P1@P2]) */ -#define OP_MakeRecord 97 /* synopsis: r[P3]=mkrec(r[P1@P2]) */ -#define OP_Count 98 /* synopsis: r[P2]=count() */ -#define OP_ReadCookie 99 -#define OP_SetCookie 100 -#define OP_ReopenIdx 101 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenRead 102 /* synopsis: root=P2 iDb=P3 */ +#define OP_IfPos 60 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */ +#define OP_IfNotZero 61 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */ +#define OP_DecrJumpZero 62 /* jump, synopsis: if (--r[P1])==0 goto P2 */ +#define OP_IncrVacuum 63 /* jump */ +#define OP_VNext 64 /* jump */ +#define OP_Filter 65 /* jump, synopsis: if key(P3@P4) not in filter(P1) goto P2 */ +#define OP_PureFunc 66 /* synopsis: r[P3]=func(r[P2@NP]) */ +#define OP_Function 67 /* synopsis: r[P3]=func(r[P2@NP]) */ +#define OP_Return 68 +#define OP_EndCoroutine 69 +#define OP_HaltIfNull 70 /* synopsis: if r[P3]=null halt */ +#define OP_Halt 71 +#define OP_Integer 72 /* synopsis: r[P2]=P1 */ +#define OP_Int64 73 /* synopsis: r[P2]=PINT13 */ +#define OP_String 74 /* synopsis: r[P2]='P4' (len=P1) */ +#define OP_BeginSubrtn 75 /* synopsis: r[P2]=NULL */ +#define OP_Null 76 /* synopsis: r[P2..P3]=NULL */ +#define OP_SoftNull 77 /* synopsis: r[P1]=NULL */ +#define OP_Blob 78 /* synopsis: r[P2]=P4 (len=P1) */ +#define OP_Variable 79 /* synopsis: r[P2]=parameter(P1) */ +#define OP_Move 80 /* synopsis: r[P2@P3]=r[P1@P3] */ +#define OP_Copy 81 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */ +#define OP_SCopy 82 /* synopsis: r[P2]=r[P1] */ +#define OP_IntCopy 83 /* synopsis: r[P2]=r[P1] */ +#define OP_FkCheck 84 +#define OP_ResultRow 85 /* synopsis: output=r[P1@P2] */ +#define OP_CollSeq 86 +#define OP_AddImm 87 /* synopsis: r[P1]=r[P1]+P2 */ +#define OP_RealAffinity 88 +#define OP_Cast 89 /* synopsis: affinity(r[P1]) */ +#define OP_Permutation 90 +#define OP_Compare 91 /* synopsis: r[P1@P3] <-> r[P2@P3] */ +#define OP_IsTrue 92 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */ +#define OP_ZeroOrNull 93 /* synopsis: r[P2] = 0 OR NULL */ +#define OP_Offset 94 /* synopsis: r[P3] = sqlite_offset(P1) */ +#define OP_Column 95 /* synopsis: r[P3]=PX cursor P1 column P2 */ +#define OP_TypeCheck 96 /* synopsis: typecheck(r[P1@P2]) */ +#define OP_Affinity 97 /* synopsis: affinity(r[P1@P2]) */ +#define OP_MakeRecord 98 /* synopsis: r[P3]=mkrec(r[P1@P2]) */ +#define OP_Count 99 /* synopsis: r[P2]=count() */ +#define OP_ReadCookie 100 +#define OP_SetCookie 101 +#define OP_ReopenIdx 102 /* synopsis: root=P2 iDb=P3 */ #define OP_BitAnd 103 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */ #define OP_BitOr 104 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */ #define OP_ShiftLeft 105 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */ @@ -16896,83 +17980,84 @@ typedef struct VdbeOpList VdbeOpList; #define OP_Divide 110 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */ #define OP_Remainder 111 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */ #define OP_Concat 112 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */ -#define OP_OpenWrite 113 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenDup 114 +#define OP_OpenRead 113 /* synopsis: root=P2 iDb=P3 */ +#define OP_OpenWrite 114 /* synopsis: root=P2 iDb=P3 */ #define OP_BitNot 115 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */ -#define OP_OpenAutoindex 116 /* synopsis: nColumn=P2 */ -#define OP_OpenEphemeral 117 /* synopsis: nColumn=P2 */ +#define OP_OpenDup 116 +#define OP_OpenAutoindex 117 /* synopsis: nColumn=P2 */ #define OP_String8 118 /* same as TK_STRING, synopsis: r[P2]='P4' */ -#define OP_SorterOpen 119 -#define OP_SequenceTest 120 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */ -#define OP_OpenPseudo 121 /* synopsis: P3 columns in r[P2] */ -#define OP_Close 122 -#define OP_ColumnsUsed 123 -#define OP_SeekScan 124 /* synopsis: Scan-ahead up to P1 rows */ -#define OP_SeekHit 125 /* synopsis: set P2<=seekHit<=P3 */ -#define OP_Sequence 126 /* synopsis: r[P2]=cursor[P1].ctr++ */ -#define OP_NewRowid 127 /* synopsis: r[P2]=rowid */ -#define OP_Insert 128 /* synopsis: intkey=r[P3] data=r[P2] */ -#define OP_RowCell 129 -#define OP_Delete 130 -#define OP_ResetCount 131 -#define OP_SorterCompare 132 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */ -#define OP_SorterData 133 /* synopsis: r[P2]=data */ -#define OP_RowData 134 /* synopsis: r[P2]=data */ -#define OP_Rowid 135 /* synopsis: r[P2]=PX rowid of P1 */ -#define OP_NullRow 136 -#define OP_SeekEnd 137 -#define OP_IdxInsert 138 /* synopsis: key=r[P2] */ -#define OP_SorterInsert 139 /* synopsis: key=r[P2] */ -#define OP_IdxDelete 140 /* synopsis: key=r[P2@P3] */ -#define OP_DeferredSeek 141 /* synopsis: Move P3 to P1.rowid if needed */ -#define OP_IdxRowid 142 /* synopsis: r[P2]=rowid */ -#define OP_FinishSeek 143 -#define OP_Destroy 144 -#define OP_Clear 145 -#define OP_ResetSorter 146 -#define OP_CreateBtree 147 /* synopsis: r[P2]=root iDb=P1 flags=P3 */ -#define OP_SqlExec 148 -#define OP_ParseSchema 149 -#define OP_LoadAnalysis 150 -#define OP_DropTable 151 -#define OP_DropIndex 152 -#define OP_DropTrigger 153 -#define OP_Real 154 /* same as TK_FLOAT, synopsis: r[P2]=P4 */ -#define OP_IntegrityCk 155 -#define OP_RowSetAdd 156 /* synopsis: rowset(P1)=r[P2] */ -#define OP_Param 157 -#define OP_FkCounter 158 /* synopsis: fkctr[P1]+=P2 */ -#define OP_MemMax 159 /* synopsis: r[P1]=max(r[P1],r[P2]) */ -#define OP_OffsetLimit 160 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */ -#define OP_AggInverse 161 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */ -#define OP_AggStep 162 /* synopsis: accum=r[P3] step(r[P2@P5]) */ -#define OP_AggStep1 163 /* synopsis: accum=r[P3] step(r[P2@P5]) */ -#define OP_AggValue 164 /* synopsis: r[P3]=value N=P2 */ -#define OP_AggFinal 165 /* synopsis: accum=r[P1] N=P2 */ -#define OP_Expire 166 -#define OP_CursorLock 167 -#define OP_CursorUnlock 168 -#define OP_TableLock 169 /* synopsis: iDb=P1 root=P2 write=P3 */ -#define OP_VBegin 170 -#define OP_VCreate 171 -#define OP_VDestroy 172 -#define OP_VOpen 173 -#define OP_VCheck 174 -#define OP_VInitIn 175 /* synopsis: r[P2]=ValueList(P1,P3) */ -#define OP_VColumn 176 /* synopsis: r[P3]=vcolumn(P2) */ -#define OP_VRename 177 -#define OP_Pagecount 178 -#define OP_MaxPgcnt 179 -#define OP_ClrSubtype 180 /* synopsis: r[P1].subtype = 0 */ -#define OP_GetSubtype 181 /* synopsis: r[P2] = r[P1].subtype */ -#define OP_SetSubtype 182 /* synopsis: r[P2].subtype = r[P1] */ -#define OP_FilterAdd 183 /* synopsis: filter(P1) += key(P3@P4) */ -#define OP_Trace 184 -#define OP_CursorHint 185 -#define OP_ReleaseReg 186 /* synopsis: release r[P1@P2] mask P3 */ -#define OP_Noop 187 -#define OP_Explain 188 -#define OP_Abortable 189 +#define OP_OpenEphemeral 119 /* synopsis: nColumn=P2 */ +#define OP_SorterOpen 120 +#define OP_SequenceTest 121 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */ +#define OP_OpenPseudo 122 /* synopsis: P3 columns in r[P2] */ +#define OP_Close 123 +#define OP_ColumnsUsed 124 /* synopsis: Cursor P1 uses columns PHEX23 */ +#define OP_SeekScan 125 /* synopsis: Scan-ahead up to P1 rows */ +#define OP_SeekHit 126 /* synopsis: set P2<=seekHit<=P3 */ +#define OP_Sequence 127 /* synopsis: r[P2]=cursor[P1].ctr++ */ +#define OP_NewRowid 128 /* synopsis: r[P2]=rowid */ +#define OP_Insert 129 /* synopsis: intkey=r[P3] data=r[P2] */ +#define OP_RowCell 130 +#define OP_Delete 131 +#define OP_ResetCount 132 +#define OP_SorterCompare 133 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */ +#define OP_SorterData 134 /* synopsis: r[P2]=data */ +#define OP_RowData 135 /* synopsis: r[P2]=data */ +#define OP_Rowid 136 /* synopsis: r[P2]=PX rowid of P1 */ +#define OP_NullRow 137 +#define OP_SeekEnd 138 +#define OP_IdxInsert 139 /* synopsis: key=r[P2] */ +#define OP_SorterInsert 140 /* synopsis: key=r[P2] */ +#define OP_IdxDelete 141 /* synopsis: key=r[P2@P5] */ +#define OP_DeferredSeek 142 /* synopsis: Move P3 to P1.rowid if needed */ +#define OP_IdxRowid 143 /* synopsis: r[P2]=rowid */ +#define OP_FinishSeek 144 +#define OP_Destroy 145 +#define OP_Clear 146 +#define OP_ResetSorter 147 +#define OP_CreateBtree 148 /* synopsis: r[P2]=root iDb=P1 flags=P3 */ +#define OP_SqlExec 149 +#define OP_ParseSchema 150 +#define OP_LoadAnalysis 151 +#define OP_DropTable 152 +#define OP_DropIndex 153 +#define OP_Real 154 /* same as TK_FLOAT, synopsis: r[P2]=PDBL13 */ +#define OP_DropTrigger 155 +#define OP_IntegrityCk 156 +#define OP_RowSetAdd 157 /* synopsis: rowset(P1)=r[P2] */ +#define OP_Param 158 +#define OP_FkCounter 159 /* synopsis: fkctr[P1]+=P2 */ +#define OP_MemMax 160 /* synopsis: r[P1]=max(r[P1],r[P2]) */ +#define OP_OffsetLimit 161 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */ +#define OP_AggInverse 162 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */ +#define OP_AggStep 163 /* synopsis: accum=r[P3] step(r[P2@P5]) */ +#define OP_AggStep1 164 /* synopsis: accum=r[P3] step(r[P2@P5]) */ +#define OP_AggValue 165 /* synopsis: r[P3]=value N=P2 */ +#define OP_AggFinal 166 /* synopsis: accum=r[P1] N=P2 */ +#define OP_Expire 167 +#define OP_CursorLock 168 +#define OP_CursorUnlock 169 +#define OP_TableLock 170 /* synopsis: iDb=P1 root=P2 write=P3 */ +#define OP_VBegin 171 +#define OP_VCreate 172 +#define OP_VDestroy 173 +#define OP_VOpen 174 +#define OP_VCheck 175 +#define OP_VInitIn 176 /* synopsis: r[P2]=ValueList(P1,P3) */ +#define OP_VColumn 177 /* synopsis: r[P3]=vcolumn(P2) */ +#define OP_VRename 178 +#define OP_Pagecount 179 +#define OP_MaxPgcnt 180 +#define OP_ClrSubtype 181 /* synopsis: r[P1].subtype = 0 */ +#define OP_GetSubtype 182 /* synopsis: r[P2] = r[P1].subtype */ +#define OP_SetSubtype 183 /* synopsis: r[P2].subtype = r[P1] */ +#define OP_FilterAdd 184 /* synopsis: filter(P1) += key(P3@P4) */ +#define OP_Trace 185 +#define OP_CursorHint 186 +#define OP_ReleaseReg 187 /* synopsis: release r[P1@P2] mask P3 */ +#define OP_Noop 188 +#define OP_Explain 189 +#define OP_Abortable 190 /* Properties such as "out2" or "jump" that are specified in ** comments following the "case" for each opcode in the vdbe.c @@ -16990,27 +18075,27 @@ typedef struct VdbeOpList VdbeOpList; /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x41, 0x00,\ /* 8 */ 0x81, 0x01, 0x01, 0x81, 0x83, 0x83, 0x01, 0x01,\ /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0xc9, 0xc9, 0xc9,\ -/* 24 */ 0xc9, 0x01, 0x49, 0x49, 0x49, 0x49, 0xc9, 0x49,\ -/* 32 */ 0xc1, 0x01, 0x41, 0x41, 0xc1, 0x01, 0x41, 0x41,\ -/* 40 */ 0x41, 0x41, 0x41, 0x26, 0x26, 0x41, 0x23, 0x0b,\ -/* 48 */ 0x81, 0x01, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b,\ -/* 56 */ 0x0b, 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x01, 0x41,\ -/* 64 */ 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10,\ -/* 72 */ 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10, 0x00,\ -/* 80 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x02, 0x02,\ -/* 88 */ 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20, 0x40, 0x00,\ -/* 96 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x40, 0x26,\ +/* 24 */ 0xc9, 0x49, 0x49, 0x49, 0x49, 0xc9, 0x49, 0xc1,\ +/* 32 */ 0x01, 0x41, 0x41, 0xc1, 0x01, 0x01, 0x41, 0x41,\ +/* 40 */ 0x41, 0x41, 0x41, 0x26, 0x26, 0x41, 0x09, 0x23,\ +/* 48 */ 0x0b, 0x81, 0x01, 0x03, 0x03, 0x0b, 0x0b, 0x0b,\ +/* 56 */ 0x0b, 0x0b, 0x0b, 0x01, 0x03, 0x03, 0x03, 0x01,\ +/* 64 */ 0x41, 0x01, 0x00, 0x00, 0x02, 0x02, 0x08, 0x00,\ +/* 72 */ 0x10, 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10,\ +/* 80 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x02,\ +/* 88 */ 0x02, 0x02, 0x00, 0x00, 0x12, 0x1e, 0x20, 0x40,\ +/* 96 */ 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x40, 0x26,\ /* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\ -/* 112 */ 0x26, 0x00, 0x40, 0x12, 0x40, 0x40, 0x10, 0x00,\ -/* 120 */ 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x10, 0x10,\ -/* 128 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x50,\ -/* 136 */ 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50, 0x40,\ -/* 144 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\ -/* 152 */ 0x00, 0x00, 0x10, 0x00, 0x06, 0x10, 0x00, 0x04,\ -/* 160 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ -/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50,\ -/* 176 */ 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12, 0x00,\ -/* 184 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,} +/* 112 */ 0x26, 0x40, 0x00, 0x12, 0x40, 0x40, 0x10, 0x40,\ +/* 120 */ 0x00, 0x00, 0x00, 0x40, 0x00, 0x40, 0x40, 0x10,\ +/* 128 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00,\ +/* 136 */ 0x50, 0x00, 0x40, 0x04, 0x04, 0x00, 0x40, 0x50,\ +/* 144 */ 0x40, 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,\ +/* 152 */ 0x00, 0x00, 0x10, 0x00, 0x00, 0x06, 0x10, 0x00,\ +/* 160 */ 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ +/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x10,\ +/* 176 */ 0x50, 0x40, 0x00, 0x10, 0x10, 0x02, 0x12, 0x12,\ +/* 184 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,} /* The resolve3P2Values() routine is able to run faster if it knows ** the value of the largest JUMP opcode. The smaller the maximum @@ -17018,7 +18103,7 @@ typedef struct VdbeOpList VdbeOpList; ** generated this include file strives to group all JUMP opcodes ** together near the beginning of the list. */ -#define SQLITE_MX_JUMP_OPCODE 64 /* Maximum JUMP opcode */ +#define SQLITE_MX_JUMP_OPCODE 65 /* Maximum JUMP opcode */ /************** End of opcodes.h *********************************************/ /************** Continuing where we left off in vdbe.h ***********************/ @@ -17027,7 +18112,7 @@ typedef struct VdbeOpList VdbeOpList; ** Additional non-public SQLITE_PREPARE_* flags */ #define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */ -#define SQLITE_PREPARE_MASK 0x0f /* Mask of public flags */ +#define SQLITE_PREPARE_MASK 0x3f /* Mask of public flags */ /* ** Prototypes for the VDBE interface. See comments on the implementation @@ -17042,8 +18127,9 @@ SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int); SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*); SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...); SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeAddInt64(Vdbe*,int,i64); +SQLITE_PRIVATE int sqlite3VdbeAddDouble(Vdbe*,int,double); SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int); SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(Parse*,int,int,int,int,const FuncDef*,int); SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int); @@ -17135,14 +18221,17 @@ SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*); SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*); SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*); SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8); -SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int); +SQLITE_PRIVATE void sqlite3VdbeReprepareOnBind(Vdbe*, int, int); #ifndef SQLITE_OMIT_TRACE SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*); #endif SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*); SQLITE_PRIVATE int sqlite3BlobCompare(const Mem*, const Mem*); +#ifdef SQLITE_ENABLE_PERCENTILE +SQLITE_PRIVATE const char *sqlite3VdbeFuncName(const sqlite3_context*); +#endif -SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*); +SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(int,const void*,UnpackedRecord*); SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int); SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*); @@ -17155,13 +18244,15 @@ SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe*); SQLITE_PRIVATE void sqlite3MemSetArrayInt64(sqlite3_value *aMem, int iIdx, i64 val); +#ifndef SQLITE_OMIT_DATETIME_FUNCS SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*); +#endif #ifdef SQLITE_ENABLE_BYTECODE_VTAB SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3*); #endif -/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on -** each VDBE opcode. +/* Use SQLITE_ENABLE_EXPLAIN_COMMENTS to enable generation of extra +** comments on each VDBE opcode. ** ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op ** comments in VDBE programs that show key decision points in the code @@ -17289,6 +18380,7 @@ SQLITE_PRIVATE int sqlite3CursorRangeHintExprCheck(Walker *pWalker, Expr *pExpr) */ #ifndef _PCACHE_H_ +#define _PCACHE_H_ typedef struct PgHdr PgHdr; typedef struct PCache PCache; @@ -17304,10 +18396,10 @@ struct PgHdr { PCache *pCache; /* PRIVATE: Cache that owns this page */ PgHdr *pDirty; /* Transient list of dirty sorted by pgno */ Pager *pPager; /* The pager this page is part of */ - Pgno pgno; /* Page number for this page */ #ifdef SQLITE_CHECK_PAGES - u32 pageHash; /* Hash of page content */ + u64 pageHash; /* Hash of page content */ #endif + Pgno pgno; /* Page number for this page */ u16 flags; /* PGHDR flags defined below */ /********************************************************************** @@ -17511,7 +18603,7 @@ SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache); # define SQLITE_MUTEX_OMIT #endif #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP) -# if SQLITE_OS_UNIX +# if SQLITE_OS_UNIX || defined(__CYGWIN__) # define SQLITE_MUTEX_PTHREADS # elif SQLITE_OS_WIN # define SQLITE_MUTEX_W32 @@ -17647,7 +18739,7 @@ struct Schema { ** The number of different kinds of things that can be limited ** using the sqlite3_limit() interface. */ -#define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1) +#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_STEPS+1) /* ** Lookaside malloc is a set of fixed-size buffers that can be used @@ -17742,47 +18834,11 @@ struct FuncDefHash { }; #define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ) -#if defined(SQLITE_USER_AUTHENTICATION) -# warning "The SQLITE_USER_AUTHENTICATION extension is deprecated. \ - See ext/userauth/user-auth.txt for details." -#endif -#ifdef SQLITE_USER_AUTHENTICATION -/* -** Information held in the "sqlite3" database connection object and used -** to manage user authentication. -*/ -typedef struct sqlite3_userauth sqlite3_userauth; -struct sqlite3_userauth { - u8 authLevel; /* Current authentication level */ - int nAuthPW; /* Size of the zAuthPW in bytes */ - char *zAuthPW; /* Password used to authenticate */ - char *zAuthUser; /* User name used to authenticate */ -}; - -/* Allowed values for sqlite3_userauth.authLevel */ -#define UAUTH_Unknown 0 /* Authentication not yet checked */ -#define UAUTH_Fail 1 /* User authentication failed */ -#define UAUTH_User 2 /* Authenticated as a normal user */ -#define UAUTH_Admin 3 /* Authenticated as an administrator */ - -/* Functions used only by user authorization logic */ -SQLITE_PRIVATE int sqlite3UserAuthTable(const char*); -SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*); -SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*); -SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**); - -#endif /* SQLITE_USER_AUTHENTICATION */ - /* ** typedef for the authorization callback function. */ -#ifdef SQLITE_USER_AUTHENTICATION - typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*, - const char*, const char*); -#else - typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*, - const char*); -#endif +typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*, + const char*); #ifndef SQLITE_OMIT_DEPRECATED /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing @@ -17837,6 +18893,7 @@ struct sqlite3 { u8 noSharedCache; /* True if no shared-cache backends */ u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */ u8 eOpenState; /* Current condition of the connection */ + u8 nFpDigit; /* Significant digits to keep on double->text */ int nextPagesize; /* Pagesize after VACUUM if >0 */ i64 nChange; /* Value returned by sqlite3_changes() */ i64 nTotalChange; /* Value returned by sqlite3_total_changes() */ @@ -17845,9 +18902,9 @@ struct sqlite3 { struct sqlite3InitInfo { /* Information used during initialization */ Pgno newTnum; /* Rootpage of table being initialized */ u8 iDb; /* Which db file is being initialized */ - u8 busy; /* TRUE if currently initializing */ + u8 busy; /* TRUE if initing. 2 if due to ADD COLUMN */ unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */ - unsigned imposterTable : 1; /* Building an imposter table */ + unsigned imposterTable : 2; /* Building an imposter table */ unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */ const char **azInit; /* "type", "name", and "tbl_name" columns */ } init; @@ -17920,12 +18977,17 @@ struct sqlite3 { Savepoint *pSavepoint; /* List of active savepoints */ int nAnalysisLimit; /* Number of index rows to ANALYZE */ int busyTimeout; /* Busy handler timeout, in msec */ +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + int setlkTimeout; /* Blocking lock timeout, in msec. -1 -> inf. */ + int setlkFlags; /* Flags passed to setlk_timeout() */ +#endif int nSavepoint; /* Number of non-transaction savepoints */ int nStatement; /* Number of nested statement-transactions */ i64 nDeferredCons; /* Net deferred constraints this transaction. */ i64 nDeferredImmCons; /* Net deferred immediate constraints */ int *pnBytesFreed; /* If not NULL, increment this in DbFree() */ DbClientData *pDbData; /* sqlite3_set_clientdata() content */ + u64 nSpill; /* TEMP content spilled to disk */ #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY /* The following variables are all protected by the STATIC_MAIN ** mutex, not by sqlite3.mutex. They are used by code in notify.c. @@ -17943,9 +19005,6 @@ struct sqlite3 { void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ #endif -#ifdef SQLITE_USER_AUTHENTICATION - sqlite3_userauth auth; /* User authentication information */ -#endif }; /* @@ -18009,6 +19068,9 @@ struct sqlite3 { #define SQLITE_CorruptRdOnly HI(0x00002) /* Prohibit writes due to error */ #define SQLITE_ReadUncommit HI(0x00004) /* READ UNCOMMITTED in shared-cache */ #define SQLITE_FkNoAction HI(0x00008) /* Treat all FK as NO ACTION */ +#define SQLITE_AttachCreate HI(0x00010) /* ATTACH allowed to create new dbs */ +#define SQLITE_AttachWrite HI(0x00020) /* ATTACH allowed to open for write */ +#define SQLITE_Comments HI(0x00040) /* Enable SQL comments */ /* Flags used only if debugging */ #ifdef SQLITE_DEBUG @@ -18039,7 +19101,7 @@ struct sqlite3 { #define SQLITE_QueryFlattener 0x00000001 /* Query flattening */ #define SQLITE_WindowFunc 0x00000002 /* Use xInverse for window functions */ #define SQLITE_GroupByOrder 0x00000004 /* GROUPBY cover of ORDERBY */ -#define SQLITE_FactorOutConst 0x00000008 /* Constant factoring */ + /* 0x00000008 -- Available for reuse */ #define SQLITE_DistinctOpt 0x00000010 /* DISTINCT using indexes */ #define SQLITE_CoverIdxScan 0x00000020 /* Covering index scans */ #define SQLITE_OrderByIdxJoin 0x00000040 /* ORDER BY of joins via index */ @@ -18048,7 +19110,7 @@ struct sqlite3 { #define SQLITE_CountOfView 0x00000200 /* The count-of-view optimization */ #define SQLITE_CursorHints 0x00000400 /* Add OP_CursorHint opcodes */ #define SQLITE_Stat4 0x00000800 /* Use STAT4 data */ - /* TH3 expects this value ^^^^^^^^^^ to be 0x0000800. Don't change it */ + /* TH3 expects this value ^^^^^^^^^^ */ #define SQLITE_PushDown 0x00001000 /* WHERE-clause push-down opt */ #define SQLITE_SimplifyJoin 0x00002000 /* Convert LEFT JOIN to JOIN */ #define SQLITE_SkipScan 0x00004000 /* Skip-scans */ @@ -18056,18 +19118,22 @@ struct sqlite3 { #define SQLITE_MinMaxOpt 0x00010000 /* The min/max optimization */ #define SQLITE_SeekScan 0x00020000 /* The OP_SeekScan optimization */ #define SQLITE_OmitOrderBy 0x00040000 /* Omit pointless ORDER BY */ - /* TH3 expects this value ^^^^^^^^^^ to be 0x40000. Coordinate any change */ -#define SQLITE_BloomFilter 0x00080000 /* Use a Bloom filter on searches */ -#define SQLITE_BloomPulldown 0x00100000 /* Run Bloom filters early */ + /* TH3 expects this value ^^^^^^^^^^ */ +#define SQLITE_BloomFilter 0x00080000 /* Use a Bloom filters */ + /* TH3 expects this value ^^^^^^^^^^ */ + /* 0x00100000 -- Available for reuse */ #define SQLITE_BalancedMerge 0x00200000 /* Balance multi-way merges */ #define SQLITE_ReleaseReg 0x00400000 /* Use OP_ReleaseReg for testing */ #define SQLITE_FlttnUnionAll 0x00800000 /* Disable the UNION ALL flattener */ - /* TH3 expects this value ^^^^^^^^^^ See flatten04.test */ + /* TH3 expects this value ^^^^^^^^^^ */ #define SQLITE_IndexedExpr 0x01000000 /* Pull exprs from index when able */ #define SQLITE_Coroutines 0x02000000 /* Co-routines for subqueries */ #define SQLITE_NullUnusedCols 0x04000000 /* NULL unused columns in subqueries */ #define SQLITE_OnePass 0x08000000 /* Single-pass DELETE and UPDATE */ #define SQLITE_OrderBySubq 0x10000000 /* ORDER BY in subquery helps outer */ +#define SQLITE_StarQuery 0x20000000 /* Heurists for star queries */ +#define SQLITE_ExistsToJoin 0x40000000 /* The EXISTS-to-JOIN optimization */ +#define SQLITE_UnionLimit 0x80000000 /* Optimizations for UNION + LIMIT */ #define SQLITE_AllOpts 0xffffffff /* All optimizations */ /* @@ -18104,7 +19170,7 @@ struct sqlite3 { ** field is used by per-connection app-def functions. */ struct FuncDef { - i8 nArg; /* Number of arguments. -1 means unlimited */ + i16 nArg; /* Number of arguments. -1 means unlimited */ u32 funcFlags; /* Some combination of SQLITE_FUNC_* */ void *pUserData; /* User data parameter */ FuncDef *pNext; /* Next function with same name */ @@ -18306,7 +19372,7 @@ struct FuncDestructor { #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ {nArg, SQLITE_FUNC_BUILTIN|\ SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ - pArg, 0, xFunc, 0, 0, 0, #zName, } + pArg, 0, xFunc, 0, 0, 0, #zName, {0} } #define LIKEFUNC(zName, nArg, arg, flags) \ {nArg, SQLITE_FUNC_BUILTIN|SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \ (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} } @@ -18473,6 +19539,7 @@ struct CollSeq { #define SQLITE_AFF_INTEGER 0x44 /* 'D' */ #define SQLITE_AFF_REAL 0x45 /* 'E' */ #define SQLITE_AFF_FLEXNUM 0x46 /* 'F' */ +#define SQLITE_AFF_DEFER 0x58 /* 'X' - defer computation until later */ #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) @@ -18597,6 +19664,7 @@ struct Table { } u; Trigger *pTrigger; /* List of triggers on this object */ Schema *pSchema; /* Schema that contains this table */ + u8 aHx[16]; /* Column aHt[K%sizeof(aHt)] might have hash K */ }; /* @@ -18632,6 +19700,7 @@ struct Table { #define TF_Ephemeral 0x00004000 /* An ephemeral table */ #define TF_Eponymous 0x00008000 /* An eponymous virtual table */ #define TF_Strict 0x00010000 /* STRICT mode */ +#define TF_Imposter 0x00020000 /* An imposter table */ /* ** Allowed values for Table.eTabType @@ -18730,9 +19799,13 @@ struct FKey { struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ int iFrom; /* Index of column in pFrom */ char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */ - } aCol[1]; /* One entry for each of nCol columns */ + } aCol[FLEXARRAY]; /* One entry for each of nCol columns */ }; +/* The size (in bytes) of an FKey object holding N columns. The answer +** does NOT include space to hold the zTo name. */ +#define SZ_FKEY(N) (offsetof(FKey,aCol)+(N)*sizeof(struct sColMap)) + /* ** SQLite supports many different ways to resolve a constraint ** error. ROLLBACK processing means that a constraint violation @@ -18783,9 +19856,15 @@ struct FKey { ** argument to sqlite3VdbeKeyCompare and is used to control the ** comparison of the two index keys. ** -** Note that aSortOrder[] and aColl[] have nField+1 slots. There -** are nField slots for the columns of an index then one extra slot -** for the rowid at the end. +** The aSortOrder[] and aColl[] arrays have nAllField slots each. There +** are nKeyField slots for the columns of an index then extra slots +** for the rowid or key at the end. The aSortOrder array is located after +** the aColl[] array. +** +** If SQLITE_ENABLE_PREUPDATE_HOOK is defined, then aSortFlags might be NULL +** to indicate that this object is for use by a preupdate hook. When aSortFlags +** is NULL, then nAllField is uninitialized and no space is allocated for +** aColl[], so those fields may not be used. */ struct KeyInfo { u32 nRef; /* Number of references to this KeyInfo object */ @@ -18794,9 +19873,21 @@ struct KeyInfo { u16 nAllField; /* Total columns, including key plus others */ sqlite3 *db; /* The database connection */ u8 *aSortFlags; /* Sort order for each column. */ - CollSeq *aColl[1]; /* Collating sequence for each term of the key */ + CollSeq *aColl[FLEXARRAY]; /* Collating sequence for each term of the key */ }; +/* The size (in bytes) of a KeyInfo object with up to N fields. This includes +** the main body of the KeyInfo object and the aColl[] array of N elements, +** but does not count the memory used to hold aSortFlags[]. */ +#define SZ_KEYINFO(N) (offsetof(KeyInfo,aColl) + (N)*sizeof(CollSeq*)) + +/* The size of a bare KeyInfo with no aColl[] entries */ +#if FLEXARRAY+1 > 1 +# define SZ_KEYINFO_0 offsetof(KeyInfo,aColl) +#else +# define SZ_KEYINFO_0 sizeof(KeyInfo) +#endif + /* ** Allowed bit values for entries in the KeyInfo.aSortFlags[] array. */ @@ -18815,9 +19906,8 @@ struct KeyInfo { ** ** An instance of this object serves as a "key" for doing a search on ** an index b+tree. The goal of the search is to find the entry that -** is closed to the key described by this object. This object might hold -** just a prefix of the key. The number of fields is given by -** pKeyInfo->nField. +** is closest to the key described by this object. This object might hold +** just a prefix of the key. The number of fields is given by nField. ** ** The r1 and r2 fields are the values to return if this key is less than ** or greater than a key in the btree, respectively. These are normally @@ -18827,7 +19917,7 @@ struct KeyInfo { ** The key comparison functions actually return default_rc when they find ** an equals comparison. default_rc can be -1, 0, or +1. If there are ** multiple entries in the b-tree with the same key (when only looking -** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to +** at the first nField elements) then default_rc can be set to -1 to ** cause the search to find the last match, or +1 to cause the search to ** find the first match. ** @@ -18839,8 +19929,8 @@ struct KeyInfo { ** b-tree. */ struct UnpackedRecord { - KeyInfo *pKeyInfo; /* Collation and sort-order information */ - Mem *aMem; /* Values */ + KeyInfo *pKeyInfo; /* Comparison info for the index that is unpacked */ + Mem *aMem; /* Values for columns of the index */ union { char *z; /* Cache of aMem[0].z for vdbeRecordCompareString() */ i64 i; /* Cache of aMem[0].u.i for vdbeRecordCompareInt() */ @@ -18916,7 +20006,7 @@ struct Index { Pgno tnum; /* DB Page containing root of this index */ LogEst szIdxRow; /* Estimated average row size in bytes */ u16 nKeyCol; /* Number of columns forming the key */ - u16 nColumn; /* Number of columns stored in the index */ + u16 nColumn; /* Nr columns in btree. Can be 2*Table.nCol */ u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ unsigned idxType:2; /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */ unsigned bUnordered:1; /* Use this index for == or IN queries only */ @@ -18925,7 +20015,6 @@ struct Index { unsigned isCovering:1; /* True if this is a covering index */ unsigned noSkipScan:1; /* Do not try to use skip-scan if true */ unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */ - unsigned bLowQual:1; /* sqlite_stat1 says this is a low-quality index */ unsigned bNoQuery:1; /* Do not use this index to optimize queries */ unsigned bAscKeyBug:1; /* True if the bba7b69f9849b5bf bug applies */ unsigned bHasVCol:1; /* Index references one or more VIRTUAL columns */ @@ -19015,7 +20104,7 @@ struct AggInfo { ** from source tables rather than from accumulators */ u8 useSortingIdx; /* In direct mode, reference the sorting index rather ** than the source table */ - u16 nSortingColumn; /* Number of columns in the sorting index */ + u32 nSortingColumn; /* Number of columns in the sorting index */ int sortingIdx; /* Cursor number of the sorting index */ int sortingIdxPTab; /* Cursor number of pseudo-table */ int iFirstReg; /* First register in range for aCol[] and aFunc[] */ @@ -19024,8 +20113,8 @@ struct AggInfo { Table *pTab; /* Source table */ Expr *pCExpr; /* The original expression */ int iTable; /* Cursor number of the source table */ - i16 iColumn; /* Column number within the source table */ - i16 iSorterColumn; /* Column number in the sorting index */ + int iColumn; /* Column number within the source table */ + int iSorterColumn; /* Column number in the sorting index */ } *aCol; int nColumn; /* Number of used entries in aCol[] */ int nAccumulator; /* Number of columns that show through to the output. @@ -19200,6 +20289,7 @@ struct Expr { Table *pTab; /* TK_COLUMN: Table containing column. Can be NULL ** for a column of an index on an expression */ Window *pWin; /* EP_WinFunc: Window/Filter defn for a function */ + int nReg; /* TK_NULLS: Number of registers to NULL out */ struct { /* TK_IN, TK_SELECT, and TK_EXISTS */ int iAddr; /* Subroutine entry address */ int regReturn; /* Register used to hold return address */ @@ -19254,10 +20344,10 @@ struct Expr { /* Macros can be used to test, set, or clear bits in the ** Expr.flags field. */ -#define ExprHasProperty(E,P) (((E)->flags&(P))!=0) -#define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P)) -#define ExprSetProperty(E,P) (E)->flags|=(P) -#define ExprClearProperty(E,P) (E)->flags&=~(P) +#define ExprHasProperty(E,P) (((E)->flags&(u32)(P))!=0) +#define ExprHasAllProperty(E,P) (((E)->flags&(u32)(P))==(u32)(P)) +#define ExprSetProperty(E,P) (E)->flags|=(u32)(P) +#define ExprClearProperty(E,P) (E)->flags&=~(u32)(P) #define ExprAlwaysTrue(E) (((E)->flags&(EP_OuterON|EP_IsTrue))==EP_IsTrue) #define ExprAlwaysFalse(E) (((E)->flags&(EP_OuterON|EP_IsFalse))==EP_IsFalse) #define ExprIsFullSize(E) (((E)->flags&(EP_Reduced|EP_TokenOnly))==0) @@ -19369,9 +20459,14 @@ struct ExprList { int iConstExprReg; /* Register in which Expr value is cached. Used only ** by Parse.pConstExpr */ } u; - } a[1]; /* One slot for each expression in the list */ + } a[FLEXARRAY]; /* One slot for each expression in the list */ }; +/* The size (in bytes) of an ExprList object that is big enough to hold +** as many as N expressions. */ +#define SZ_EXPRLIST(N) \ + (offsetof(ExprList,a) + (N)*sizeof(struct ExprList_item)) + /* ** Allowed values for Expr.a.eEName */ @@ -19397,16 +20492,14 @@ struct ExprList { */ struct IdList { int nId; /* Number of identifiers on the list */ - u8 eU4; /* Which element of a.u4 is valid */ struct IdList_item { char *zName; /* Name of the identifier */ - union { - int idx; /* Index in some Table.aCol[] of a column named zName */ - Expr *pExpr; /* Expr to implement a USING variable -- NOT USED */ - } u4; - } a[1]; + } a[FLEXARRAY]; }; +/* The size (in bytes) of an IdList object that can hold up to N IDs. */ +#define SZ_IDLIST(N) (offsetof(IdList,a)+(N)*sizeof(struct IdList_item)) + /* ** Allowed values for IdList.eType, which determines which value of the a.u4 ** is valid. @@ -19486,6 +20579,7 @@ struct SrcItem { unsigned rowidUsed :1; /* The ROWID of this table is referenced */ unsigned fixedSchema :1; /* Uses u4.pSchema, not u4.zDatabase */ unsigned hadSchema :1; /* Had u4.zDatabase before u4.pSchema */ + unsigned fromExists :1; /* Comes from WHERE EXISTS(...) */ } fg; int iCursor; /* The VDBE cursor number used to access this table */ Bitmask colUsed; /* Bit N set if column N used. Details above for N>62 */ @@ -19526,11 +20620,19 @@ struct OnOrUsing { ** */ struct SrcList { - int nSrc; /* Number of tables or subqueries in the FROM clause */ - u32 nAlloc; /* Number of entries allocated in a[] below */ - SrcItem a[1]; /* One entry for each identifier on the list */ + int nSrc; /* Number of tables or subqueries in the FROM clause */ + u32 nAlloc; /* Number of entries allocated in a[] below */ + SrcItem a[FLEXARRAY]; /* One entry for each identifier on the list */ }; +/* Size (in bytes) of a SrcList object that can hold as many as N +** SrcItem objects. */ +#define SZ_SRCLIST(N) (offsetof(SrcList,a)+(N)*sizeof(SrcItem)) + +/* Size (in bytes( of a SrcList object that holds 1 SrcItem. This is a +** special case of SZ_SRCITEM(1) that comes up often. */ +#define SZ_SRCLIST_1 (offsetof(SrcList,a)+sizeof(SrcItem)) + /* ** Permitted values of the SrcList.a.jointype field */ @@ -19688,19 +20790,6 @@ struct Upsert { /* ** An instance of the following structure contains all information ** needed to generate code for a single SELECT statement. -** -** See the header comment on the computeLimitRegisters() routine for a -** detailed description of the meaning of the iLimit and iOffset fields. -** -** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes. -** These addresses must be stored so that we can go back and fill in -** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor -** the number of columns in P2 can be computed at the same time -** as the OP_OpenEphm instruction is coded because not -** enough information about the compound query is known at that point. -** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences -** for the result set. The KeyInfo for addrOpenEphm[2] contains collating -** sequences for the ORDER BY clause. */ struct Select { u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */ @@ -19708,7 +20797,6 @@ struct Select { u32 selFlags; /* Various SF_* values */ int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */ u32 selId; /* Unique identifier number for this SELECT */ - int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */ ExprList *pEList; /* The fields of the result */ SrcList *pSrc; /* The FROM clause */ Expr *pWhere; /* The WHERE clause */ @@ -19740,7 +20828,7 @@ struct Select { #define SF_Resolved 0x0000004 /* Identifiers have been resolved */ #define SF_Aggregate 0x0000008 /* Contains agg functions or a GROUP BY */ #define SF_HasAgg 0x0000010 /* Contains aggregate functions */ -#define SF_UsesEphemeral 0x0000020 /* Uses the OpenEphemeral opcode */ +#define SF_ClonedRhsIn 0x0000020 /* Cloned RHS of an IN operator */ #define SF_Expanded 0x0000040 /* sqlite3SelectExpand() called on this */ #define SF_HasTypeInfo 0x0000080 /* FROM subqueries have Table metadata */ #define SF_Compound 0x0000100 /* Part of a compound query */ @@ -19750,14 +20838,14 @@ struct Select { #define SF_MinMaxAgg 0x0001000 /* Aggregate containing min() or max() */ #define SF_Recursive 0x0002000 /* The recursive part of a recursive CTE */ #define SF_FixedLimit 0x0004000 /* nSelectRow set by a constant LIMIT */ -#define SF_MaybeConvert 0x0008000 /* Need convertCompoundSelectToSubquery() */ +/* 0x0008000 // available for reuse */ #define SF_Converted 0x0010000 /* By convertCompoundSelectToSubquery() */ #define SF_IncludeHidden 0x0020000 /* Include hidden columns in output */ #define SF_ComplexResult 0x0040000 /* Result contains subquery or function */ #define SF_WhereBegin 0x0080000 /* Really a WhereBegin() call. Debug Only */ #define SF_WinRewrite 0x0100000 /* Window function rewrite accomplished */ #define SF_View 0x0200000 /* SELECT statement is a view */ -#define SF_NoopOrderBy 0x0400000 /* ORDER BY is ignored for this query */ +/* 0x0400000 // available for reuse */ #define SF_UFSrcCheck 0x0800000 /* Check pSrc as required by UPDATE...FROM */ #define SF_PushDown 0x1000000 /* Modified by WHERE-clause push-down opt */ #define SF_MultiPart 0x2000000 /* Has multiple incompatible PARTITIONs */ @@ -19765,6 +20853,7 @@ struct Select { #define SF_OrderByReqd 0x8000000 /* The ORDER BY clause may not be omitted */ #define SF_UpdateFrom 0x10000000 /* Query originates with UPDATE FROM */ #define SF_Correlated 0x20000000 /* True if references the outer context */ +#define SF_OnToWhere 0x40000000 /* One or more ON clauses moved to WHERE */ /* True if SrcItem X is a subquery that has SF_NestedFrom */ #define IsNestedFrom(X) \ @@ -19776,11 +20865,6 @@ struct Select { ** by one of the following macros. The "SRT" prefix means "SELECT Result ** Type". ** -** SRT_Union Store results as a key in a temporary index -** identified by pDest->iSDParm. -** -** SRT_Except Remove results from the temporary index pDest->iSDParm. -** ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result ** set is not empty. ** @@ -19844,30 +20928,28 @@ struct Select { ** table. (pDest->iSDParm) is the number of key columns in ** each index record in this case. */ -#define SRT_Union 1 /* Store result as keys in an index */ -#define SRT_Except 2 /* Remove result from a UNION index */ -#define SRT_Exists 3 /* Store 1 if the result is not empty */ -#define SRT_Discard 4 /* Do not save the results anywhere */ -#define SRT_DistFifo 5 /* Like SRT_Fifo, but unique results only */ -#define SRT_DistQueue 6 /* Like SRT_Queue, but unique results only */ +#define SRT_Exists 1 /* Store 1 if the result is not empty */ +#define SRT_Discard 2 /* Do not save the results anywhere */ +#define SRT_DistFifo 3 /* Like SRT_Fifo, but unique results only */ +#define SRT_DistQueue 4 /* Like SRT_Queue, but unique results only */ /* The DISTINCT clause is ignored for all of the above. Not that ** IgnorableDistinct() implies IgnorableOrderby() */ #define IgnorableDistinct(X) ((X->eDest)<=SRT_DistQueue) -#define SRT_Queue 7 /* Store result in an queue */ -#define SRT_Fifo 8 /* Store result as data with an automatic rowid */ +#define SRT_Queue 5 /* Store result in an queue */ +#define SRT_Fifo 6 /* Store result as data with an automatic rowid */ /* The ORDER BY clause is ignored for all of the above */ #define IgnorableOrderby(X) ((X->eDest)<=SRT_Fifo) -#define SRT_Output 9 /* Output each row of result */ -#define SRT_Mem 10 /* Store result in a memory cell */ -#define SRT_Set 11 /* Store results as keys in an index */ -#define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */ -#define SRT_Coroutine 13 /* Generate a single row of result */ -#define SRT_Table 14 /* Store result as data with an automatic rowid */ -#define SRT_Upfrom 15 /* Store result as data with rowid */ +#define SRT_Output 7 /* Output each row of result */ +#define SRT_Mem 8 /* Store result in a memory cell */ +#define SRT_Set 9 /* Store results as keys in an index */ +#define SRT_EphemTab 10 /* Create transient tab and store like SRT_Table */ +#define SRT_Coroutine 11 /* Generate a single row of result */ +#define SRT_Table 12 /* Store result as data with an automatic rowid */ +#define SRT_Upfrom 13 /* Store result as data with rowid */ /* ** An instance of this object describes where to put of the results of @@ -19978,6 +21060,13 @@ struct ParseCleanup { void (*xCleanup)(sqlite3*,void*); /* Deallocation routine */ }; +/* +** Number of 64-bit entried in the variable number bitmap cache (VNBMC). +*/ +#ifndef SQLITE_VNBMC +# define SQLITE_VNBMC 2 +#endif + /* ** An SQL parser context. A copy of this structure is passed through ** the parser and down into all the parser action routine in order to @@ -19999,25 +21088,34 @@ struct Parse { char *zErrMsg; /* An error message */ Vdbe *pVdbe; /* An engine for executing database bytecode */ int rc; /* Return code from execution */ - u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */ - u8 checkSchema; /* Causes schema cookie check after an error */ + LogEst nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */ u8 nested; /* Number of nested calls to the parser/code generator */ u8 nTempReg; /* Number of temporary registers in aTempReg[] */ u8 isMultiWrite; /* True if statement may modify/insert multiple rows */ - u8 mayAbort; /* True if statement may throw an ABORT exception */ - u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */ - u8 okConstFactor; /* OK to factor out constants */ u8 disableLookaside; /* Number of times lookaside has been disabled */ u8 prepFlags; /* SQLITE_PREPARE_* flags */ u8 withinRJSubrtn; /* Nesting level for RIGHT JOIN body subroutines */ - u8 bHasWith; /* True if statement contains WITH */ u8 mSubrtnSig; /* mini Bloom filter on available SubrtnSig.selId */ + u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */ + u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */ #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) u8 earlyCleanup; /* OOM inside sqlite3ParserAddCleanup() */ #endif #ifdef SQLITE_DEBUG u8 ifNotExists; /* Might be true if IF NOT EXISTS. Assert()s only */ -#endif + u8 isCreate; /* CREATE TABLE, INDEX, or VIEW (but not TRIGGER) + ** and ALTER TABLE ADD COLUMN. */ +#endif + bft disableTriggers:1; /* True to disable triggers */ + bft mayAbort :1; /* True if statement may throw an ABORT exception */ + bft hasCompound :1; /* Need to invoke convertCompoundSelectToSubquery() */ + bft bReturning :1; /* Coding a RETURNING trigger */ + bft bHasExists :1; /* Has a correlated "EXISTS (SELECT ....)" expression */ + bft colNamesSet :1; /* TRUE after OP_ColumnName has been issued to pVdbe */ + bft bHasWith :1; /* True if statement contains WITH */ + bft okConstFactor:1; /* OK to factor out constants */ + bft checkSchema :1; /* Causes schema cookie check after an error */ + bft usesAinc :1; /* True if pAinc is valid */ int nRangeReg; /* Size of the temporary register block */ int iRangeReg; /* First register in temporary register block */ int nErr; /* Number of errors seen */ @@ -20026,42 +21124,27 @@ struct Parse { int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */ int iSelfTab; /* Table associated with an index on expr, or negative ** of the base register during check-constraint eval */ + int nNestSel; /* Number of nested SELECT statements and/or VIEWs */ int nLabel; /* The *negative* of the number of labels used */ int nLabelAlloc; /* Number of slots in aLabel */ int *aLabel; /* Space to hold the labels */ ExprList *pConstExpr;/* Constant expressions */ IndexedExpr *pIdxEpr;/* List of expressions used by active indexes */ IndexedExpr *pIdxPartExpr; /* Exprs constrained by index WHERE clauses */ - Token constraintName;/* Name of the constraint currently being parsed */ yDbMask writeMask; /* Start a write transaction on these databases */ yDbMask cookieMask; /* Bitmask of schema verified databases */ - int regRowid; /* Register holding rowid of CREATE TABLE entry */ - int regRoot; /* Register holding root page number for new objects */ - int nMaxArg; /* Max args passed to user function by sub-program */ + int nMaxArg; /* Max args to xUpdate and xFilter vtab methods */ int nSelect; /* Number of SELECT stmts. Counter for Select.selId */ #ifndef SQLITE_OMIT_PROGRESS_CALLBACK u32 nProgressSteps; /* xProgress steps taken during sqlite3_prepare() */ #endif #ifndef SQLITE_OMIT_SHARED_CACHE int nTableLock; /* Number of locks in aTableLock */ - TableLock *aTableLock; /* Required table locks for shared-cache mode */ #endif - AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */ Parse *pToplevel; /* Parse structure for main program (or NULL) */ Table *pTriggerTab; /* Table triggers are being coded for */ TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */ ParseCleanup *pCleanup; /* List of cleanup operations to run after parse */ - union { - int addrCrTab; /* Address of OP_CreateBtree on CREATE TABLE */ - Returning *pReturning; /* The RETURNING clause */ - } u1; - u32 oldmask; /* Mask of old.* columns referenced */ - u32 newmask; /* Mask of new.* columns referenced */ - LogEst nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */ - u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */ - u8 bReturning; /* Coding a RETURNING trigger */ - u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */ - u8 disableTriggers; /* True to disable triggers */ /************************************************************************** ** Fields above must be initialized to zero. The fields that follow, @@ -20073,6 +21156,26 @@ struct Parse { int aTempReg[8]; /* Holding area for temporary registers */ Parse *pOuterParse; /* Outer Parse object when nested */ Token sNameToken; /* Token with unqualified schema object name */ + u32 oldmask; /* Mask of old.* columns referenced */ + u32 newmask; /* Mask of new.* columns referenced */ + union { + struct { /* These fields available when isCreate is true */ + int addrCrTab; /* Address of OP_CreateBtree on CREATE TABLE */ + int regRowid; /* Register holding rowid of CREATE TABLE entry */ + int regRoot; /* Register holding root page for new objects */ + Token constraintName; /* Name of the constraint currently being parsed */ + } cr; + struct { /* These fields available to all other statements */ + Returning *pReturning; /* The RETURNING clause */ + } d; + } u1; + AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters. Only + ** valid if Parse.usesAinc is true */ +#ifndef SQLITE_OMIT_SHARED_CACHE + TableLock *aTableLock; /* Required table locks for shared-cache mode. Only + ** valid if Parse.nTableLock>0 */ +#endif + /************************************************************************ ** Above is constant between recursions. Below is reset before and after @@ -20083,6 +21186,7 @@ struct Parse { Token sLastToken; /* The last token parsed */ ynVar nVar; /* Number of '?' variables seen in the SQL so far */ + u64 aVnbmc[SQLITE_VNBMC]; /* Varible Number Bitmap Cache */ u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */ u8 explain; /* True if the EXPLAIN flag is found on the query */ u8 eParseMode; /* PARSE_MODE_XXX constant */ @@ -20090,9 +21194,7 @@ struct Parse { int nVtabLock; /* Number of virtual tables to lock */ #endif int nHeight; /* Expression tree height of current sub-select */ -#ifndef SQLITE_OMIT_EXPLAIN int addrExplain; /* Address of current OP_Explain opcode */ -#endif VList *pVList; /* Mapping between variable names and numbers */ Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */ const char *zTail; /* All SQL text past the last semicolon parsed */ @@ -20249,19 +21351,19 @@ struct Trigger { ** orconf -> stores the ON CONFLICT algorithm ** pSelect -> The content to be inserted - either a SELECT statement or ** a VALUES clause. -** zTarget -> Dequoted name of the table to insert into. +** pSrc -> Table to insert into. ** pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ... ** statement, then this stores the column-names to be ** inserted into. ** pUpsert -> The ON CONFLICT clauses for an Upsert ** ** (op == TK_DELETE) -** zTarget -> Dequoted name of the table to delete from. +** pSrc -> Table to delete from ** pWhere -> The WHERE clause of the DELETE statement if one is specified. ** Otherwise NULL. ** ** (op == TK_UPDATE) -** zTarget -> Dequoted name of the table to update. +** pSrc -> Table to update, followed by any FROM clause tables. ** pWhere -> The WHERE clause of the UPDATE statement if one is specified. ** Otherwise NULL. ** pExprList -> A list of the columns to update and the expressions to update @@ -20281,8 +21383,7 @@ struct TriggerStep { u8 orconf; /* OE_Rollback etc. */ Trigger *pTrig; /* The trigger that this step is a part of */ Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */ - char *zTarget; /* Target table for DELETE, UPDATE, INSERT */ - SrcList *pFrom; /* FROM clause for UPDATE statement (if any) */ + SrcList *pSrc; /* Table to insert/update/delete */ Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */ ExprList *pExprList; /* SET clause for UPDATE, or RETURNING clause */ IdList *pIdList; /* Column names for INSERT */ @@ -20365,10 +21466,11 @@ typedef struct { /* ** Allowed values for mInitFlags */ -#define INITFLAG_AlterMask 0x0003 /* Types of ALTER */ +#define INITFLAG_AlterMask 0x0007 /* Types of ALTER */ #define INITFLAG_AlterRename 0x0001 /* Reparse after a RENAME */ #define INITFLAG_AlterDrop 0x0002 /* Reparse after a DROP COLUMN */ #define INITFLAG_AlterAdd 0x0003 /* Reparse after an ADD COLUMN */ +#define INITFLAG_AlterDropCons 0x0004 /* Reparse after a DROP CONSTRAINT */ /* Tuning parameters are set using SQLITE_TESTCTRL_TUNE and are controlled ** on debug-builds of the CLI using ".testctrl tune ID VALUE". Tuning @@ -20498,6 +21600,7 @@ struct Walker { NameContext *pNC; /* Naming context */ int n; /* A counter */ int iCur; /* A cursor number */ + int sz; /* String literal length */ SrcList *pSrcList; /* FROM clause */ struct CCurHint *pCCurHint; /* Used by codeCursorHint() */ struct RefSrcList *pRefSrcList; /* sqlite3ReferencesSrcList() */ @@ -20513,6 +21616,7 @@ struct Walker { SrcItem *pSrcItem; /* A single FROM clause item */ DbFixer *pFix; /* See sqlite3FixSelect() */ Mem *aMem; /* See sqlite3BtreeCursorHint() */ + struct CheckOnCtx *pCheckOnCtx; /* See selectCheckOnClauses() */ } u; }; @@ -20590,9 +21694,13 @@ struct With { int nCte; /* Number of CTEs in the WITH clause */ int bView; /* Belongs to the outermost Select of a view */ With *pOuter; /* Containing WITH clause, or NULL */ - Cte a[1]; /* For each CTE in the WITH clause.... */ + Cte a[FLEXARRAY]; /* For each CTE in the WITH clause.... */ }; +/* The size (in bytes) of a With object that can hold as many +** as N different CTEs. */ +#define SZ_WITH(N) (offsetof(With,a) + (N)*sizeof(Cte)) + /* ** The Cte object is not guaranteed to persist for the entire duration ** of code generation. (The query flattener or other parser tree @@ -20621,9 +21729,13 @@ struct DbClientData { DbClientData *pNext; /* Next in a linked list */ void *pData; /* The data */ void (*xDestructor)(void*); /* Destructor. Might be NULL */ - char zName[1]; /* Name of this client data. MUST BE LAST */ + char zName[FLEXARRAY]; /* Name of this client data. MUST BE LAST */ }; +/* The size (in bytes) of a DbClientData object that can has a name +** that is N bytes long, including the zero-terminator. */ +#define SZ_DBCLIENTDATA(N) (offsetof(DbClientData,zName)+(N)) + #ifdef SQLITE_DEBUG /* ** An instance of the TreeView object is used for printing the content of @@ -20719,6 +21831,57 @@ SQLITE_PRIVATE Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprLis /* ** Assuming zIn points to the first byte of a UTF-8 character, ** advance zIn to point to the first byte of the next UTF-8 character. +** +** # Dividing malformed UTF-8 into characters (tag-20260418-01) +** +** If a text input is malformed UTF-8, SQLite does not make any guarantees +** about how the bytes are divided up into characters. The system promises +** to not overflow an array or cause other memory errors when presented +** with malformed UTF-8. And it promises to preserve the specific +** sequence of bytes as long as no conversion occur. But beyond that, +** there are no guarantees. Results can vary from one version to the +** next. +** +** The SQLITE_SKIP_UTF8 macro below is one technique for dividing UTF-8 +** into characters. The length() and substr() SQL functions use a +** different technique when searching across multiple characters, a +** technique that exchanges a subtraction for comparison of z and results +** in faster machine code on some compilers and architectures. The code +** in substr() to skip over p1 characters goes something like this: +** +** for( ; p1>0; p1--){ +** // vvvv--- tag-20260418-01 +** if( (u8)(z[0]-1)<(0x80-1) ){ +** z++; +** }else if( z[0]==0 ){ +** break; +** }else{ +** do{ z++; }while( (z[0]&0xc0)==0x80 ); +** } +** } +** +** In valid UTF-8, multibyte characters always begin with a byte with the +** two most significant bits set and that is followed by one or more bytes +** for which the two most significant bits are 10. In other words: +** +** First byte: (BYTE & 0xc0)==0xc0 +** Following bytes: (BYTE & 0xc0)==0x80 +** +** What to do if the input byte sequence contain a "following byte" that +** is not preceded by a "first byte"? How many characters are in the +** byte sequence: 0x61 0x81 0x82 0x7a? 3 or 4 or something else? +** +** If you use the macro below, the answer will be 4. If you use the code +** snippet demonstrated at tag-20260418-01, then answer is 3. If you +** use a variant of tag-20260418-01 where the constant of comparison is +** 0xc0-1 instead of 0x80-1 then the answer is again 4. The key point is +** that because the input is malformed UTF-8, so is no "correct" answer. +** SQLite is free to use either value. +** +** It turns out that GCC 13.3.0 is able to generate faster code (at least +** on x86-64) if the constant at tag-20260418-01 is (0x80-1). If you make +** that constant (0xc0-1) instead, gcc 13.3.0 generates code that runs slower. +** So the (0x80-1) constant is used for substr() and length(). */ #define SQLITE_SKIP_UTF8(zIn) { \ if( (*(zIn++))>=0xc0 ){ \ @@ -20893,7 +22056,20 @@ SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*); SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void); SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void); -#if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT) + +/* The SQLITE_THREAD_MISUSE_WARNINGS compile-time option used to be called +** SQLITE_ENABLE_MULTITHREADED_CHECKS. Keep that older macro for backwards +** compatibility, at least for a while... */ +#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS +# define SQLITE_THREAD_MISUSE_WARNINGS 1 +#endif + +/* SQLITE_THREAD_MISUSE_ABORT implies SQLITE_THREAD_MISUSE_WARNINGS */ +#ifdef SQLITE_THREAD_MISUSE_ABORT +# define SQLITE_THREAD_MISUSE_WARNINGS 1 +#endif + +#if defined(SQLITE_THREAD_MISUSE_WARNINGS) && !defined(SQLITE_MUTEX_OMIT) SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*); #else # define sqlite3MutexWarnOnContention(x) @@ -20922,17 +22098,22 @@ struct PrintfArguments { sqlite3_value **apArg; /* The argument values */ }; +/* +** Maxium number of base-10 digits in an unsigned 64-bit integer +*/ +#define SQLITE_U64_DIGITS 20 + /* ** An instance of this object receives the decoding of a floating point ** value into an approximate decimal representation. */ struct FpDecode { - char sign; /* '+' or '-' */ - char isSpecial; /* 1: Infinity 2: NaN */ - int n; /* Significant digits in the decode */ - int iDP; /* Location of the decimal point */ - char *z; /* Start of significant digits */ - char zBuf[24]; /* Storage for significant digits */ + int n; /* Significant digits in the decode */ + int iDP; /* Location of the decimal point */ + char *z; /* Start of significant digits */ + char zBuf[SQLITE_U64_DIGITS+1]; /* Storage for significant digits */ + char sign; /* '+' or '-' */ + char isSpecial; /* 1: Infinity 2: NaN */ }; SQLITE_PRIVATE void sqlite3FpDecode(FpDecode*,double,int,int); @@ -20943,6 +22124,7 @@ SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...); #endif #if defined(SQLITE_TEST) SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*); +SQLITE_PRIVATE const char *sqlite3TestPtrToText(void*); #endif #if defined(SQLITE_DEBUG) @@ -20992,6 +22174,7 @@ SQLITE_PRIVATE void sqlite3ShowTriggerList(const Trigger*); SQLITE_PRIVATE void sqlite3ShowWindow(const Window*); SQLITE_PRIVATE void sqlite3ShowWinFunc(const Window*); #endif +SQLITE_PRIVATE void sqlite3ShowBitvec(Bitvec*); #endif SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*); @@ -21020,6 +22203,7 @@ SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int); #endif SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int); SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*); +SQLITE_PRIVATE Expr *sqlite3ExprInt32(sqlite3*,int); SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*); SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*); SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*); @@ -21042,6 +22226,7 @@ SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,const Token*,int); SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*); SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*); SQLITE_PRIVATE void sqlite3ExprListDeleteGeneric(sqlite3*,void*); +SQLITE_PRIVATE int sqlite3ExprCanReturnSubtype(Parse*,Expr*); SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*); SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index*); SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**); @@ -21057,6 +22242,7 @@ SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*); SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*); SQLITE_PRIVATE void sqlite3ColumnSetExpr(Parse*,Table*,Column*,Expr*); SQLITE_PRIVATE Expr *sqlite3ColumnExpr(Table*,Column*); +SQLITE_PRIVATE Expr *sqlite3ColumnExprAuth(Table*,Column*,Parse*); SQLITE_PRIVATE void sqlite3ColumnSetColl(sqlite3*,Column*,const char*zColl); SQLITE_PRIVATE const char *sqlite3ColumnColl(Column*); SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*); @@ -21066,7 +22252,7 @@ SQLITE_PRIVATE void sqlite3SubqueryColumnTypes(Parse*,Table*,Select*,char); SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*,char); SQLITE_PRIVATE void sqlite3OpenSchemaTable(Parse *, int); SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*); -SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index*, i16); +SQLITE_PRIVATE int sqlite3TableColumnToIndex(Index*, int); #ifdef SQLITE_OMIT_GENERATED_COLUMNS # define sqlite3TableColumnToStorage(T,X) (X) /* No-op pass-through */ # define sqlite3StorageColumnToTable(T,X) (X) /* No-op pass-through */ @@ -21164,7 +22350,8 @@ SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*); SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*); SQLITE_PRIVATE void sqlite3ClearOnOrUsing(sqlite3*, OnOrUsing*); SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*); -SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**); +SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,int,int,char**); +SQLITE_PRIVATE int sqlite3IndexBloomable(const Index*,int); SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*, Expr*, int, int, u8); SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int); @@ -21173,6 +22360,7 @@ SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList Expr*,ExprList*,u32,Expr*); SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*); SQLITE_PRIVATE void sqlite3SelectDeleteGeneric(sqlite3*,void*); +SQLITE_PRIVATE void sqlite3SelectCheckOnClauses(Parse *pParse, Select *pSelect); SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*); SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, Trigger*); SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int); @@ -21211,6 +22399,7 @@ SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Table*, Column*, int) SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int); SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int); SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int); +SQLITE_PRIVATE void sqlite3ExprNullRegisterRange(Parse*, int, int); SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*); SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int); SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8); @@ -21263,12 +22452,14 @@ SQLITE_PRIVATE int sqlite3ExprIsConstant(Parse*,Expr*); SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8); SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*); SQLITE_PRIVATE int sqlite3ExprIsSingleTableConstraint(Expr*,const SrcList*,int,int); +SQLITE_PRIVATE int sqlite3ExprListIsConstant(Parse *pParse, ExprList *pList, int bNoIs); #ifdef SQLITE_ENABLE_CURSOR_HINTS SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*); #endif -SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr*, int*, Parse*); +SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr*, int*, Parse*, int); SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*); SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char); +SQLITE_PRIVATE int sqlite3ExprIsLikeOperator(const Expr*); SQLITE_PRIVATE int sqlite3IsRowid(const char*); SQLITE_PRIVATE const char *sqlite3RowidAlias(Table *pTab); SQLITE_PRIVATE void sqlite3GenerateRowDelete( @@ -21300,19 +22491,24 @@ SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,const Select*,int); SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(int,const char*); SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int); SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8); -SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum*,sqlite3_value*); +SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum*,sqlite3_value*,int); +SQLITE_PRIVATE int sqlite3AppendOneUtf8Character(char*, u32); SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void); SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void); SQLITE_PRIVATE void sqlite3RegisterJsonFunctions(void); SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*); #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON) -SQLITE_PRIVATE int sqlite3JsonTableFunctions(sqlite3*); +SQLITE_PRIVATE Module *sqlite3JsonVtabRegister(sqlite3*,const char*); #endif SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*); SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*); SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int); SQLITE_PRIVATE With *sqlite3WithDup(sqlite3 *db, With *p); +#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_CARRAY) +SQLITE_PRIVATE Module *sqlite3CarrayRegister(sqlite3*); +#endif + #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int); #endif @@ -21332,17 +22528,16 @@ SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, i SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*); SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*, const char*,const char*); -SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*, +SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(Parse*,SrcList*, IdList*, Select*,u8,Upsert*, const char*,const char*); -SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,SrcList*,ExprList*, +SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(Parse*,SrcList*,SrcList*,ExprList*, Expr*, u8, const char*,const char*); -SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*, +SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(Parse*,SrcList*, Expr*, const char*,const char*); SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*); SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*); SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int); -SQLITE_PRIVATE SrcList *sqlite3TriggerStepSrc(Parse*, TriggerStep*); # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p)) # define sqlite3IsToplevel(p) ((p)->pToplevel==0) #else @@ -21356,7 +22551,6 @@ SQLITE_PRIVATE SrcList *sqlite3TriggerStepSrc(Parse*, TriggerStep*); # define sqlite3ParseToplevel(p) p # define sqlite3IsToplevel(p) 1 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0 -# define sqlite3TriggerStepSrc(A,B) 0 #endif SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*); @@ -21389,7 +22583,7 @@ SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*); SQLITE_PRIVATE int sqlite3RealSameAsInt(double,sqlite3_int64); SQLITE_PRIVATE i64 sqlite3RealToI64(double); SQLITE_PRIVATE int sqlite3Int64ToText(i64,char*); -SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8); +SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*); SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*); SQLITE_PRIVATE int sqlite3GetUInt32(const char*, u32*); SQLITE_PRIVATE int sqlite3Atoi(const char*); @@ -21414,6 +22608,7 @@ SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int); */ SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64); SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *); +SQLITE_PRIVATE i64 sqlite3VarintValue(const unsigned char*); SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *); SQLITE_PRIVATE int sqlite3VarintLen(u64 v); @@ -21429,9 +22624,6 @@ SQLITE_PRIVATE int sqlite3VarintLen(u64 v); #define putVarint32(A,B) \ (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\ sqlite3PutVarint((A),(B))) -#define getVarint sqlite3GetVarint -#define putVarint sqlite3PutVarint - SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*); SQLITE_PRIVATE char *sqlite3TableAffinityStr(sqlite3*,const Table*); @@ -21467,14 +22659,23 @@ SQLITE_PRIVATE int sqlite3IsMemdb(const sqlite3_vfs*); SQLITE_PRIVATE const char *sqlite3ErrStr(int); SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse); SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int); +SQLITE_PRIVATE int sqlite3BinaryCompare(void*,int,const void*,int,const void*); +#if SQLITE_USES_INLINE +static SQLITE_INLINE int sqlite3IsBinary(const CollSeq *p){ + assert( p==0 || p->xCmp!=sqlite3BinaryCompare + || strcmp(p->zName,"BINARY")==0 ); + return p==0 || p->xCmp==sqlite3BinaryCompare; +} +#else SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq*); +#endif SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName); SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8); SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr); SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr); SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const Expr*); -SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(const Parse *pParse, Expr*, const Token*, int); -SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(const Parse*,Expr*,const char*); +SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int); +SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*); SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*); SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr*); SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *); @@ -21521,6 +22722,7 @@ SQLITE_PRIVATE const unsigned char *sqlite3aGTb; SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[]; SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config; SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions; +SQLITE_PRIVATE const sqlite3_str sqlite3OomStr; #ifndef SQLITE_OMIT_WSD SQLITE_PRIVATE int sqlite3PendingByte; #endif @@ -21533,10 +22735,21 @@ SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*); SQLITE_PRIVATE void sqlite3AlterFunctions(void); SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*); SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*); -SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *); +SQLITE_PRIVATE void sqlite3AlterDropConstraint(Parse*,SrcList*,Token*,Token*); +SQLITE_PRIVATE void sqlite3AlterAddConstraint( + Parse *pParse, /* Parse context */ + SrcList *pSrc, /* Table to add constraint to */ + Token *pFirst, /* First token of new constraint */ + Token *pName, /* Name of new constraint. NULL if name omitted. */ + const char *zExpr, /* Text of CHECK expression */ + int nExpr, /* Size of pExpr in bytes */ + Expr *pExpr /* The parsed CHECK expression */ +); +SQLITE_PRIVATE void sqlite3AlterSetNotNull(Parse*, SrcList*, Token*, Token*); +SQLITE_PRIVATE i64 sqlite3GetToken(const unsigned char *, int *); SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...); SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int); -SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int); +SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int, int); SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*); SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*); SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, SrcItem*); @@ -21609,9 +22822,9 @@ SQLITE_PRIVATE char *sqlite3RCStrResize(char*,u64); SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int); SQLITE_PRIVATE int sqlite3StrAccumEnlarge(StrAccum*, i64); +SQLITE_PRIVATE int sqlite3StrAccumEnlargeIfNeeded(StrAccum*, i64); SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*); SQLITE_PRIVATE void sqlite3StrAccumSetError(StrAccum*, u8); -SQLITE_PRIVATE void sqlite3ResultStrAccum(sqlite3_context*,StrAccum*); SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int); SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int); SQLITE_PRIVATE void sqlite3RecordErrorByteOffset(sqlite3*,const char*); @@ -21704,10 +22917,12 @@ SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db); SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName); SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*); SQLITE_PRIVATE void sqlite3MarkAllShadowTablesOf(sqlite3*, Table*); +SQLITE_PRIVATE void sqlite3VtabEponymousTableClearAll(sqlite3*); #else # define sqlite3ShadowTableName(A,B) 0 # define sqlite3IsShadowTableOf(A,B,C) 0 # define sqlite3MarkAllShadowTablesOf(A,B) +# define sqlite3VtabEponymousTableClearAll(X) #endif SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*); SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*); @@ -21862,6 +23077,10 @@ SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int); SQLITE_PRIVATE void sqlite3ExprSetErrorOffset(Expr*,int); SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*); +SQLITE_PRIVATE SQLITE_OPT_INLINE u64 sqlite3Get8byte(const u8*); +#if SQLITE_BYTEORDER!=4321 +SQLITE_PRIVATE SQLITE_OPT_INLINE u64 sqlite3BSwap64(u64); +#endif SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32); #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY @@ -22165,6 +23384,9 @@ static const char * const sqlite3azCompileOpt[] = { #ifdef SQLITE_BUG_COMPATIBLE_20160819 "BUG_COMPATIBLE_20160819", #endif +#ifdef SQLITE_BUG_COMPATIBLE_20250510 + "BUG_COMPATIBLE_20250510", +#endif #ifdef SQLITE_CASE_SENSITIVE_LIKE "CASE_SENSITIVE_LIKE", #endif @@ -22296,6 +23518,9 @@ static const char * const sqlite3azCompileOpt[] = { #ifdef SQLITE_ENABLE_BYTECODE_VTAB "ENABLE_BYTECODE_VTAB", #endif +#ifdef SQLITE_ENABLE_CARRAY + "ENABLE_CARRAY", +#endif #ifdef SQLITE_ENABLE_CEROD "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD), #endif @@ -22386,6 +23611,9 @@ static const char * const sqlite3azCompileOpt[] = { #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK "ENABLE_OVERSIZE_CELL_CHECK", #endif +#ifdef SQLITE_ENABLE_PERCENTILE + "ENABLE_PERCENTILE", +#endif #ifdef SQLITE_ENABLE_PREUPDATE_HOOK "ENABLE_PREUPDATE_HOOK", #endif @@ -22401,6 +23629,9 @@ static const char * const sqlite3azCompileOpt[] = { #ifdef SQLITE_ENABLE_SESSION "ENABLE_SESSION", #endif +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + "ENABLE_SETLK_TIMEOUT", +#endif #ifdef SQLITE_ENABLE_SNAPSHOT "ENABLE_SNAPSHOT", #endif @@ -22455,6 +23686,9 @@ static const char * const sqlite3azCompileOpt[] = { #ifdef SQLITE_EXTRA_INIT "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT), #endif +#ifdef SQLITE_EXTRA_INIT_MUTEXED + "EXTRA_INIT_MUTEXED=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT_MUTEXED), +#endif #ifdef SQLITE_EXTRA_SHUTDOWN "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN), #endif @@ -22544,6 +23778,9 @@ static const char * const sqlite3azCompileOpt[] = { #ifdef SQLITE_MAX_PAGE_SIZE "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE), #endif +#ifdef SQLITE_MAX_SCHEMA + "MAX_SCHEMA=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA), +#endif #ifdef SQLITE_MAX_SCHEMA_RETRY "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY), #endif @@ -22821,6 +24058,9 @@ static const char * const sqlite3azCompileOpt[] = { #ifdef SQLITE_STMTJRNL_SPILL "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL), #endif +#ifdef SQLITE_STRICT_SUBTYPE + "STRICT_SUBTYPE", +#endif #ifdef SQLITE_SUBSTR_COMPATIBILITY "SUBSTR_COMPATIBILITY", #endif @@ -22852,9 +24092,6 @@ static const char * const sqlite3azCompileOpt[] = { #ifdef SQLITE_UNTESTABLE "UNTESTABLE", #endif -#ifdef SQLITE_USER_AUTHENTICATION - "USER_AUTHENTICATION", -#endif #ifdef SQLITE_USE_ALLOCA "USE_ALLOCA", #endif @@ -23195,6 +24432,16 @@ SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = { */ SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions; +/* +** This singleton is an sqlite3_str object that is returned if +** sqlite3_malloc() fails to provide space for a real one. This +** sqlite3_str object accepts no new text and always returns +** an SQLITE_NOMEM error. +*/ +SQLITE_PRIVATE const sqlite3_str sqlite3OomStr = { + 0, 0, 0, 0, 0, SQLITE_NOMEM, 0 +}; + #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG) /* ** Counter used for coverage testing. Does not come into play for @@ -23442,12 +24689,19 @@ struct VdbeCursor { #endif VdbeTxtBlbCache *pCache; /* Cache of large TEXT or BLOB values */ - /* 2*nField extra array elements allocated for aType[], beyond the one - ** static element declared in the structure. nField total array slots for - ** aType[] and nField+1 array slots for aOffset[] */ - u32 aType[1]; /* Type values record decode. MUST BE LAST */ + /* Space is allocated for aType to hold at least 2*nField+1 entries: + ** nField slots for aType[] and nField+1 array slots for aOffset[] */ + u32 aType[FLEXARRAY]; /* Type values record decode. MUST BE LAST */ }; +/* +** The size (in bytes) of a VdbeCursor object that has an nField value of N +** or less. The value of SZ_VDBECURSOR(n) is guaranteed to be a multiple +** of 8. +*/ +#define SZ_VDBECURSOR(N) \ + (ROUND8(offsetof(VdbeCursor,aType)) + ((N)+1)*sizeof(u64)) + /* Return true if P is a null-only cursor */ #define IsNullCursor(P) \ @@ -23553,6 +24807,7 @@ struct sqlite3_value { #ifdef SQLITE_DEBUG Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */ u16 mScopyFlags; /* flags value immediately after the shallow copy */ + u8 bScopy; /* The pScopyFrom of some other Mem *might* point here */ #endif }; @@ -23589,7 +24844,7 @@ struct sqlite3_value { ** MEM_Int, MEM_Real, and MEM_IntReal. ** ** * MEM_Blob|MEM_Zero A blob in Mem.z of length Mem.n plus -** MEM.u.i extra 0x00 bytes at the end. +** Mem.u.nZero extra 0x00 bytes at the end. ** ** * MEM_Int Integer stored in Mem.u.i. ** @@ -23702,14 +24957,17 @@ struct sqlite3_context { int isError; /* Error code returned by the function. */ u8 enc; /* Encoding to use for results */ u8 skipFlag; /* Skip accumulator loading if true */ - u8 argc; /* Number of arguments */ - sqlite3_value *argv[1]; /* Argument set */ + u16 argc; /* Number of arguments */ + sqlite3_value *argv[FLEXARRAY]; /* Argument set */ }; -/* A bitfield type for use inside of structures. Always follow with :N where -** N is the number of bits. +/* +** The size (in bytes) of an sqlite3_context object that holds N +** argv[] arguments. */ -typedef unsigned bft; /* Bit Field Type */ +#define SZ_CONTEXT(N) \ + (offsetof(sqlite3_context,argv)+(N)*sizeof(sqlite3_value*)) + /* The ScanStatus object holds a single value for the ** sqlite3_stmt_scanstatus() interface. @@ -23770,7 +25028,7 @@ struct Vdbe { i64 nStmtDefCons; /* Number of def. constraints when stmt started */ i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */ Mem *aMem; /* The memory locations */ - Mem **apArg; /* Arguments to currently executing user function */ + Mem **apArg; /* Arguments xUpdate and xFilter vtab methods */ VdbeCursor **apCsr; /* One element of this array for each open cursor */ Mem *aVar; /* Values for the OP_Variable opcode. */ @@ -23790,6 +25048,7 @@ struct Vdbe { #ifdef SQLITE_DEBUG int rcApp; /* errcode set by sqlite3_result_error_code() */ u32 nWrite; /* Number of write operations that have occurred */ + int napArg; /* Size of the apArg[] array */ #endif u16 nResColumn; /* Number of columns in one row of the result set */ u16 nResAlloc; /* Column slots allocated to aColName[] */ @@ -23816,7 +25075,9 @@ struct Vdbe { VdbeFrame *pFrame; /* Parent frame */ VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */ int nFrame; /* Number of frames in pFrame list */ - u32 expmask; /* Binding to these vars invalidates VM */ + u32 expmask; /* Binding to these vars might invalidate VM */ + u32 smimask; /* Only invalid if changing to/from small integer */ + /* Note: smimask is always a subset of expmask */ SubProgram *pProgram; /* Linked list of all sub-programs used by VM */ AuxData *pAuxData; /* Linked list of auxdata allocations */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS @@ -23842,17 +25103,21 @@ struct PreUpdate { VdbeCursor *pCsr; /* Cursor to read old values from */ int op; /* One of SQLITE_INSERT, UPDATE, DELETE */ u8 *aRecord; /* old.* database record */ - KeyInfo keyinfo; + KeyInfo *pKeyinfo; /* Key information */ UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */ UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */ int iNewReg; /* Register for new.* values */ int iBlobWrite; /* Value returned by preupdate_blobwrite() */ i64 iKey1; /* First key value passed to hook */ i64 iKey2; /* Second key value passed to hook */ + Mem oldipk; /* Memory cell holding "old" IPK value */ Mem *aNew; /* Array of new.* values */ Table *pTab; /* Schema object being updated */ Index *pPk; /* PK index if pTab is WITHOUT ROWID */ sqlite3_value **apDflt; /* Array of default values, if required */ + struct { + u8 keyinfoSpace[SZ_KEYINFO_0]; /* Space to hold pKeyinfo[0] content */ + } uKey; }; /* @@ -23880,6 +25145,17 @@ struct ValueList { SQLITE_PRIVATE const u8 sqlite3SmallTypeSizes[]; #endif +/* Input "x" is a sequence of unsigned characters that represent a +** big-endian integer. Return the equivalent native integer +*/ +#define ONE_BYTE_INT(x) ((i8)(x)[0]) +#define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1]) +#define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2]) +#define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3]) +#define FOUR_BYTE_U64(x) (((u64)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3]) +#define FOUR_BYTE_INT(x) ((int)FOUR_BYTE_UINT(x)) +#define SIX_BYTE_INT(x) (FOUR_BYTE_UINT(x+2)+4294967296LL*TWO_BYTE_INT(x)) + /* ** Function prototypes */ @@ -23923,6 +25199,7 @@ SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*); SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, i64, u8, void(*)(void*)); +SQLITE_PRIVATE int sqlite3VdbeMemSetText(Mem*, const char*, i64, void(*)(void*)); SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64); #ifdef SQLITE_OMIT_FLOATING_POINT # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64 @@ -23941,13 +25218,14 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetZeroBlob(Mem*,int); SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem*); #endif SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem*); -SQLITE_PRIVATE void sqlite3VdbeMemZeroTerminateIfAble(Mem*); +SQLITE_PRIVATE int sqlite3VdbeMemZeroTerminateIfAble(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8); SQLITE_PRIVATE int sqlite3IntFloatCompare(i64,double); SQLITE_PRIVATE i64 sqlite3VdbeIntValue(const Mem*); SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*); SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*); +SQLITE_PRIVATE int sqlite3MemRealValueRC(Mem*, double*); SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull); SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*); @@ -23978,6 +25256,7 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int,int); #endif SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p); +SQLITE_PRIVATE int sqlite3VdbeFindIndexKey(BtCursor*, Index*, UnpackedRecord*, int*, int); SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *); SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *); @@ -24016,9 +25295,11 @@ SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*); #endif #ifndef SQLITE_OMIT_FOREIGN_KEY -SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int); +SQLITE_PRIVATE int sqlite3VdbeCheckFkImmediate(Vdbe*); +SQLITE_PRIVATE int sqlite3VdbeCheckFkDeferred(Vdbe*); #else -# define sqlite3VdbeCheckFk(p,i) 0 +# define sqlite3VdbeCheckFkImmediate(p) 0 +# define sqlite3VdbeCheckFkDeferred(p) 0 #endif #ifdef SQLITE_DEBUG @@ -24219,30 +25500,33 @@ SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){ nInit += countLookasideSlots(db->lookaside.pSmallInit); nFree += countLookasideSlots(db->lookaside.pSmallFree); #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ - if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit; - return db->lookaside.nSlot - (nInit+nFree); + assert( db->lookaside.nSlot >= nInit+nFree ); + if( pHighwater ) *pHighwater = (int)(db->lookaside.nSlot - nInit); + return (int)(db->lookaside.nSlot - (nInit+nFree)); } /* ** Query status information for a single database connection */ -SQLITE_API int sqlite3_db_status( - sqlite3 *db, /* The database connection whose status is desired */ - int op, /* Status verb */ - int *pCurrent, /* Write current value here */ - int *pHighwater, /* Write high-water mark here */ - int resetFlag /* Reset high-water mark if true */ +SQLITE_API int sqlite3_db_status64( + sqlite3 *db, /* The database connection whose status is desired */ + int op, /* Status verb */ + sqlite3_int64 *pCurrent, /* Write current value here */ + sqlite3_int64 *pHighwtr, /* Write high-water mark here */ + int resetFlag /* Reset high-water mark if true */ ){ int rc = SQLITE_OK; /* Return code */ #ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){ + if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwtr==0 ){ return SQLITE_MISUSE_BKPT; } #endif sqlite3_mutex_enter(db->mutex); switch( op ){ case SQLITE_DBSTATUS_LOOKASIDE_USED: { - *pCurrent = sqlite3LookasideUsed(db, pHighwater); + int H = 0; + *pCurrent = sqlite3LookasideUsed(db, &H); + *pHighwtr = H; if( resetFlag ){ LookasideSlot *p = db->lookaside.pFree; if( p ){ @@ -24273,7 +25557,7 @@ SQLITE_API int sqlite3_db_status( assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 ); assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 ); *pCurrent = 0; - *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT]; + *pHighwtr = db->lookaside.anStat[op-SQLITE_DBSTATUS_LOOKASIDE_HIT]; if( resetFlag ){ db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0; } @@ -24287,7 +25571,7 @@ SQLITE_API int sqlite3_db_status( */ case SQLITE_DBSTATUS_CACHE_USED_SHARED: case SQLITE_DBSTATUS_CACHE_USED: { - int totalUsed = 0; + sqlite3_int64 totalUsed = 0; int i; sqlite3BtreeEnterAll(db); for(i=0; i<db->nDb; i++){ @@ -24303,18 +25587,18 @@ SQLITE_API int sqlite3_db_status( } sqlite3BtreeLeaveAll(db); *pCurrent = totalUsed; - *pHighwater = 0; + *pHighwtr = 0; break; } /* ** *pCurrent gets an accurate estimate of the amount of memory used ** to store the schema for all databases (main, temp, and any ATTACHed - ** databases. *pHighwater is set to zero. + ** databases. *pHighwtr is set to zero. */ case SQLITE_DBSTATUS_SCHEMA_USED: { - int i; /* Used to iterate through schemas */ - int nByte = 0; /* Used to accumulate return value */ + int i; /* Used to iterate through schemas */ + int nByte = 0; /* Used to accumulate return value */ sqlite3BtreeEnterAll(db); db->pnBytesFreed = &nByte; @@ -24348,7 +25632,7 @@ SQLITE_API int sqlite3_db_status( db->lookaside.pEnd = db->lookaside.pTrueEnd; sqlite3BtreeLeaveAll(db); - *pHighwater = 0; + *pHighwtr = 0; *pCurrent = nByte; break; } @@ -24356,7 +25640,7 @@ SQLITE_API int sqlite3_db_status( /* ** *pCurrent gets an accurate estimate of the amount of memory used ** to store all prepared statements. - ** *pHighwater is set to zero. + ** *pHighwtr is set to zero. */ case SQLITE_DBSTATUS_STMT_USED: { struct Vdbe *pVdbe; /* Used to iterate through VMs */ @@ -24371,7 +25655,7 @@ SQLITE_API int sqlite3_db_status( db->lookaside.pEnd = db->lookaside.pTrueEnd; db->pnBytesFreed = 0; - *pHighwater = 0; /* IMP: R-64479-57858 */ + *pHighwtr = 0; /* IMP: R-64479-57858 */ *pCurrent = nByte; break; @@ -24379,7 +25663,7 @@ SQLITE_API int sqlite3_db_status( /* ** Set *pCurrent to the total cache hits or misses encountered by all - ** pagers the database handle is connected to. *pHighwater is always set + ** pagers the database handle is connected to. *pHighwtr is always set ** to zero. */ case SQLITE_DBSTATUS_CACHE_SPILL: @@ -24399,19 +25683,39 @@ SQLITE_API int sqlite3_db_status( sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet); } } - *pHighwater = 0; /* IMP: R-42420-56072 */ + *pHighwtr = 0; /* IMP: R-42420-56072 */ /* IMP: R-54100-20147 */ /* IMP: R-29431-39229 */ - *pCurrent = (int)nRet & 0x7fffffff; + *pCurrent = nRet; + break; + } + + /* Set *pCurrent to the number of bytes that the db database connection + ** has spilled to the filesystem in temporary files that could have been + ** stored in memory, had sufficient memory been available. + ** The *pHighwater is always set to zero. + */ + case SQLITE_DBSTATUS_TEMPBUF_SPILL: { + u64 nRet = 0; + if( db->aDb[1].pBt ){ + Pager *pPager = sqlite3BtreePager(db->aDb[1].pBt); + sqlite3PagerCacheStat(pPager, SQLITE_DBSTATUS_CACHE_WRITE, + resetFlag, &nRet); + nRet *= sqlite3BtreeGetPageSize(db->aDb[1].pBt); + } + nRet += db->nSpill; + if( resetFlag ) db->nSpill = 0; + *pHighwtr = 0; + *pCurrent = nRet; break; } /* Set *pCurrent to non-zero if there are unresolved deferred foreign ** key constraints. Set *pCurrent to zero if all foreign key constraints - ** have been satisfied. The *pHighwater is always set to zero. + ** have been satisfied. The *pHighwtr is always set to zero. */ case SQLITE_DBSTATUS_DEFERRED_FKS: { - *pHighwater = 0; /* IMP: R-11967-56545 */ + *pHighwtr = 0; /* IMP: R-11967-56545 */ *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0; break; } @@ -24424,6 +25728,31 @@ SQLITE_API int sqlite3_db_status( return rc; } +/* +** 32-bit variant of sqlite3_db_status64() +*/ +SQLITE_API int sqlite3_db_status( + sqlite3 *db, /* The database connection whose status is desired */ + int op, /* Status verb */ + int *pCurrent, /* Write current value here */ + int *pHighwtr, /* Write high-water mark here */ + int resetFlag /* Reset high-water mark if true */ +){ + sqlite3_int64 C = 0, H = 0; + int rc; +#ifdef SQLITE_ENABLE_API_ARMOR + if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwtr==0 ){ + return SQLITE_MISUSE_BKPT; + } +#endif + rc = sqlite3_db_status64(db, op, &C, &H, resetFlag); + if( rc==0 ){ + *pCurrent = C & 0x7fffffff; + *pHighwtr = H & 0x7fffffff; + } + return rc; +} + /************** End of status.c **********************************************/ /************** Begin file date.c ********************************************/ /* @@ -24616,6 +25945,10 @@ static int parseTimezone(const char *zDate, DateTime *p){ } zDate += 5; p->tz = sgn*(nMn + nHr*60); + if( p->tz==0 ){ /* Forum post 2025-09-17T10:12:14z */ + p->isLocal = 0; + p->isUtc = 1; + } zulu_time: while( sqlite3Isspace(*zDate) ){ zDate++; } return *zDate!=0; @@ -24650,10 +25983,14 @@ static int parseHhMmSs(const char *zDate, DateTime *p){ zDate++; } ms /= rScale; + /* Truncate to avoid problems with sub-milliseconds + ** rounding. https://sqlite.org/forum/forumpost/766a2c9231 */ + if( ms>0.999 ) ms = 0.999; } }else{ s = 0; } + if( h==24 && (m!=0 || s!=0 || ms!=0.0) ) return 1; p->validJD = 0; p->rawS = 0; p->validHMS = 1; @@ -24690,6 +26027,10 @@ static void computeJD(DateTime *p){ Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */ M = 1; D = 1; + if( p->validHMS && p->h==24 ){ + p->h = 0; + D = 2; + } } if( Y<-4713 || Y>9999 || p->rawS ){ datetimeError(p); @@ -24718,6 +26059,21 @@ static void computeJD(DateTime *p){ } } +/* +** Return the number of dates in a specific month. +*/ +static int daysOfMonth(int Y, int M){ + if( (1<<M) & 0x15aa ){ + return 31; + }else if( M!=2 ){ + return 30; + }else if( Y%4==0 && (Y%100!=0 || Y%400==0) ){ + return 29; + }else{ + return 28; + } +} + /* ** Given the YYYY-MM-DD information current in p, determine if there ** is day-of-month overflow and set nFloor to the number of days that @@ -24725,20 +26081,12 @@ static void computeJD(DateTime *p){ ** date back to the end of the month. */ static void computeFloor(DateTime *p){ + int mxD; /* Maximum day number for the current month */ assert( p->validYMD || p->isError ); - assert( p->D>=0 && p->D<=31 ); + assert( p->D>=0 && p->D<=32 ); assert( p->M>=0 && p->M<=12 ); - if( p->D<=28 ){ - p->nFloor = 0; - }else if( (1<<p->M) & 0x15aa ){ - p->nFloor = 0; - }else if( p->M!=2 ){ - p->nFloor = (p->D==31); - }else if( p->Y%4!=0 || (p->Y%100==0 && p->Y%400!=0) ){ - p->nFloor = p->D - 28; - }else{ - p->nFloor = p->D - 29; - } + mxD = daysOfMonth(p->Y, p->M); + p->nFloor = p->D>mxD ? p->D - mxD : 0; } /* @@ -24768,7 +26116,19 @@ static int parseYyyyMmDd(const char *zDate, DateTime *p){ zDate += 10; while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; } if( parseHhMmSs(zDate, p)==0 ){ - /* We got the time */ + if( p->h==24 ){ + int mxD = daysOfMonth(Y,M); + p->h = 0; + D++; + if( D>mxD ){ + D -= mxD; + M++; + if( M>12 ){ + M = 1; + Y++; + } + } + } }else if( *zDate==0 ){ p->validHMS = 0; }else{ @@ -24850,7 +26210,7 @@ static int parseDateOrTime( return 0; }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){ return setDateTimeToCurrent(context, p); - }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8)>0 ){ + }else if( sqlite3AtoF(zDate, &r)>0 ){ setRawDateNumber(p, r); return 0; }else if( (sqlite3StrICmp(zDate,"subsec")==0 @@ -25188,6 +26548,49 @@ static int parseModifier( } break; } + case 'e': { + /* + ** end of day + ** end of month + ** end of year + ** + ** Move the date forwards to the last millisecond of the current + ** day, month or year. + */ + if( sqlite3_strnicmp(z, "end of ", 7)!=0 ){ + break; + } + if( !p->validJD && !p->validYMD && !p->validHMS ) break; + z += 7; + computeYMD(p); + p->validHMS = 1; + p->h = 23; + p->m = 59; + p->s = 59.999; + p->rawS = 0; + p->tz = 0; + p->validJD = 0; + if( sqlite3_stricmp(z,"month")==0 ){ + p->D = 1; + p->M++; + if( p->M>12 ){ + p->Y++; + p->M = 1; + } + computeFloor(p); + computeJD(p); + p->iJD -= (p->nFloor+1)*86400000; + clearYMD_HMS_TZ(p); + rc = 0; + }else if( sqlite3_stricmp(z,"year")==0 ){ + p->M = 12; + p->D = 31; + rc = 0; + }else if( sqlite3_stricmp(z,"day")==0 ){ + rc = 0; + } + break; + } case 'f': { /* ** floor @@ -25290,22 +26693,30 @@ static int parseModifier( case 'w': { /* ** weekday N + ** weekday -N ** - ** Move the date to the same time on the next occurrence of - ** weekday N where 0==Sunday, 1==Monday, and so forth. If the - ** date is already on the appropriate weekday, this is a no-op. + ** Move the date forward (for N>=0) or backward (for N<=-0) to the + ** same time on the next/previous occurrence of weekday abs(N) + ** where 0==Sunday, 1==Monday, and so forth. If the date is already + ** on the appropriate weekday, this is a no-op. */ if( sqlite3_strnicmp(z, "weekday ", 8)==0 - && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)>0 - && r>=0.0 && r<7.0 && (n=(int)r)==r ){ + && sqlite3AtoF(&z[8], &r)>0 + && r>=-6.0 && r<=6.0 + && sqlite3RealSameAsInt(r,(i64)(n=(int)r)) + ){ sqlite3_int64 Z; computeYMD_HMS(p); p->tz = 0; p->validJD = 0; computeJD(p); Z = ((p->iJD + 129600000)/86400000) % 7; - if( Z>n ) Z -= 7; - p->iJD += (n - Z)*86400000; + if( n<0 ) n = -n; + if( Z!=n ){ + if( Z>n ) Z -= 7; + p->iJD += (n - Z)*86400000; + if( strchr(z+8,'-')!=0 ) p->iJD -= 7*86400000; + } clearYMD_HMS_TZ(p); rc = 0; } @@ -25313,7 +26724,9 @@ static int parseModifier( } case 's': { /* - ** start of TTTTT + ** start of day + ** start of month + ** start of year ** ** Move the date backwards to the beginning of the current day, ** or month or year. @@ -25367,9 +26780,11 @@ static int parseModifier( case '8': case '9': { double rRounder; - int i; + int i, rx; int Y,M,D,h,m,x; const char *z2 = z; + char *zCopy; + sqlite3 *db = sqlite3_context_db_handle(pCtx); char z0 = z[0]; for(n=1; z[n]; n++){ if( z[n]==':' ) break; @@ -25379,7 +26794,11 @@ static int parseModifier( if( n==6 && getDigits(&z[1], "50f", &Y)==1 ) break; } } - if( sqlite3AtoF(z, &r, n, SQLITE_UTF8)<=0 ){ + zCopy = sqlite3DbStrNDup(db, z, n); + if( zCopy==0 ) break; + rx = sqlite3AtoF(zCopy, &r)<=0; + sqlite3DbFree(db, zCopy); + if( rx ){ assert( rc==1 ); break; } @@ -25782,7 +27201,7 @@ static int daysAfterMonday(DateTime *pDate){ ** In other words, return the day of the week according ** to this code: ** -** 0=Sunday, 1=Monday, 2=Tues, ..., 6=Saturday +** 0=Sunday, 1=Monday, 2=Tuesday, ..., 6=Saturday */ static int daysAfterSunday(DateTime *pDate){ assert( pDate->validJD ); @@ -25808,8 +27227,8 @@ static int daysAfterSunday(DateTime *pDate){ ** %l hour 1-12 (leading zero converted to space) ** %m month 01-12 ** %M minute 00-59 -** %p "am" or "pm" -** %P "AM" or "PM" +** %p "AM" or "PM" +** %P "am" or "pm" ** %R time as HH:MM ** %s seconds since 1970-01-01 ** %S seconds 00-59 @@ -25831,38 +27250,38 @@ static void strftimeFunc( size_t i,j; sqlite3 *db; const char *zFmt; - sqlite3_str sRes; + sqlite3_str *pRes; if( argc==0 ) return; zFmt = (const char*)sqlite3_value_text(argv[0]); if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return; db = sqlite3_context_db_handle(context); - sqlite3StrAccumInit(&sRes, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); + pRes = sqlite3_str_new(db); computeJD(&x); computeYMD_HMS(&x); for(i=j=0; zFmt[i]; i++){ char cf; if( zFmt[i]!='%' ) continue; - if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j)); + if( j<i ) sqlite3_str_append(pRes, zFmt+j, (int)(i-j)); i++; j = i + 1; cf = zFmt[i]; switch( cf ){ case 'd': /* Fall thru */ case 'e': { - sqlite3_str_appendf(&sRes, cf=='d' ? "%02d" : "%2d", x.D); + sqlite3_str_appendf(pRes, cf=='d' ? "%02d" : "%2d", x.D); break; } case 'f': { /* Fractional seconds. (Non-standard) */ double s = x.s; - if( s>59.999 ) s = 59.999; - sqlite3_str_appendf(&sRes, "%06.3f", s); + if( NEVER(s>59.999) ) s = 59.999; + sqlite3_str_appendf(pRes, "%06.3f", s); break; } case 'F': { - sqlite3_str_appendf(&sRes, "%04d-%02d-%02d", x.Y, x.M, x.D); + sqlite3_str_appendf(pRes, "%04d-%02d-%02d", x.Y, x.M, x.D); break; } case 'G': /* Fall thru */ @@ -25874,15 +27293,15 @@ static void strftimeFunc( y.validYMD = 0; computeYMD(&y); if( cf=='g' ){ - sqlite3_str_appendf(&sRes, "%02d", y.Y%100); + sqlite3_str_appendf(pRes, "%02d", y.Y%100); }else{ - sqlite3_str_appendf(&sRes, "%04d", y.Y); + sqlite3_str_appendf(pRes, "%04d", y.Y); } break; } case 'H': case 'k': { - sqlite3_str_appendf(&sRes, cf=='H' ? "%02d" : "%2d", x.h); + sqlite3_str_appendf(pRes, cf=='H' ? "%02d" : "%2d", x.h); break; } case 'I': /* Fall thru */ @@ -25890,65 +27309,65 @@ static void strftimeFunc( int h = x.h; if( h>12 ) h -= 12; if( h==0 ) h = 12; - sqlite3_str_appendf(&sRes, cf=='I' ? "%02d" : "%2d", h); + sqlite3_str_appendf(pRes, cf=='I' ? "%02d" : "%2d", h); break; } case 'j': { /* Day of year. Jan01==1, Jan02==2, and so forth */ - sqlite3_str_appendf(&sRes,"%03d",daysAfterJan01(&x)+1); + sqlite3_str_appendf(pRes,"%03d",daysAfterJan01(&x)+1); break; } case 'J': { /* Julian day number. (Non-standard) */ - sqlite3_str_appendf(&sRes,"%.16g",x.iJD/86400000.0); + sqlite3_str_appendf(pRes,"%.16g",x.iJD/86400000.0); break; } case 'm': { - sqlite3_str_appendf(&sRes,"%02d",x.M); + sqlite3_str_appendf(pRes,"%02d",x.M); break; } case 'M': { - sqlite3_str_appendf(&sRes,"%02d",x.m); + sqlite3_str_appendf(pRes,"%02d",x.m); break; } case 'p': /* Fall thru */ case 'P': { if( x.h>=12 ){ - sqlite3_str_append(&sRes, cf=='p' ? "PM" : "pm", 2); + sqlite3_str_append(pRes, cf=='p' ? "PM" : "pm", 2); }else{ - sqlite3_str_append(&sRes, cf=='p' ? "AM" : "am", 2); + sqlite3_str_append(pRes, cf=='p' ? "AM" : "am", 2); } break; } case 'R': { - sqlite3_str_appendf(&sRes, "%02d:%02d", x.h, x.m); + sqlite3_str_appendf(pRes, "%02d:%02d", x.h, x.m); break; } case 's': { if( x.useSubsec ){ - sqlite3_str_appendf(&sRes,"%.3f", + sqlite3_str_appendf(pRes,"%.3f", (x.iJD - 21086676*(i64)10000000)/1000.0); }else{ i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000); - sqlite3_str_appendf(&sRes,"%lld",iS); + sqlite3_str_appendf(pRes,"%lld",iS); } break; } case 'S': { - sqlite3_str_appendf(&sRes,"%02d",(int)x.s); + sqlite3_str_appendf(pRes,"%02d",(int)x.s); break; } case 'T': { - sqlite3_str_appendf(&sRes,"%02d:%02d:%02d", x.h, x.m, (int)x.s); + sqlite3_str_appendf(pRes,"%02d:%02d:%02d", x.h, x.m, (int)x.s); break; } case 'u': /* Day of week. 1 to 7. Monday==1, Sunday==7 */ case 'w': { /* Day of week. 0 to 6. Sunday==0, Monday==1 */ char c = (char)daysAfterSunday(&x) + '0'; if( c=='0' && cf=='u' ) c = '7'; - sqlite3_str_appendchar(&sRes, 1, c); + sqlite3_str_appendchar(pRes, 1, c); break; } case 'U': { /* Week num. 00-53. First Sun of the year is week 01 */ - sqlite3_str_appendf(&sRes,"%02d", + sqlite3_str_appendf(pRes,"%02d", (daysAfterJan01(&x)-daysAfterSunday(&x)+7)/7); break; } @@ -25959,30 +27378,30 @@ static void strftimeFunc( y.iJD += (3 - daysAfterMonday(&x))*86400000; y.validYMD = 0; computeYMD(&y); - sqlite3_str_appendf(&sRes,"%02d", daysAfterJan01(&y)/7+1); + sqlite3_str_appendf(pRes,"%02d", daysAfterJan01(&y)/7+1); break; } case 'W': { /* Week num. 00-53. First Mon of the year is week 01 */ - sqlite3_str_appendf(&sRes,"%02d", + sqlite3_str_appendf(pRes,"%02d", (daysAfterJan01(&x)-daysAfterMonday(&x)+7)/7); break; } case 'Y': { - sqlite3_str_appendf(&sRes,"%04d",x.Y); + sqlite3_str_appendf(pRes,"%04d",x.Y); break; } case '%': { - sqlite3_str_appendchar(&sRes, 1, '%'); + sqlite3_str_appendchar(pRes, 1, '%'); break; } default: { - sqlite3_str_reset(&sRes); + sqlite3_str_free(pRes); return; } } } - if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j)); - sqlite3ResultStrAccum(context, &sRes); + if( j<i ) sqlite3_str_append(pRes, zFmt+j, (int)(i-j)); + sqlite3_result_str(context, pRes, SQLITE_FINISH); } /* @@ -26118,7 +27537,7 @@ static void timediffFunc( sqlite3StrAccumInit(&sRes, 0, 0, 0, 100); sqlite3_str_appendf(&sRes, "%c%04d-%02d-%02d %02d:%02d:%06.3f", sign, Y, M, d1.D-1, d1.h, d1.m, d1.s); - sqlite3ResultStrAccum(context, &sRes); + sqlite3_result_str(context, &sRes, SQLITE_XFER); } @@ -26199,7 +27618,7 @@ static void datedebugFunc( char *zJson; zJson = sqlite3_mprintf( "{iJD:%lld,Y:%d,M:%d,D:%d,h:%d,m:%d,tz:%d," - "s:%.3f,validJD:%d,validYMS:%d,validHMS:%d," + "s:%.3f,validJD:%d,validYMD:%d,validHMS:%d," "nFloor:%d,rawS:%d,isError:%d,useSubsec:%d," "isUtc:%d,isLocal:%d}", x.iJD, x.Y, x.M, x.D, x.h, x.m, x.tz, @@ -26546,7 +27965,7 @@ SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p }else{ double r; rc = pVfs->xCurrentTime(pVfs, &r); - *pTimeOut = (sqlite3_int64)(r*86400000.0); + *pTimeOut = sqlite3RealToI64(r*86400000.0); } return rc; } @@ -28978,23 +30397,28 @@ static SQLITE_WSD int mutexIsInit = 0; #ifndef SQLITE_MUTEX_OMIT -#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS +#ifdef SQLITE_THREAD_MISUSE_WARNINGS /* -** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains +** This block (enclosed by SQLITE_THREAD_MISUSE_WARNINGS) contains ** the implementation of a wrapper around the system default mutex ** implementation (sqlite3DefaultMutex()). ** ** Most calls are passed directly through to the underlying default ** mutex implementation. Except, if a mutex is configured by calling ** sqlite3MutexWarnOnContention() on it, then if contention is ever -** encountered within xMutexEnter() a warning is emitted via sqlite3_log(). +** encountered within xMutexEnter() then a warning is emitted via +** sqlite3_log(). Furthermore, if SQLITE_THREAD_MISUSE_ABORT is +** defined then abort() is called after the sqlite3_log() warning. ** -** This type of mutex is used as the database handle mutex when testing -** apps that usually use SQLITE_CONFIG_MULTITHREAD mode. +** This type of mutex is used on the database handle mutex when testing +** apps that usually use SQLITE_CONFIG_MULTITHREAD mode. A failure +** indicates that the app ought to be using SQLITE_OPEN_FULLMUTEX or +** similar because it is trying to use the same database handle from +** two different connections at the same time. */ /* -** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS +** Type for all mutexes used when SQLITE_THREAD_MISUSE_WARNINGS ** is defined. Variable CheckMutex.mutex is a pointer to the real mutex ** allocated by the system mutex implementation. Variable iType is usually set ** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST @@ -29030,11 +30454,12 @@ static int checkMutexNotheld(sqlite3_mutex *p){ */ static int checkMutexInit(void){ pGlobalMutexMethods = sqlite3DefaultMutex(); - return SQLITE_OK; + return pGlobalMutexMethods->xMutexInit(); } static int checkMutexEnd(void){ + int rc = pGlobalMutexMethods->xMutexEnd(); pGlobalMutexMethods = 0; - return SQLITE_OK; + return rc; } /* @@ -29111,6 +30536,9 @@ static void checkMutexEnter(sqlite3_mutex *p){ sqlite3_log(SQLITE_MISUSE, "illegal multi-threaded access to database connection" ); +#if SQLITE_THREAD_MISUSE_ABORT + abort(); +#endif } pGlobalMutexMethods->xMutexEnter(pCheck->mutex); } @@ -29162,7 +30590,7 @@ SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){ pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION; } } -#endif /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */ +#endif /* ifdef SQLITE_THREAD_MISUSE_WARNINGS */ /* ** Initialize the mutex system. @@ -29179,7 +30607,7 @@ SQLITE_PRIVATE int sqlite3MutexInit(void){ sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex; if( sqlite3GlobalConfig.bCoreMutex ){ -#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS +#ifdef SQLITE_THREAD_MISUSE_WARNINGS pFrom = multiThreadedCheckMutex(); #else pFrom = sqlite3DefaultMutex(); @@ -29581,8 +31009,15 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ # define SQLITE_MUTEX_NREF 0 #endif +#if GCC_VERSION>0 +# define ALIGN128 __attribute__((aligned(128))) +#else +# define ALIGN128 +#endif + /* -** Each recursive mutex is an instance of the following structure. +** Each SQLite mutex is an instance of the following structure. +** */ struct sqlite3_mutex { pthread_mutex_t mutex; /* Mutex controlling the lock */ @@ -29697,19 +31132,31 @@ static int pthreadMutexEnd(void){ return SQLITE_OK; } ** the same type number. */ static sqlite3_mutex *pthreadMutexAlloc(int iType){ - static sqlite3_mutex staticMutexes[] = { - SQLITE3_MUTEX_INITIALIZER(2), - SQLITE3_MUTEX_INITIALIZER(3), - SQLITE3_MUTEX_INITIALIZER(4), - SQLITE3_MUTEX_INITIALIZER(5), - SQLITE3_MUTEX_INITIALIZER(6), - SQLITE3_MUTEX_INITIALIZER(7), - SQLITE3_MUTEX_INITIALIZER(8), - SQLITE3_MUTEX_INITIALIZER(9), - SQLITE3_MUTEX_INITIALIZER(10), - SQLITE3_MUTEX_INITIALIZER(11), - SQLITE3_MUTEX_INITIALIZER(12), - SQLITE3_MUTEX_INITIALIZER(13) + /* Static mutexes - those with IDs of 2 or more... + ** + ** The ALIGN128 macro attempts to force 128-byte alignment on mutexes, + ** so that adjacent mutex objects are always on different cache lines + ** in the CPU. This is CPU-dependent, of course, but 128-byte alignment + ** seems to work well for all contemporary processors. Experiments show + ** that 64 works just as well most of the time, but the internet says + ** that 128-byte alignment works better. + */ + static ALIGN128 union staticMutex { + sqlite3_mutex m; + char aSpacer[128]; + } aMutex[] = { + { .m = SQLITE3_MUTEX_INITIALIZER(2) }, + { .m = SQLITE3_MUTEX_INITIALIZER(3) }, + { .m = SQLITE3_MUTEX_INITIALIZER(4) }, + { .m = SQLITE3_MUTEX_INITIALIZER(5) }, + { .m = SQLITE3_MUTEX_INITIALIZER(6) }, + { .m = SQLITE3_MUTEX_INITIALIZER(7) }, + { .m = SQLITE3_MUTEX_INITIALIZER(8) }, + { .m = SQLITE3_MUTEX_INITIALIZER(9) }, + { .m = SQLITE3_MUTEX_INITIALIZER(10) }, + { .m = SQLITE3_MUTEX_INITIALIZER(11) }, + { .m = SQLITE3_MUTEX_INITIALIZER(12) }, + { .m = SQLITE3_MUTEX_INITIALIZER(13) }, }; sqlite3_mutex *p; switch( iType ){ @@ -29746,12 +31193,12 @@ static sqlite3_mutex *pthreadMutexAlloc(int iType){ } default: { #ifdef SQLITE_ENABLE_API_ARMOR - if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){ + if( iType-2<0 || iType-2>=ArraySize(aMutex) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - p = &staticMutexes[iType-2]; + p = &aMutex[iType-2].m; break; } } @@ -29991,64 +31438,16 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ #ifdef __CYGWIN__ # include <sys/cygwin.h> +# include <sys/stat.h> /* amalgamator: dontcache */ +# include <unistd.h> /* amalgamator: dontcache */ # include <errno.h> /* amalgamator: dontcache */ #endif -/* -** Determine if we are dealing with Windows NT. -** -** We ought to be able to determine if we are compiling for Windows 9x or -** Windows NT using the _WIN32_WINNT macro as follows: -** -** #if defined(_WIN32_WINNT) -** # define SQLITE_OS_WINNT 1 -** #else -** # define SQLITE_OS_WINNT 0 -** #endif -** -** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as -** it ought to, so the above test does not work. We'll just assume that -** everything is Windows NT unless the programmer explicitly says otherwise -** by setting SQLITE_OS_WINNT to 0. -*/ -#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT) -# define SQLITE_OS_WINNT 1 -#endif - -/* -** Determine if we are dealing with Windows CE - which has a much reduced -** API. -*/ -#if defined(_WIN32_WCE) -# define SQLITE_OS_WINCE 1 -#else -# define SQLITE_OS_WINCE 0 -#endif - -/* -** Determine if we are dealing with WinRT, which provides only a subset of -** the full Win32 API. -*/ -#if !defined(SQLITE_OS_WINRT) -# define SQLITE_OS_WINRT 0 -#endif - -/* -** For WinCE, some API function parameters do not appear to be declared as -** volatile. -*/ -#if SQLITE_OS_WINCE -# define SQLITE_WIN32_VOLATILE -#else -# define SQLITE_WIN32_VOLATILE volatile -#endif - /* ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex() ** functions are not available (e.g. those not using MSVC, Cygwin, etc). */ -#if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \ - SQLITE_THREADSAFE>0 && !defined(__CYGWIN__) +#if SQLITE_OS_WIN && SQLITE_THREADSAFE>0 && !defined(__CYGWIN__) # define SQLITE_OS_WIN_THREADS 1 #else # define SQLITE_OS_WIN_THREADS 0 @@ -30066,11 +31465,32 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ */ #ifdef SQLITE_MUTEX_W32 +#if MSVC_VERSION>0 +# define ALIGN128 __declspec(align(128)) +#else +# define ALIGN128 +#endif + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4324) +#endif /* _MSC_VER */ + /* -** Each recursive mutex is an instance of the following structure. +** Each SQLite mutex is an instance of the following structure. +** +** The ALIGN128 macro attempts to force 128-byte alignment on mutexes, +** so that adjacent mutex objects are always on different cache lines +** in the CPU. This is CPU-dependent, of course, but 128-byte alignment +** seems to work well for all contemporary processors. Experiments show +** that 64 works just as well most of the time, but the internet says +** that 128-byte alignment works better. */ struct sqlite3_mutex { - CRITICAL_SECTION mutex; /* Mutex controlling the lock */ + union { + CRITICAL_SECTION cs; /* The CRITICAL_SECTION mutex. id==1 */ + SRWLOCK srwl; /* The Slim reader/writer lock. id!=1 */ + } u; int id; /* Mutex type */ #ifdef SQLITE_DEBUG volatile int nRef; /* Number of entrances */ @@ -30078,20 +31498,9 @@ struct sqlite3_mutex { volatile LONG trace; /* True to trace changes */ #endif }; - -/* -** These are the initializer values used when declaring a "static" mutex -** on Win32. It should be noted that all mutexes require initialization -** on the Win32 platform. -*/ -#define SQLITE_W32_MUTEX_INITIALIZER { 0 } - -#ifdef SQLITE_DEBUG -#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \ - 0L, (DWORD)0, 0 } -#else -#define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id } -#endif +#ifdef _MSC_VER +#pragma warning(pop) +#endif /* _MSC_VER */ #ifdef SQLITE_DEBUG /* @@ -30102,13 +31511,8 @@ static int winMutexHeld(sqlite3_mutex *p){ return p->nRef!=0 && p->owner==GetCurrentThreadId(); } -static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){ - return p->nRef==0 || p->owner!=tid; -} - static int winMutexNotheld(sqlite3_mutex *p){ - DWORD tid = GetCurrentThreadId(); - return winMutexNotheld2(p, tid); + return p->nRef==0 || p->owner!=GetCurrentThreadId(); } #endif @@ -30130,44 +31534,41 @@ SQLITE_PRIVATE void sqlite3MemoryBarrier(void){ } /* -** Initialize and deinitialize the mutex subsystem. +** Static mutexes. +** +** The ALIGN128 macro on the static mutex array forces 128-byte alignment +** on the mutexes so that adjacent mutex objects are always on different +** cache lines in the CPU. This is CPU-dependent, of course, but 128-byte +** alignment seems to work well for all contemporary processors. +** Experiments show that 64 works just as well most of the time, but +** the internet says that 128-byte alignment works better. */ -static sqlite3_mutex winMutex_staticMutexes[] = { - SQLITE3_MUTEX_INITIALIZER(2), - SQLITE3_MUTEX_INITIALIZER(3), - SQLITE3_MUTEX_INITIALIZER(4), - SQLITE3_MUTEX_INITIALIZER(5), - SQLITE3_MUTEX_INITIALIZER(6), - SQLITE3_MUTEX_INITIALIZER(7), - SQLITE3_MUTEX_INITIALIZER(8), - SQLITE3_MUTEX_INITIALIZER(9), - SQLITE3_MUTEX_INITIALIZER(10), - SQLITE3_MUTEX_INITIALIZER(11), - SQLITE3_MUTEX_INITIALIZER(12), - SQLITE3_MUTEX_INITIALIZER(13) -}; - +static ALIGN128 union staticMutexes { + sqlite3_mutex m; + char spacer[128]; +} aWindowsMutex[12]; static int winMutex_isInit = 0; -static int winMutex_isNt = -1; /* <0 means "need to query" */ /* As the winMutexInit() and winMutexEnd() functions are called as part ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the ** "interlocked" magic used here is probably not strictly necessary. */ -static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0; +static LONG volatile winMutex_lock = 0; -SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */ SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */ static int winMutexInit(void){ /* The first to increment to 1 does actual initialization */ if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){ int i; - for(i=0; i<ArraySize(winMutex_staticMutexes); i++){ -#if SQLITE_OS_WINRT - InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0); -#else - InitializeCriticalSection(&winMutex_staticMutexes[i].mutex); + for(i=0; i<ArraySize(aWindowsMutex); i++){ + sqlite3_mutex *p = &aWindowsMutex[i].m; + p->id = i+2; + InitializeSRWLock(&p->u.srwl); +#ifdef SQLITE_DEBUG + p->nRef = 0; + p->owner = 0; + p->trace = 0; #endif } winMutex_isInit = 1; @@ -30186,10 +31587,6 @@ static int winMutexEnd(void){ ** (which should be the last to shutdown.) */ if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){ if( winMutex_isInit==1 ){ - int i; - for(i=0; i<ArraySize(winMutex_staticMutexes); i++){ - DeleteCriticalSection(&winMutex_staticMutexes[i].mutex); - } winMutex_isInit = 0; } } @@ -30258,22 +31655,22 @@ static sqlite3_mutex *winMutexAlloc(int iType){ p->trace = 1; #endif #endif -#if SQLITE_OS_WINRT - InitializeCriticalSectionEx(&p->mutex, 0, 0); -#else - InitializeCriticalSection(&p->mutex); -#endif + if( iType==SQLITE_MUTEX_RECURSIVE ){ + InitializeCriticalSection(&p->u.cs); + }else{ + InitializeSRWLock(&p->u.srwl); + } } break; } default: { #ifdef SQLITE_ENABLE_API_ARMOR - if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){ + if( iType-2<0 || iType-2>=ArraySize(aWindowsMutex) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - p = &winMutex_staticMutexes[iType-2]; + p = &aWindowsMutex[iType-2].m; #ifdef SQLITE_DEBUG #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC InterlockedCompareExchange(&p->trace, 1, 0); @@ -30295,8 +31692,10 @@ static sqlite3_mutex *winMutexAlloc(int iType){ static void winMutexFree(sqlite3_mutex *p){ assert( p ); assert( p->nRef==0 && p->owner==0 ); - if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){ - DeleteCriticalSection(&p->mutex); + if( p->id==SQLITE_MUTEX_FAST ){ + sqlite3_free(p); + }else if( p->id==SQLITE_MUTEX_RECURSIVE ){ + DeleteCriticalSection(&p->u.cs); sqlite3_free(p); }else{ #ifdef SQLITE_ENABLE_API_ARMOR @@ -30317,67 +31716,56 @@ static void winMutexFree(sqlite3_mutex *p){ ** more than once, the behavior is undefined. */ static void winMutexEnter(sqlite3_mutex *p){ -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - DWORD tid = GetCurrentThreadId(); -#endif -#ifdef SQLITE_DEBUG - assert( p ); - assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); -#else assert( p ); +#ifdef SQLITE_DEBUG + assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) ); #endif assert( winMutex_isInit==1 ); - EnterCriticalSection(&p->mutex); + if( p->id==SQLITE_MUTEX_RECURSIVE ){ + EnterCriticalSection(&p->u.cs); + }else{ + AcquireSRWLockExclusive(&p->u.srwl); + } #ifdef SQLITE_DEBUG assert( p->nRef>0 || p->owner==0 ); - p->owner = tid; + p->owner = GetCurrentThreadId(); p->nRef++; if( p->trace ){ OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n", - tid, p->id, p, p->trace, p->nRef)); + GetCurrentThreadId(), p->id, p, p->trace, p->nRef)); } #endif } static int winMutexTry(sqlite3_mutex *p){ -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - DWORD tid = GetCurrentThreadId(); -#endif int rc = SQLITE_BUSY; assert( p ); - assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); + assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) ); /* - ** The sqlite3_mutex_try() routine is very rarely used, and when it - ** is used it is merely an optimization. So it is OK for it to always + ** The sqlite3_mutex_try() routine is seldom used, and when it is + ** used it is merely an optimization. So it is OK for it to always ** fail. - ** - ** The TryEnterCriticalSection() interface is only available on WinNT. - ** And some windows compilers complain if you try to use it without - ** first doing some #defines that prevent SQLite from building on Win98. - ** For that reason, we will omit this optimization for now. See - ** ticket #2685. */ -#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400 - assert( winMutex_isInit==1 ); - assert( winMutex_isNt>=-1 && winMutex_isNt<=1 ); - if( winMutex_isNt<0 ){ - winMutex_isNt = sqlite3_win32_is_nt(); + if( p->id==SQLITE_MUTEX_RECURSIVE ){ + rc = TryEnterCriticalSection(&p->u.cs); + }else{ + rc = TryAcquireSRWLockExclusive(&p->u.srwl); } - assert( winMutex_isNt==0 || winMutex_isNt==1 ); - if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){ + if( rc ){ #ifdef SQLITE_DEBUG - p->owner = tid; + p->owner = GetCurrentThreadId(); p->nRef++; #endif rc = SQLITE_OK; + }else{ + rc = SQLITE_BUSY; } -#else - UNUSED_PARAMETER(p); -#endif #ifdef SQLITE_DEBUG if( p->trace ){ - OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n", - tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc))); + OSTRACE(( + "TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n", + GetCurrentThreadId(), p->id, p, p->trace, p->owner, p->nRef, + sqlite3ErrName(rc))); } #endif return rc; @@ -30390,23 +31778,24 @@ static int winMutexTry(sqlite3_mutex *p){ ** is not currently allocated. SQLite will never do either. */ static void winMutexLeave(sqlite3_mutex *p){ -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - DWORD tid = GetCurrentThreadId(); -#endif assert( p ); #ifdef SQLITE_DEBUG assert( p->nRef>0 ); - assert( p->owner==tid ); + assert( p->owner==GetCurrentThreadId() ); p->nRef--; if( p->nRef==0 ) p->owner = 0; assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); #endif assert( winMutex_isInit==1 ); - LeaveCriticalSection(&p->mutex); + if( p->id==SQLITE_MUTEX_RECURSIVE ){ + LeaveCriticalSection(&p->u.cs); + }else{ + ReleaseSRWLockExclusive(&p->u.srwl); + } #ifdef SQLITE_DEBUG if( p->trace ){ OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n", - tid, p->id, p, p->trace, p->nRef)); + GetCurrentThreadId(), p->id, p, p->trace, p->nRef)); } #endif } @@ -30726,27 +32115,6 @@ static void mallocWithAlarm(int n, void **pp){ *pp = p; } -/* -** Maximum size of any single memory allocation. -** -** This is not a limit on the total amount of memory used. This is -** a limit on the size parameter to sqlite3_malloc() and sqlite3_realloc(). -** -** The upper bound is slightly less than 2GiB: 0x7ffffeff == 2,147,483,391 -** This provides a 256-byte safety margin for defense against 32-bit -** signed integer overflow bugs when computing memory allocation sizes. -** Paranoid applications might want to reduce the maximum allocation size -** further for an even larger safety margin. 0x3fffffff or 0x0fffffff -** or even smaller would be reasonable upper bounds on the size of a memory -** allocations for most applications. -*/ -#ifndef SQLITE_MAX_ALLOCATION_SIZE -# define SQLITE_MAX_ALLOCATION_SIZE 2147483391 -#endif -#if SQLITE_MAX_ALLOCATION_SIZE>2147483391 -# error Maximum size for SQLITE_MAX_ALLOCATION_SIZE is 2147483391 -#endif - /* ** Allocate memory. This routine is like sqlite3_malloc() except that it ** assumes the memory subsystem has already been initialized. @@ -30970,8 +32338,7 @@ SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){ sqlite3_free(pOld); /* IMP: R-26507-47431 */ return 0; } - if( nBytes>=0x7fffff00 ){ - /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ + if( nBytes>SQLITE_MAX_ALLOCATION_SIZE ){ return 0; } nOld = sqlite3MallocSize(pOld); @@ -31385,17 +32752,19 @@ SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){ #define etPERCENT 7 /* Percent symbol. %% */ #define etCHARX 8 /* Characters. %c */ /* The rest are extensions, not normally found in printf() */ -#define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */ -#define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '', - NULL pointers replaced by SQL NULL. %Q */ -#define etTOKEN 11 /* a pointer to a Token structure */ -#define etSRCITEM 12 /* a pointer to a SrcItem */ -#define etPOINTER 13 /* The %p conversion */ -#define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */ -#define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ -#define etDECIMAL 16 /* %d or %u, but not %x, %o */ +#define etESCAPE_q 9 /* Strings with '\'' doubled. %q */ +#define etESCAPE_Q 10 /* Strings with '\'' doubled and enclosed in '', + NULL pointers replaced by SQL NULL. %Q */ +#define etTOKEN 11 /* a pointer to a Token structure */ +#define etSRCITEM 12 /* a pointer to a SrcItem */ +#define etPOINTER 13 /* The %p conversion */ +#define etESCAPE_w 14 /* %w -> Strings with '\"' doubled */ +#define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ +#define etDECIMAL 16 /* %d or %u, but not %x, %o */ +#define etESCAPE_j 17 /* %j -> JSON string literal w/o "..." */ +#define etESCAPE_J 18 /* %J -> JSON string literal with "..." */ -#define etINVALID 17 /* Any unrecognized conversion type */ +#define etINVALID 19 /* Any unrecognized conversion type */ /* @@ -31414,6 +32783,7 @@ typedef struct et_info { /* Information about each format field */ etByte type; /* Conversion paradigm */ etByte charset; /* Offset into aDigits[] of the digits string */ etByte prefix; /* Offset into aPrefix[] of the prefix string */ + char iNxt; /* Next with same hash, or 0 for end of chain */ } et_info; /* @@ -31422,44 +32792,64 @@ typedef struct et_info { /* Information about each format field */ #define FLAG_SIGNED 1 /* True if the value to convert is signed */ #define FLAG_STRING 4 /* Allow infinite precision */ - /* -** The following table is searched linearly, so it is good to put the -** most frequently used conversion types first. +** The table is searched by hash. In the case of %C where C is the character +** and that character has ASCII value j, then the hash is j%25. +** +** The order of the entries in fmtinfo[] and the hash chain was entered +** manually, but based on the output of the following TCL script: */ +#if 0 /***** Beginning of script ******/ +foreach c {d s g z q Q w c o u x X f e E G i n % p T S r J j} { + scan $c %c x + set n($c) $x +} +set mx [llength [array names n]] +puts "count: $mx" + +set mx 25 +puts "*********** mx=$mx ************" +for {set r 0} {$r<$mx} {incr r} { + puts -nonewline [format %2d: $r] + foreach c [array names n] { + if {($n($c))%$mx==$r} {puts -nonewline " $c"} + } + puts "" +} +#endif /***** End of script ********/ + static const char aDigits[] = "0123456789ABCDEF0123456789abcdef"; +static const char aHex[] = "0123456789abcdef"; static const char aPrefix[] = "-x0\000X0"; -static const et_info fmtinfo[] = { - { 'd', 10, 1, etDECIMAL, 0, 0 }, - { 's', 0, 4, etSTRING, 0, 0 }, - { 'g', 0, 1, etGENERIC, 30, 0 }, - { 'z', 0, 4, etDYNSTRING, 0, 0 }, - { 'q', 0, 4, etSQLESCAPE, 0, 0 }, - { 'Q', 0, 4, etSQLESCAPE2, 0, 0 }, - { 'w', 0, 4, etSQLESCAPE3, 0, 0 }, - { 'c', 0, 0, etCHARX, 0, 0 }, - { 'o', 8, 0, etRADIX, 0, 2 }, - { 'u', 10, 0, etDECIMAL, 0, 0 }, - { 'x', 16, 0, etRADIX, 16, 1 }, - { 'X', 16, 0, etRADIX, 0, 4 }, -#ifndef SQLITE_OMIT_FLOATING_POINT - { 'f', 0, 1, etFLOAT, 0, 0 }, - { 'e', 0, 1, etEXP, 30, 0 }, - { 'E', 0, 1, etEXP, 14, 0 }, - { 'G', 0, 1, etGENERIC, 14, 0 }, -#endif - { 'i', 10, 1, etDECIMAL, 0, 0 }, - { 'n', 0, 0, etSIZE, 0, 0 }, - { '%', 0, 0, etPERCENT, 0, 0 }, - { 'p', 16, 0, etPOINTER, 0, 1 }, - - /* All the rest are undocumented and are for internal use only */ - { 'T', 0, 0, etTOKEN, 0, 0 }, - { 'S', 0, 0, etSRCITEM, 0, 0 }, - { 'r', 10, 1, etORDINAL, 0, 0 }, +static const et_info fmtinfo[25] = { + /* 0 */ { 'd', 10, 1, etDECIMAL, 0, 0, 0 }, + /* 1 */ { 'e', 0, 1, etEXP, 30, 0, 0 }, + /* 2 */ { 'f', 0, 1, etFLOAT, 0, 0, 0 }, + /* 3 */ { 'g', 0, 1, etGENERIC, 30, 0, 0 }, + /* 4 */ { 'j', 0, 0, etESCAPE_j, 0, 0, 0 }, /* Hash: 6 */ + /* 5 */ { 'i', 10, 1, etDECIMAL, 0, 0, 0 }, + /* 6 */ { 'Q', 0, 4, etESCAPE_Q, 0, 0, 4 }, + /* 7 */ { 'p', 16, 0, etPOINTER, 0, 1, 0 }, /* Hash: 12 */ + /* 8 */ { 'S', 0, 0, etSRCITEM, 0, 0, 0 }, + /* 9 */ { 'T', 0, 0, etTOKEN, 0, 0, 0 }, + /* 10 */ { 'n', 0, 0, etSIZE, 0, 0, 0 }, + /* 11 */ { 'o', 8, 0, etRADIX, 0, 2, 0 }, + /* 12 */ { '%', 0, 0, etPERCENT, 0, 0, 7 }, + /* 13 */ { 'q', 0, 4, etESCAPE_q, 0, 0, 16 }, + /* 14 */ { 'r', 10, 1, etORDINAL, 0, 0, 0 }, + /* 15 */ { 's', 0, 4, etSTRING, 0, 0, 0 }, + /* 16 */ { 'X', 16, 0, etRADIX, 0, 4, 0 }, /* Hash: 13 */ + /* 17 */ { 'u', 10, 0, etDECIMAL, 0, 0, 0 }, + /* 18 */ { 'w', 0, 4, etESCAPE_w, 0, 0, 0 }, /* Hash: 19 */ + /* 19 */ { 'E', 0, 1, etEXP, 14, 0, 18 }, + /* 20 */ { 'x', 16, 0, etRADIX, 16, 1, 0 }, + /* 21 */ { 'G', 0, 1, etGENERIC, 14, 0, 0 }, + /* 22 */ { 'z', 0, 4, etDYNSTRING, 0, 0, 0 }, + /* 23 */ { 'J', 0, 0, etESCAPE_J, 0, 0, 0 }, /* Hash: 24 */ + /* 24 */ { 'c', 0, 0, etCHARX, 0, 0, 23 } }; -/* Notes: +/* Additional Notes: ** ** %S Takes a pointer to SrcItem. Shows name or database.name ** %!S Like %S but prefer the zName over the zAlias @@ -31507,7 +32897,7 @@ static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){ sqlite3StrAccumSetError(pAccum, SQLITE_TOOBIG); return 0; } - z = sqlite3DbMallocRaw(pAccum->db, n); + z = sqlite3_malloc(n); if( z==0 ){ sqlite3StrAccumSetError(pAccum, SQLITE_NOMEM); } @@ -31524,12 +32914,23 @@ static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){ #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */ /* -** Hard limit on the precision of floating-point conversions. +** Hard limit on the precision of floating-point conversions to +** the minimum of SQLITE_PRINTF_PRECISION_LIMIT and 100 million. */ -#ifndef SQLITE_PRINTF_PRECISION_LIMIT +#ifdef SQLITE_PRINTF_PRECISION_LIMIT +# if SQLITE_PRINTF_PRECISION_LIMIT<100000000 +# define SQLITE_FP_PRECISION_LIMIT SQLITE_PRINTF_PRECISION_LIMIT +# else +# define SQLITE_FP_PRECISION_LIMIT 100000000 +# endif +#else # define SQLITE_FP_PRECISION_LIMIT 100000000 #endif +/* Forward reference */ +static void sqlite3StrAppend64(sqlite3_str *p, const char *z, i64 N); +static void sqlite3StrAppendchar64(sqlite3_str *p, i64 N, char c); + /* ** Render a string given by "fmt" into the StrAccum object. */ @@ -31540,10 +32941,10 @@ SQLITE_API void sqlite3_str_vappendf( ){ int c; /* Next character in the format string */ char *bufpt; /* Pointer to the conversion buffer */ - int precision; /* Precision of the current field */ - int length; /* Length of the field */ + i64 precision; /* Precision of the current field */ + i64 length; /* Length of the field */ int idx; /* A general purpose loop counter */ - int width; /* Width of the current field */ + i64 width; /* Width of the current field */ etByte flag_leftjustify; /* True if "-" flag is present */ etByte flag_prefix; /* '+' or ' ' or 0 for prefix */ etByte flag_alternateform; /* True if "#" flag is present */ @@ -31586,9 +32987,12 @@ SQLITE_API void sqlite3_str_vappendf( #if HAVE_STRCHRNUL fmt = strchrnul(fmt, '%'); #else - do{ fmt++; }while( *fmt && *fmt != '%' ); + fmt = strchr(fmt, '%'); + if( fmt==0 ){ + fmt = bufpt + strlen(bufpt); + } #endif - sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt)); + sqlite3StrAppend64(pAccum, bufpt, fmt - bufpt); if( *fmt==0 ) break; } if( (c=(*++fmt))==0 ){ @@ -31700,6 +33104,9 @@ SQLITE_API void sqlite3_str_vappendf( }while( !done && (c=(*++fmt))!=0 ); /* Fetch the info entry for the field */ +#ifdef SQLITE_EBCDIC + /* The hash table only works for ASCII. For EBCDIC, we need to do + ** a linear search of the table */ infop = &fmtinfo[0]; xtype = etINVALID; for(idx=0; idx<ArraySize(fmtinfo); idx++){ @@ -31709,6 +33116,20 @@ SQLITE_API void sqlite3_str_vappendf( break; } } +#else + /* Fast hash-table lookup */ + assert( ArraySize(fmtinfo)==25 ); + idx = ((unsigned)c) % 25; + if( fmtinfo[idx].fmttype==c + || fmtinfo[idx = fmtinfo[idx].iNxt].fmttype==c + ){ + infop = &fmtinfo[idx]; + xtype = infop->type; + }else{ + infop = &fmtinfo[0]; + xtype = etINVALID; + } +#endif /* ** At this point, variables are initialized as follows: @@ -31776,6 +33197,14 @@ SQLITE_API void sqlite3_str_vappendf( } prefix = 0; } + +#if WHERETRACE_ENABLED + if( xtype==etPOINTER && sqlite3WhereTrace & 0x100000 ) longvalue = 0; +#endif +#if TREETRACE_ENABLED + if( xtype==etPOINTER && sqlite3TreeTrace & 0x100000 ) longvalue = 0; +#endif + if( longvalue==0 ) flag_alternateform = 0; if( flag_zeropad && precision<width-(prefix!=0) ){ precision = width-(prefix!=0); @@ -31809,20 +33238,23 @@ SQLITE_API void sqlite3_str_vappendf( longvalue = longvalue/base; }while( longvalue>0 ); } - length = (int)(&zOut[nOut-1]-bufpt); - while( precision>length ){ - *(--bufpt) = '0'; /* Zero pad */ - length++; + length = &zOut[nOut-1] - bufpt; + if( precision>length ){ /* zero pad */ + i64 nn = precision-length; + bufpt -= nn; + memset(bufpt,'0',nn); + length = precision; } if( cThousand ){ - int nn = (length - 1)/3; /* Number of "," to insert */ - int ix = (length - 1)%3 + 1; + i64 nn = (length - 1)/3; /* Number of "," to insert */ + i64 ix = (length - 1)%3 + 1; + int ii; bufpt -= nn; - for(idx=0; nn>0; idx++){ - bufpt[idx] = bufpt[idx+nn]; + for(ii=0; nn>0; ii++){ + bufpt[ii] = bufpt[ii+nn]; ix--; if( ix==0 ){ - bufpt[++idx] = cThousand; + bufpt[++ii] = cThousand; nn--; ix = 3; } @@ -31835,7 +33267,7 @@ SQLITE_API void sqlite3_str_vappendf( pre = &aPrefix[infop->prefix]; for(; (x=(*pre))!=0; pre++) *(--bufpt) = x; } - length = (int)(&zOut[nOut-1]-bufpt); + length = &zOut[nOut-1] - bufpt; break; case etFLOAT: case etEXP: @@ -31843,6 +33275,7 @@ SQLITE_API void sqlite3_str_vappendf( FpDecode s; int iRound; int j; + i64 szBufNeeded; /* Size needed to hold the output */ if( bArgList ){ realvalue = getDoubleArg(pArgList); @@ -31850,11 +33283,9 @@ SQLITE_API void sqlite3_str_vappendf( realvalue = va_arg(ap,double); } if( precision<0 ) precision = 6; /* Set default precision */ -#ifdef SQLITE_FP_PRECISION_LIMIT if( precision>SQLITE_FP_PRECISION_LIMIT ){ precision = SQLITE_FP_PRECISION_LIMIT; } -#endif if( xtype==etFLOAT ){ iRound = -precision; }else if( xtype==etGENERIC ){ @@ -31863,11 +33294,16 @@ SQLITE_API void sqlite3_str_vappendf( }else{ iRound = precision+1; } - sqlite3FpDecode(&s, realvalue, iRound, flag_altform2 ? 26 : 16); + sqlite3FpDecode(&s, realvalue, iRound, flag_altform2 ? 20 : 16); if( s.isSpecial ){ if( s.isSpecial==2 ){ - bufpt = flag_zeropad ? "null" : "NaN"; - length = sqlite3Strlen30(bufpt); + if( flag_zeropad ){ + bufpt = "null"; + length = 4; + }else{ + bufpt = "NaN"; + length = 3; + } break; }else if( flag_zeropad ){ s.z[0] = '9'; @@ -31883,12 +33319,26 @@ SQLITE_API void sqlite3_str_vappendf( }else{ bufpt++; } - length = sqlite3Strlen30(bufpt); + length = strlen(bufpt); break; } } if( s.sign=='-' ){ - prefix = '-'; + if( flag_alternateform + && !flag_prefix + && xtype==etFLOAT + && s.iDP<=iRound + ){ + /* Suppress the minus sign if all of the following are true: + ** * The value displayed is zero + ** * The '#' flag is used + ** * The '+' flag is not used, and + ** * The format is %f + */ + prefix = 0; + }else{ + prefix = '-'; + } }else{ prefix = flag_prefix; } @@ -31917,17 +33367,31 @@ SQLITE_API void sqlite3_str_vappendf( }else{ e2 = s.iDP - 1; } - bufpt = buf; - { - i64 szBufNeeded; /* Size of a temporary buffer needed */ - szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15; - if( cThousand && e2>0 ) szBufNeeded += (e2+2)/3; - if( szBufNeeded > etBUFSIZE ){ - bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded); - if( bufpt==0 ) return; + + szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+10; + if( cThousand && e2>0 ) szBufNeeded += (e2+2)/3; + if( szBufNeeded + pAccum->nChar >= pAccum->nAlloc ){ + if( pAccum->mxAlloc==0 && pAccum->accError==0 ){ + /* Unable to allocate space in pAccum, perhaps because it + ** is coming from sqlite3_snprintf() or similar. We'll have + ** to render into temporary space and the memcpy() it over. */ + bufpt = sqlite3_malloc64(szBufNeeded); + if( bufpt==0 ){ + sqlite3StrAccumSetError(pAccum, SQLITE_NOMEM); + return; + } + zExtra = bufpt; + }else if( sqlite3StrAccumEnlarge(pAccum, szBufNeeded)<szBufNeeded ){ + width = length = 0; + break; + }else{ + bufpt = pAccum->zText + pAccum->nChar; } + }else{ + bufpt = pAccum->zText + pAccum->nChar; } zOut = bufpt; + flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2; /* The sign in front of the number */ if( prefix ){ @@ -31935,12 +33399,24 @@ SQLITE_API void sqlite3_str_vappendf( } /* Digits prior to the decimal point */ j = 0; + assert( s.n>0 ); if( e2<0 ){ *(bufpt++) = '0'; - }else{ + }else if( cThousand ){ for(; e2>=0; e2--){ *(bufpt++) = j<s.n ? s.z[j++] : '0'; - if( cThousand && (e2%3)==0 && e2>1 ) *(bufpt++) = ','; + if( (e2%3)==0 && e2>1 ) *(bufpt++) = ','; + } + }else{ + j = e2+1; + if( j>s.n ) j = s.n; + memcpy(bufpt, s.z, j); + bufpt += j; + e2 -= j; + if( e2>=0 ){ + memset(bufpt, '0', e2+1); + bufpt += e2+1; + e2 = -1; } } /* The decimal point */ @@ -31949,12 +33425,26 @@ SQLITE_API void sqlite3_str_vappendf( } /* "0" digits after the decimal point but before the first ** significant digit of the number */ - for(e2++; e2<0 && precision>0; precision--, e2++){ - *(bufpt++) = '0'; + if( e2<(-1) && precision>0 ){ + int nn = -1-e2; + if( nn>precision ) nn = precision; + memset(bufpt, '0', nn); + bufpt += nn; + precision -= nn; } /* Significant digits after the decimal point */ - while( (precision--)>0 ){ - *(bufpt++) = j<s.n ? s.z[j++] : '0'; + if( precision>0 ){ + int nn = s.n - j; + if( NEVER(nn>precision) ) nn = precision; + if( nn>0 ){ + memcpy(bufpt, s.z+j, nn); + bufpt += nn; + precision -= nn; + } + if( precision>0 && !flag_rtz ){ + memset(bufpt, '0', precision); + bufpt += precision; + } } /* Remove trailing zeros and the "." if no digits follow the "." */ if( flag_rtz && flag_dp ){ @@ -31984,27 +33474,40 @@ SQLITE_API void sqlite3_str_vappendf( *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */ *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */ } - *bufpt = 0; - - /* The converted number is in buf[] and zero terminated. Output it. - ** Note that the number is in the usual order, not reversed as with - ** integer conversions. */ - length = (int)(bufpt-zOut); - bufpt = zOut; - /* Special case: Add leading zeros if the flag_zeropad flag is - ** set and we are not left justified */ - if( flag_zeropad && !flag_leftjustify && length < width){ - int i; - int nPad = width - length; - for(i=width; i>=nPad; i--){ - bufpt[i] = bufpt[i-nPad]; + length = bufpt - zOut; + assert( length <= szBufNeeded ); + if( length<width ){ + i64 nPad = width - length; + if( flag_leftjustify ){ + memset(bufpt, ' ', nPad); + }else if( !flag_zeropad ){ + memmove(zOut+nPad, zOut, length); + memset(zOut, ' ', nPad); + }else{ + int adj = prefix!=0; + memmove(zOut+nPad+adj, zOut+adj, length-adj); + memset(zOut+adj, '0', nPad); } - i = prefix!=0; - while( nPad-- ) bufpt[i++] = '0'; length = width; } - break; + + if( zExtra==0 ){ + /* The result is being rendered directory into pAccum. This + ** is the common and fast case */ + assert( pAccum->nChar + length < SMXV(pAccum->nChar) ); + pAccum->nChar += length; + zOut[length] = 0; + continue; + }else{ + /* We were unable to render directly into pAccum because we + ** couldn't allocate sufficient memory. We need to memcpy() + ** the rendering (or some prefix thereof) into the output + ** buffer. */ + bufpt[0] = 0; + bufpt = zExtra; + break; + } } case etSIZE: if( !bArgList ){ @@ -32033,43 +33536,24 @@ SQLITE_API void sqlite3_str_vappendf( } }else{ unsigned int ch = va_arg(ap,unsigned int); - if( ch<0x00080 ){ - buf[0] = ch & 0xff; - length = 1; - }else if( ch<0x00800 ){ - buf[0] = 0xc0 + (u8)((ch>>6)&0x1f); - buf[1] = 0x80 + (u8)(ch & 0x3f); - length = 2; - }else if( ch<0x10000 ){ - buf[0] = 0xe0 + (u8)((ch>>12)&0x0f); - buf[1] = 0x80 + (u8)((ch>>6) & 0x3f); - buf[2] = 0x80 + (u8)(ch & 0x3f); - length = 3; - }else{ - buf[0] = 0xf0 + (u8)((ch>>18) & 0x07); - buf[1] = 0x80 + (u8)((ch>>12) & 0x3f); - buf[2] = 0x80 + (u8)((ch>>6) & 0x3f); - buf[3] = 0x80 + (u8)(ch & 0x3f); - length = 4; - } + length = sqlite3AppendOneUtf8Character(buf, ch); } if( precision>1 ){ i64 nPrior = 1; width -= precision-1; if( width>1 && !flag_leftjustify ){ - sqlite3_str_appendchar(pAccum, width-1, ' '); + sqlite3StrAppendchar64(pAccum, width-1, ' '); width = 0; } - sqlite3_str_append(pAccum, buf, length); + sqlite3StrAppend64(pAccum, buf, length); precision--; while( precision > 1 ){ i64 nCopyBytes; if( nPrior > precision-1 ) nPrior = precision - 1; nCopyBytes = length*nPrior; - if( nCopyBytes + pAccum->nChar >= pAccum->nAlloc ){ - sqlite3StrAccumEnlarge(pAccum, nCopyBytes); + if( sqlite3StrAccumEnlargeIfNeeded(pAccum, nCopyBytes) ){ + break; } - if( pAccum->accError ) break; sqlite3_str_append(pAccum, &pAccum->zText[pAccum->nChar-nCopyBytes], nCopyBytes); precision -= nPrior; @@ -32117,36 +33601,122 @@ SQLITE_API void sqlite3_str_vappendf( while( precision-- > 0 && z[0] ){ SQLITE_SKIP_UTF8(z); } - length = (int)(z - (unsigned char*)bufpt); + length = z - (unsigned char*)bufpt; }else{ for(length=0; length<precision && bufpt[length]; length++){} } }else{ - length = 0x7fffffff & (int)strlen(bufpt); + length = strlen(bufpt); } adjust_width_for_utf8: if( flag_altform2 && width>0 ){ /* Adjust width to account for extra bytes in UTF-8 characters */ - int ii = length - 1; + i64 ii = length - 1; while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++; } break; - case etSQLESCAPE: /* %q: Escape ' characters */ - case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */ - case etSQLESCAPE3: { /* %w: Escape " characters */ + case etESCAPE_j: /* %j: JSON string literal w/o "..." */ + case etESCAPE_J: { /* %J: Generate a JSON string literal */ + char *escarg; + i64 i, j, px, iStart; + unsigned char ch; + + if( bArgList ){ + escarg = getTextArg(pArgList); + }else{ + escarg = va_arg(ap,char*); + } + iStart = sqlite3_str_length(pAccum); + if( escarg==0 ){ + if( xtype==etESCAPE_J ) sqlite3_str_append(pAccum, "null", 4); + }else{ + if( xtype==etESCAPE_J ) sqlite3_str_append(pAccum, "\"", 1); + px = precision; + testcase( px==0 ); + if( px<0 ){ + px = 0x7fffffff; + }else if( flag_altform2 ){ + /* Convert precision from code-points to bytes */ + for(i=0; i<px && escarg[i]; i++){ + if( (escarg[i]&0xc0)==0x80 ) px++; + } + if( i==px ){ + while( (escarg[px]&0xc0)==0x80 ) px++; + } + } + for(i=j=0; i<px; i++){ + if( (ch = ((u8*)escarg)[i])<=0x1f || ch=='"' || ch=='\\' ){ + if( j<i ) sqlite3StrAppend64(pAccum, &escarg[j], i-j); + j = i+1; + if( ch==0 ) break; + sqlite3_str_appendchar(pAccum, 1, '\\'); + if( ch>0x1f ){ + sqlite3_str_appendchar(pAccum, 1, ch); + }else if( ((1u<<ch)&0x3700)!=0 ){ + ch = "btn?fr"[ch-8]; + sqlite3_str_appendchar(pAccum, 1, ch); + }else{ + sqlite3_str_append(pAccum, "u00", 3); + sqlite3_str_appendchar(pAccum, 1, aHex[ch>>4]); + sqlite3_str_appendchar(pAccum, 1, aHex[ch&0xf]); + } + } + } + if( j<i ) sqlite3StrAppend64(pAccum, &escarg[j], i-j); + if( xtype==etESCAPE_J ) sqlite3_str_append(pAccum, "\"", 1); + } + if( width>0 && sqlite3_str_errcode(pAccum)==SQLITE_OK ){ + sqlite3_int64 n = sqlite3_str_length(pAccum) - iStart; + sqlite3_int64 len = n; + char *zz; + if( flag_altform2 && n>0 ){ + zz = sqlite3_str_value(pAccum); + for(i=iStart; zz[i]; i++){ + if( (zz[i]&0xc0)==0x80 ) len--; + } + } + if( width>len ){ + sqlite3_int64 sp = width-len; + assert( sp>0 && sp<0x7fffffff ); + sqlite3StrAppendchar64(pAccum, (int)sp, ' '); + if( !flag_leftjustify + && n>0 + && sqlite3_str_errcode(pAccum)==0 + ){ + zz = sqlite3_str_value(pAccum); + zz += iStart; + memmove(zz+sp, zz, n); + memset(zz, ' ', sp); + } + } + } + continue; + } + case etESCAPE_q: /* %q: Escape ' characters */ + case etESCAPE_Q: /* %Q: Escape ' and enclose in '...' */ + case etESCAPE_w: { /* %w: Escape " characters */ i64 i, j, k, n; - int needQuote, isnull; + int needQuote = 0; char ch; - char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */ char *escarg; + char q; if( bArgList ){ escarg = getTextArg(pArgList); }else{ escarg = va_arg(ap,char*); } - isnull = escarg==0; - if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)"); + if( escarg==0 ){ + escarg = (xtype==etESCAPE_Q ? "NULL" : "(NULL)"); + }else if( xtype==etESCAPE_Q ){ + needQuote = 1; + } + if( xtype==etESCAPE_w ){ + q = '"'; + flag_alternateform = 0; + }else{ + q = '\''; + } /* For %q, %Q, and %w, the precision is the number of bytes (or ** characters if the ! flags is present) to use from the input. ** Because of the extra quoting characters inserted, the number @@ -32159,7 +33729,30 @@ SQLITE_API void sqlite3_str_vappendf( while( (escarg[i+1]&0xc0)==0x80 ){ i++; } } } - needQuote = !isnull && xtype==etSQLESCAPE2; + if( flag_alternateform ){ + /* For %#q, do unistr()-style backslash escapes for + ** all control characters, and for backslash itself. + ** For %#Q, do the same but only if there is at least + ** one control character. */ + i64 nBack = 0; + i64 nCtrl = 0; + for(k=0; k<i; k++){ + if( escarg[k]=='\\' ){ + nBack++; + }else if( ((u8*)escarg)[k]<=0x1f ){ + nCtrl++; + } + } + if( nCtrl || xtype==etESCAPE_q ){ + n += nBack + 5*nCtrl; + if( xtype==etESCAPE_Q ){ + n += 10; + needQuote = 2; + } + }else{ + flag_alternateform = 0; + } + } n += i + 3; if( n>etBUFSIZE ){ bufpt = zExtra = printfTempBuf(pAccum, n); @@ -32168,13 +33761,41 @@ SQLITE_API void sqlite3_str_vappendf( bufpt = buf; } j = 0; - if( needQuote ) bufpt[j++] = q; + if( needQuote ){ + if( needQuote==2 ){ + memcpy(&bufpt[j], "unistr('", 8); + j += 8; + }else{ + bufpt[j++] = '\''; + } + } k = i; - for(i=0; i<k; i++){ - bufpt[j++] = ch = escarg[i]; - if( ch==q ) bufpt[j++] = ch; + if( flag_alternateform ){ + for(i=0; i<k; i++){ + bufpt[j++] = ch = escarg[i]; + if( ch==q ){ + bufpt[j++] = ch; + }else if( ch=='\\' ){ + bufpt[j++] = '\\'; + }else if( ((unsigned char)ch)<=0x1f ){ + bufpt[j-1] = '\\'; + bufpt[j++] = 'u'; + bufpt[j++] = '0'; + bufpt[j++] = '0'; + bufpt[j++] = ch>=0x10 ? '1' : '0'; + bufpt[j++] = aHex[ch&0xf]; + } + } + }else{ + for(i=0; i<k; i++){ + bufpt[j++] = ch = escarg[i]; + if( ch==q ) bufpt[j++] = ch; + } + } + if( needQuote ){ + bufpt[j++] = '\''; + if( needQuote==2 ) bufpt[j++] = ')'; } - if( needQuote ) bufpt[j++] = q; bufpt[j] = 0; length = j; goto adjust_width_for_utf8; @@ -32249,11 +33870,11 @@ SQLITE_API void sqlite3_str_vappendf( */ width -= length; if( width>0 ){ - if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' '); - sqlite3_str_append(pAccum, bufpt, length); - if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' '); + if( !flag_leftjustify ) sqlite3StrAppendchar64(pAccum, width, ' '); + sqlite3StrAppend64(pAccum, bufpt, length); + if( flag_leftjustify ) sqlite3StrAppendchar64(pAccum, width, ' '); }else{ - sqlite3_str_append(pAccum, bufpt, length); + sqlite3StrAppend64(pAccum, bufpt, length); } if( zExtra ){ @@ -32292,12 +33913,16 @@ SQLITE_PRIVATE void sqlite3RecordErrorByteOffset(sqlite3 *db, const char *z){ ** as the error offset. */ SQLITE_PRIVATE void sqlite3RecordErrorOffsetOfExpr(sqlite3 *db, const Expr *pExpr){ - while( pExpr - && (ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) || pExpr->w.iOfst<=0) - ){ - pExpr = pExpr->pLeft; + while( pExpr ){ + if( ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) ) return; + if( ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) || pExpr->w.iOfst<=0 ){ + pExpr = pExpr->pLeft; + }else{ + break; + } } if( pExpr==0 ) return; + if( ExprHasProperty(pExpr, EP_FromDDL) ) return; db->errByteOffset = pExpr->w.iOfst; } @@ -32355,6 +33980,13 @@ SQLITE_PRIVATE int sqlite3StrAccumEnlarge(StrAccum *p, i64 N){ return (int)N; } +SQLITE_PRIVATE int sqlite3StrAccumEnlargeIfNeeded(StrAccum *p, i64 N){ + if( N + p->nChar >= p->nAlloc ){ + sqlite3StrAccumEnlarge(p, N); + } + return p->accError; +} + /* ** Append N copies of character c to the given string buffer. */ @@ -32365,6 +33997,13 @@ SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){ } while( (N--)>0 ) p->zText[p->nChar++] = c; } +static void sqlite3StrAppendchar64(sqlite3_str *p, i64 N, char c){ + testcase( p->nChar + N > 0x7fffffff ); + if( p->nChar+N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){ + return; + } + while( (N--)>0 ) p->zText[p->nChar++] = c; +} /* ** The StrAccum "p" is not large enough to accept N new bytes of z[]. @@ -32376,6 +34015,7 @@ SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){ */ static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){ N = sqlite3StrAccumEnlarge(p, N); + assert( z!=0 || N==0 ); if( N>0 ){ memcpy(&p->zText[p->nChar], z, N); p->nChar += N; @@ -32399,6 +34039,20 @@ SQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){ memcpy(&p->zText[p->nChar-N], z, N); } } +static void sqlite3StrAppend64(sqlite3_str *p, const char *z, i64 N){ + assert( z!=0 || N==0 ); + assert( p->zText!=0 || p->nChar==0 || p->accError ); + assert( N>=0 ); + assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 ); + if( p->nChar+N >= (i64)p->nAlloc ){ + enlargeAndAppend(p,z,N); + }else if( N ){ + assert( p->zText ); + p->nChar += N; + memcpy(&p->zText[p->nChar-N], z, N); + } +} + /* ** Append the complete text of zero-terminated string z[] to the p string. @@ -32416,7 +34070,7 @@ SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){ static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){ char *zText; assert( p->mxAlloc>0 && !isMalloced(p) ); - zText = sqlite3DbMallocRaw(p->db, p->nChar+1 ); + zText = sqlite3DbMallocRaw(p->db, 1+(u64)p->nChar ); if( zText ){ memcpy(zText, p->zText, p->nChar+1); p->printfFlags |= SQLITE_PRINTF_MALLOCED; @@ -32436,37 +34090,11 @@ SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){ return p->zText; } -/* -** Use the content of the StrAccum passed as the second argument -** as the result of an SQL function. -*/ -SQLITE_PRIVATE void sqlite3ResultStrAccum(sqlite3_context *pCtx, StrAccum *p){ - if( p->accError ){ - sqlite3_result_error_code(pCtx, p->accError); - sqlite3_str_reset(p); - }else if( isMalloced(p) ){ - sqlite3_result_text(pCtx, p->zText, p->nChar, SQLITE_DYNAMIC); - }else{ - sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); - sqlite3_str_reset(p); - } -} - -/* -** This singleton is an sqlite3_str object that is returned if -** sqlite3_malloc() fails to provide space for a real one. This -** sqlite3_str object accepts no new text and always returns -** an SQLITE_NOMEM error. -*/ -static sqlite3_str sqlite3OomStr = { - 0, 0, 0, 0, 0, SQLITE_NOMEM, 0 -}; - /* Finalize a string created using sqlite3_str_new(). */ SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){ char *z; - if( p!=0 && p!=&sqlite3OomStr ){ + if( p!=0 && p!=(sqlite3_str*)&sqlite3OomStr ){ z = sqlite3StrAccumFinish(p); sqlite3_free(p); }else{ @@ -32485,6 +34113,14 @@ SQLITE_API int sqlite3_str_length(sqlite3_str *p){ return p ? p->nChar : 0; } +/* Truncate the text of the string to be no more than N bytes. */ +SQLITE_API void sqlite3_str_truncate(sqlite3_str *p, int N){ + if( p!=0 && N>=0 && (u32)N<p->nChar ){ + p->nChar = N; + p->zText[p->nChar] = 0; + } +} + /* Return the current value for p */ SQLITE_API char *sqlite3_str_value(sqlite3_str *p){ if( p==0 || p->nChar==0 ) return 0; @@ -32499,12 +34135,25 @@ SQLITE_API void sqlite3_str_reset(StrAccum *p){ if( isMalloced(p) ){ sqlite3DbFree(p->db, p->zText); p->printfFlags &= ~SQLITE_PRINTF_MALLOCED; + }else if( p==(sqlite3_str*)&sqlite3OomStr ){ + return; } p->nAlloc = 0; p->nChar = 0; p->zText = 0; } +/* +** Destroy a dynamically allocate sqlite3_str object and all +** of its content, all in one call. +*/ +SQLITE_API void sqlite3_str_free(sqlite3_str *p){ + if( p!=0 && p!=(sqlite3_str*)&sqlite3OomStr ){ + sqlite3_str_reset(p); + sqlite3_free(p); + } +} + /* ** Initialize a string accumulator. ** @@ -32536,7 +34185,7 @@ SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){ sqlite3StrAccumInit(p, 0, 0, 0, db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH); }else{ - p = &sqlite3OomStr; + p = (sqlite3_str*)&sqlite3OomStr; } return p; } @@ -32661,6 +34310,15 @@ SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){ return zBuf; } +/* Maximum size of an sqlite3_log() message. */ +#if defined(SQLITE_MAX_LOG_MESSAGE) + /* Leave the definition as supplied */ +#elif SQLITE_PRINT_BUF_SIZE*10>10000 +# define SQLITE_MAX_LOG_MESSAGE 10000 +#else +# define SQLITE_MAX_LOG_MESSAGE (SQLITE_PRINT_BUF_SIZE*10) +#endif + /* ** This is the routine that actually formats the sqlite3_log() message. ** We house it in a separate routine from sqlite3_log() to avoid using @@ -32677,7 +34335,7 @@ SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){ */ static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){ StrAccum acc; /* String accumulator */ - char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */ + char zMsg[SQLITE_MAX_LOG_MESSAGE]; /* Complete log message */ sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0); sqlite3_str_vappendf(&acc, zFormat, ap); @@ -33024,10 +34682,13 @@ SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc) sqlite3_str_appendf(&x, " DDL"); } if( pItem->fg.isCte ){ - sqlite3_str_appendf(&x, " CteUse=0x%p", pItem->u2.pCteUse); + static const char *aMat[] = {",MAT", "", ",NO-MAT"}; + sqlite3_str_appendf(&x, " CteUse=%d%s", + pItem->u2.pCteUse->nUse, + aMat[pItem->u2.pCteUse->eM10d]); } if( pItem->fg.isOn || (pItem->fg.isUsing==0 && pItem->u3.pOn!=0) ){ - sqlite3_str_appendf(&x, " ON"); + sqlite3_str_appendf(&x, " isOn"); } if( pItem->fg.isTabFunc ) sqlite3_str_appendf(&x, " isTabFunc"); if( pItem->fg.isCorrelated ) sqlite3_str_appendf(&x, " isCorrelated"); @@ -33044,9 +34705,13 @@ SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc) n = 0; if( pItem->fg.isSubquery ) n++; if( pItem->fg.isTabFunc ) n++; - if( pItem->fg.isUsing ) n++; + if( pItem->fg.isUsing || pItem->u3.pOn!=0 ) n++; if( pItem->fg.isUsing ){ sqlite3TreeViewIdList(pView, pItem->u3.pUsing, (--n)>0, "USING"); + }else if( pItem->u3.pOn!=0 ){ + sqlite3TreeViewItem(pView, "ON", (--n)>0); + sqlite3TreeViewExpr(pView, pItem->u3.pOn, 0); + sqlite3TreeViewPop(&pView); } if( pItem->fg.isSubquery ){ assert( n==1 ); @@ -33055,9 +34720,6 @@ SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc) sqlite3TreeViewColumnList(pView, pTab->aCol, pTab->nCol, 1); } assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem) ); - sqlite3TreeViewPush(&pView, 0); - sqlite3TreeViewLine(pView, "SUBQUERY"); - sqlite3TreeViewPop(&pView); sqlite3TreeViewSelect(pView, pItem->u4.pSubq->pSelect, 0); } if( pItem->fg.isTabFunc ){ @@ -33416,6 +35078,10 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken); break; } + case TK_ASTERISK: { + sqlite3TreeViewLine(pView,"ASKTERISK"); + break; + } #ifndef SQLITE_OMIT_CAST case TK_CAST: { /* Expressions of the form: CAST(pLeft AS token) */ @@ -33787,21 +35453,7 @@ SQLITE_PRIVATE void sqlite3TreeViewBareIdList( if( zName==0 ) zName = "(null)"; sqlite3TreeViewPush(&pView, moreToFollow); sqlite3TreeViewLine(pView, 0); - if( pList->eU4==EU4_NONE ){ - fprintf(stdout, "%s\n", zName); - }else if( pList->eU4==EU4_IDX ){ - fprintf(stdout, "%s (%d)\n", zName, pList->a[i].u4.idx); - }else{ - assert( pList->eU4==EU4_EXPR ); - if( pList->a[i].u4.pExpr==0 ){ - fprintf(stdout, "%s (pExpr=NULL)\n", zName); - }else{ - fprintf(stdout, "%s\n", zName); - sqlite3TreeViewPush(&pView, i<pList->nId-1); - sqlite3TreeViewExpr(pView, pList->a[i].u4.pExpr, 0); - sqlite3TreeViewPop(&pView); - } - } + fprintf(stdout, "%s\n", zName); sqlite3TreeViewPop(&pView); } } @@ -34111,11 +35763,21 @@ SQLITE_PRIVATE void sqlite3TreeViewTrigger( ** accessible to the debugging, and to avoid warnings about unused ** functions. But these routines only exist in debugging builds, so they ** do not contaminate the interface. +** +** See Also: +** +** sqlite3ShowWhereTerm() in where.c */ SQLITE_PRIVATE void sqlite3ShowExpr(const Expr *p){ sqlite3TreeViewExpr(0,p,0); } SQLITE_PRIVATE void sqlite3ShowExprList(const ExprList *p){ sqlite3TreeViewExprList(0,p,0,0);} SQLITE_PRIVATE void sqlite3ShowIdList(const IdList *p){ sqlite3TreeViewIdList(0,p,0,0); } -SQLITE_PRIVATE void sqlite3ShowSrcList(const SrcList *p){ sqlite3TreeViewSrcList(0,p); } +SQLITE_PRIVATE void sqlite3ShowSrcList(const SrcList *p){ + TreeView *pView = 0; + sqlite3TreeViewPush(&pView, 0); + sqlite3TreeViewLine(pView, "SRCLIST"); + sqlite3TreeViewSrcList(pView,p); + sqlite3TreeViewPop(&pView); +} SQLITE_PRIVATE void sqlite3ShowSelect(const Select *p){ sqlite3TreeViewSelect(0,p,0); } SQLITE_PRIVATE void sqlite3ShowWith(const With *p){ sqlite3TreeViewWith(0,p,0); } SQLITE_PRIVATE void sqlite3ShowUpsert(const Upsert *p){ sqlite3TreeViewUpsert(0,p,0); } @@ -34496,6 +36158,7 @@ SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ rc = sqlite3Win32Wait((HANDLE)p->tid); assert( rc!=WAIT_IO_COMPLETION ); bRc = CloseHandle((HANDLE)p->tid); + (void)bRc; /* Prevent warning when assert() is a no-op */ assert( bRc ); } if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult; @@ -34682,6 +36345,35 @@ static const unsigned char sqlite3Utf8Trans1[] = { } \ } +/* +** Write a single UTF8 character whose value is v into the +** buffer starting at zOut. zOut must be sized to hold at +** least four bytes. Return the number of bytes needed +** to encode the new character. +*/ +SQLITE_PRIVATE int sqlite3AppendOneUtf8Character(char *zOut, u32 v){ + if( v<0x00080 ){ + zOut[0] = (u8)(v & 0xff); + return 1; + } + if( v<0x00800 ){ + zOut[0] = 0xc0 + (u8)((v>>6) & 0x1f); + zOut[1] = 0x80 + (u8)(v & 0x3f); + return 2; + } + if( v<0x10000 ){ + zOut[0] = 0xe0 + (u8)((v>>12) & 0x0f); + zOut[1] = 0x80 + (u8)((v>>6) & 0x3f); + zOut[2] = 0x80 + (u8)(v & 0x3f); + return 3; + } + zOut[0] = 0xf0 + (u8)((v>>18) & 0x07); + zOut[1] = 0x80 + (u8)((v>>12) & 0x3f); + zOut[2] = 0x80 + (u8)((v>>6) & 0x3f); + zOut[3] = 0x80 + (u8)(v & 0x3f); + return 4; +} + /* ** Translate a single UTF-8 character. Return the unicode value. ** @@ -34716,9 +36408,7 @@ static const unsigned char sqlite3Utf8Trans1[] = { while( zIn<zTerm && (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ - if( c<0x80 \ - || (c&0xFFFFF800)==0xD800 \ - || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ + if( c<0x80 || (c&0xFFFFF800)==0xD800 ){ c = 0xFFFD; } \ } SQLITE_PRIVATE u32 sqlite3Utf8Read( const unsigned char **pz /* Pointer to string from which to read char */ @@ -34734,9 +36424,7 @@ SQLITE_PRIVATE u32 sqlite3Utf8Read( while( (*(*pz) & 0xc0)==0x80 ){ c = (c<<6) + (0x3f & *((*pz)++)); } - if( c<0x80 - || (c&0xFFFFF800)==0xD800 - || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } + if( c<0x80 || (c&0xFFFFF800)==0xD800 ){ c = 0xFFFD; } } return c; } @@ -35103,7 +36791,7 @@ SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nByte, int nChar){ int n = 0; if( SQLITE_UTF16NATIVE==SQLITE_UTF16LE ) z++; - while( n<nChar && ALWAYS(z<=zEnd) ){ + while( n<nChar && z<=zEnd ){ c = z[0]; z += 2; if( c>=0xd8 && c<0xdc && z<=zEnd && z[0]>=0xdc && z[0]<0xe0 ) z += 2; @@ -35136,7 +36824,6 @@ SQLITE_PRIVATE void sqlite3UtfSelfTest(void){ c = sqlite3Utf8Read((const u8**)&z); t = i; if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD; - if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD; assert( c==t ); assert( (z-zBuf)==n ); } @@ -35167,8 +36854,15 @@ SQLITE_PRIVATE void sqlite3UtfSelfTest(void){ /* #include <stdarg.h> */ #ifndef SQLITE_OMIT_FLOATING_POINT #include <math.h> + +/* Work around a bug in older Microsoft compilers +** Forum post 2026-04-10T06:33:11z */ +#if !defined(INFINITY) && defined(_MSC_VER) +# define INFINITY HUGE_VAL #endif +#endif /* SQLITE_OMIT_FLOATING_POINT */ + /* ** Calls to sqlite3FaultSim() are used to simulate a failure during testing, ** or to bypass normal error detection during testing in order to let @@ -35606,255 +37300,618 @@ SQLITE_PRIVATE u8 sqlite3StrIHash(const char *z){ return h; } -/* Double-Double multiplication. (x[0],x[1]) *= (y,yy) -** -** Reference: -** T. J. Dekker, "A Floating-Point Technique for Extending the -** Available Precision". 1971-07-26. +#if !defined(SQLITE_DISABLE_INTRINSIC) \ + && (defined(__GNUC__) || defined(__clang__)) \ + && (defined(__x86_64__) || defined(__aarch64__) || \ + (defined(__riscv) && defined(__riscv_xlen) && (__riscv_xlen>32))) +#define SQLITE_USE_UINT128 +#endif + +/* +** Two inputs are multiplied to get a 128-bit result. Write the +** lower 64-bits of the result into *pLo, and return the high-order +** 64 bits. */ -static void dekkerMul2(volatile double *x, double y, double yy){ - /* - ** The "volatile" keywords on parameter x[] and on local variables - ** below are needed force intermediate results to be truncated to - ** binary64 rather than be carried around in an extended-precision - ** format. The truncation is necessary for the Dekker algorithm to - ** work. Intel x86 floating point might omit the truncation without - ** the use of volatile. - */ - volatile double tx, ty, p, q, c, cc; - double hx, hy; - u64 m; - memcpy(&m, (void*)&x[0], 8); - m &= 0xfffffffffc000000LL; - memcpy(&hx, &m, 8); - tx = x[0] - hx; - memcpy(&m, &y, 8); - m &= 0xfffffffffc000000LL; - memcpy(&hy, &m, 8); - ty = y - hy; - p = hx*hy; - q = hx*ty + tx*hy; - c = p+q; - cc = p - c + q + tx*ty; - cc = x[0]*yy + x[1]*y + cc; - x[0] = c + cc; - x[1] = c - x[0]; - x[1] += cc; +static u64 sqlite3Multiply128(u64 a, u64 b, u64 *pLo){ +#if defined(SQLITE_USE_UINT128) + __uint128_t r = (__uint128_t)a * b; + *pLo = (u64)r; + return (u64)(r>>64); +#elif defined(_WIN64) && !defined(SQLITE_DISABLE_INTRINSIC) + *pLo = a*b; + return __umulh(a, b); +#else + u64 a0 = (u32)a; + u64 a1 = a >> 32; + u64 b0 = (u32)b; + u64 b1 = b >> 32; + u64 a0b0 = a0 * b0; + u64 a1b1 = a1 * b1; + u64 a0b1 = a0 * b1; + u64 a1b0 = a1 * b0; + u64 t = (a0b0 >> 32) + (u32)a0b1 + (u32)a1b0; + *pLo = (a0b0 & UINT64_C(0xffffffff)) | (t << 32); + return a1b1 + (a0b1>>32) + (a1b0>>32) + (t>>32); +#endif +} + +/* +** A is an unsigned 96-bit integer formed by (a<<32)+aLo. +** B is an unsigned 64-bit integer. +** +** Compute the upper 96 bits of 160-bit result of A*B. +** +** Write ((A*B)>>64 & 0xffffffff) (the middle 32 bits of A*B) +** into *pLo. Return the upper 64 bits of A*B. +** +** The lower 64 bits of A*B are discarded. +*/ +static u64 sqlite3Multiply160(u64 a, u32 aLo, u64 b, u32 *pLo){ +#if defined(SQLITE_USE_UINT128) + __uint128_t r = (__uint128_t)a * b; + r += ((__uint128_t)aLo * b) >> 32; + *pLo = (r>>32)&0xffffffff; + return r>>64; +#elif defined(_WIN64) && !defined(SQLITE_DISABLE_INTRINSIC) + u64 r1_hi = __umulh(a,b); + u64 r1_lo = a*b; + u64 r2 = (__umulh((u64)aLo,b)<<32) + ((aLo*b)>>32); + u64 t = r1_lo + r2; + if( t<r1_lo ) r1_hi++; + *pLo = t>>32; + return r1_hi; +#else + u64 x2 = a>>32; + u64 x1 = a&0xffffffff; + u64 x0 = aLo; + u64 y1 = b>>32; + u64 y0 = b&0xffffffff; + u64 x2y1 = x2*y1; + u64 r4 = x2y1>>32; + u64 x2y0 = x2*y0; + u64 x1y1 = x1*y1; + u64 r3 = (x2y1 & 0xffffffff) + (x2y0 >>32) + (x1y1 >>32); + u64 x1y0 = x1*y0; + u64 x0y1 = x0*y1; + u64 r2 = (x2y0 & 0xffffffff) + (x1y1 & 0xffffffff) + + (x1y0 >>32) + (x0y1>>32); + u64 x0y0 = x0*y0; + u64 r1 = (x1y0 & 0xffffffff) + (x0y1 & 0xffffffff) + + (x0y0 >>32); + r2 += r1>>32; + r3 += r2>>32; + *pLo = r2&0xffffffff; + return (r4<<32) + r3; +#endif } +#undef SQLITE_USE_UINT128 + /* -** The string z[] is an text representation of a real number. -** Convert this string to a double and write it into *pResult. +** Return a u64 with the N-th bit set. +*/ +#define U64_BIT(N) (((u64)1)<<(N)) + +/* +** Range of powers of 10 that we need to deal with when converting +** IEEE754 doubles to and from decimal. +*/ +#define POWERSOF10_FIRST (-348) +#define POWERSOF10_LAST (+347) + +/* +** For any p between -348 and +347, return the integer part of ** -** The string z[] is length bytes in length (bytes, not characters) and -** uses the encoding enc. The string is not necessarily zero-terminated. +** pow(10,p) * pow(2,63-pow10to2(p)) ** -** Return TRUE if the result is a valid real number (or integer) and FALSE -** if the string is empty or contains extraneous text. More specifically -** return -** 1 => The input string is a pure integer -** 2 or more => The input has a decimal point or eNNN clause -** 0 or less => The input string is not a valid number -** -1 => Not a valid number, but has a valid prefix which -** includes a decimal point and/or an eNNN clause +** Or, in other words, for any p in range, return the most significant +** 64 bits of pow(10,p). The pow(10,p) value is shifted left or right, +** as appropriate so the most significant 64 bits fit exactly into a +** 64-bit unsigned integer. ** -** Valid numbers are in one of these formats: +** Write into *pLo the next 32 significant bits of the answer after +** the first 64. ** -** [+-]digits[E[+-]digits] -** [+-]digits.[digits][E[+-]digits] -** [+-].digits[E[+-]digits] +** Algorithm: +** +** (1) For p between 0 and 26, return the value directly from the aBase[] +** lookup table. +** +** (2) For p outside the range 0 to 26, use aScale[] for the initial value +** then refine that result (if necessary) by a single multiplication +** against aBase[]. +** +** The constant tables aBase[], aScale[], and aScaleLo[] are generated +** by the C program at ../tool/mkfptab.c run with the --round option. +*/ +static u64 powerOfTen(int p, u32 *pLo){ + static const u64 aBase[] = { + UINT64_C(0x8000000000000000), /* 0: 1.0e+0 << 63 */ + UINT64_C(0xa000000000000000), /* 1: 1.0e+1 << 60 */ + UINT64_C(0xc800000000000000), /* 2: 1.0e+2 << 57 */ + UINT64_C(0xfa00000000000000), /* 3: 1.0e+3 << 54 */ + UINT64_C(0x9c40000000000000), /* 4: 1.0e+4 << 50 */ + UINT64_C(0xc350000000000000), /* 5: 1.0e+5 << 47 */ + UINT64_C(0xf424000000000000), /* 6: 1.0e+6 << 44 */ + UINT64_C(0x9896800000000000), /* 7: 1.0e+7 << 40 */ + UINT64_C(0xbebc200000000000), /* 8: 1.0e+8 << 37 */ + UINT64_C(0xee6b280000000000), /* 9: 1.0e+9 << 34 */ + UINT64_C(0x9502f90000000000), /* 10: 1.0e+10 << 30 */ + UINT64_C(0xba43b74000000000), /* 11: 1.0e+11 << 27 */ + UINT64_C(0xe8d4a51000000000), /* 12: 1.0e+12 << 24 */ + UINT64_C(0x9184e72a00000000), /* 13: 1.0e+13 << 20 */ + UINT64_C(0xb5e620f480000000), /* 14: 1.0e+14 << 17 */ + UINT64_C(0xe35fa931a0000000), /* 15: 1.0e+15 << 14 */ + UINT64_C(0x8e1bc9bf04000000), /* 16: 1.0e+16 << 10 */ + UINT64_C(0xb1a2bc2ec5000000), /* 17: 1.0e+17 << 7 */ + UINT64_C(0xde0b6b3a76400000), /* 18: 1.0e+18 << 4 */ + UINT64_C(0x8ac7230489e80000), /* 19: 1.0e+19 >> 0 */ + UINT64_C(0xad78ebc5ac620000), /* 20: 1.0e+20 >> 3 */ + UINT64_C(0xd8d726b7177a8000), /* 21: 1.0e+21 >> 6 */ + UINT64_C(0x878678326eac9000), /* 22: 1.0e+22 >> 10 */ + UINT64_C(0xa968163f0a57b400), /* 23: 1.0e+23 >> 13 */ + UINT64_C(0xd3c21bcecceda100), /* 24: 1.0e+24 >> 16 */ + UINT64_C(0x84595161401484a0), /* 25: 1.0e+25 >> 20 */ + UINT64_C(0xa56fa5b99019a5c8), /* 26: 1.0e+26 >> 23 */ + }; + static const u64 aScale[] = { + UINT64_C(0x8049a4ac0c5811ae), /* 0: 1.0e-351 << 1229 */ + UINT64_C(0xcf42894a5dce35ea), /* 1: 1.0e-324 << 1140 */ + UINT64_C(0xa76c582338ed2621), /* 2: 1.0e-297 << 1050 */ + UINT64_C(0x873e4f75e2224e68), /* 3: 1.0e-270 << 960 */ + UINT64_C(0xda7f5bf590966848), /* 4: 1.0e-243 << 871 */ + UINT64_C(0xb080392cc4349dec), /* 5: 1.0e-216 << 781 */ + UINT64_C(0x8e938662882af53e), /* 6: 1.0e-189 << 691 */ + UINT64_C(0xe65829b3046b0afa), /* 7: 1.0e-162 << 602 */ + UINT64_C(0xba121a4650e4ddeb), /* 8: 1.0e-135 << 512 */ + UINT64_C(0x964e858c91ba2655), /* 9: 1.0e-108 << 422 */ + UINT64_C(0xf2d56790ab41c2a2), /* 10: 1.0e-81 << 333 */ + UINT64_C(0xc428d05aa4751e4c), /* 11: 1.0e-54 << 243 */ + UINT64_C(0x9e74d1b791e07e48), /* 12: 1.0e-27 << 153 */ + UINT64_C(0xcccccccccccccccc), /* 13: 1.0e-1 << 67 (special case) */ + UINT64_C(0xcecb8f27f4200f3a), /* 14: 1.0e+27 >> 26 */ + UINT64_C(0xa70c3c40a64e6c51), /* 15: 1.0e+54 >> 116 */ + UINT64_C(0x86f0ac99b4e8dafd), /* 16: 1.0e+81 >> 206 */ + UINT64_C(0xda01ee641a708de9), /* 17: 1.0e+108 >> 295 */ + UINT64_C(0xb01ae745b101e9e4), /* 18: 1.0e+135 >> 385 */ + UINT64_C(0x8e41ade9fbebc27d), /* 19: 1.0e+162 >> 475 */ + UINT64_C(0xe5d3ef282a242e81), /* 20: 1.0e+189 >> 564 */ + UINT64_C(0xb9a74a0637ce2ee1), /* 21: 1.0e+216 >> 654 */ + UINT64_C(0x95f83d0a1fb69cd9), /* 22: 1.0e+243 >> 744 */ + UINT64_C(0xf24a01a73cf2dccf), /* 23: 1.0e+270 >> 833 */ + UINT64_C(0xc3b8358109e84f07), /* 24: 1.0e+297 >> 923 */ + UINT64_C(0x9e19db92b4e31ba9), /* 25: 1.0e+324 >> 1013 */ + }; + static const unsigned int aScaleLo[] = { + 0x205b896d, /* 0: 1.0e-351 << 1229 */ + 0x52064cad, /* 1: 1.0e-324 << 1140 */ + 0xaf2af2b8, /* 2: 1.0e-297 << 1050 */ + 0x5a7744a7, /* 3: 1.0e-270 << 960 */ + 0xaf39a475, /* 4: 1.0e-243 << 871 */ + 0xbd8d794e, /* 5: 1.0e-216 << 781 */ + 0x547eb47b, /* 6: 1.0e-189 << 691 */ + 0x0cb4a5a3, /* 7: 1.0e-162 << 602 */ + 0x92f34d62, /* 8: 1.0e-135 << 512 */ + 0x3a6a07f9, /* 9: 1.0e-108 << 422 */ + 0xfae27299, /* 10: 1.0e-81 << 333 */ + 0xaa97e14c, /* 11: 1.0e-54 << 243 */ + 0x775ea265, /* 12: 1.0e-27 << 153 */ + 0xcccccccc, /* 13: 1.0e-1 << 67 (special case) */ + 0x00000000, /* 14: 1.0e+27 >> 26 */ + 0x999090b6, /* 15: 1.0e+54 >> 116 */ + 0x69a028bb, /* 16: 1.0e+81 >> 206 */ + 0xe80e6f48, /* 17: 1.0e+108 >> 295 */ + 0x5ec05dd0, /* 18: 1.0e+135 >> 385 */ + 0x14588f14, /* 19: 1.0e+162 >> 475 */ + 0x8f1668c9, /* 20: 1.0e+189 >> 564 */ + 0x6d953e2c, /* 21: 1.0e+216 >> 654 */ + 0x4abdaf10, /* 22: 1.0e+243 >> 744 */ + 0xbc633b39, /* 23: 1.0e+270 >> 833 */ + 0x0a862f81, /* 24: 1.0e+297 >> 923 */ + 0x6c07a2c2, /* 25: 1.0e+324 >> 1013 */ + }; + int g, n; + u64 s, x; + u32 lo; + + assert( p>=POWERSOF10_FIRST && p<=POWERSOF10_LAST ); + if( p<0 ){ + if( p==(-1) ){ + *pLo = aScaleLo[13]; + return aScale[13]; + } + g = p/27; + n = p%27; + if( n ){ + g--; + n += 27; + } + }else if( p<27 ){ + *pLo = 0; + return aBase[p]; + }else{ + g = p/27; + n = p%27; + } + s = aScale[g+13]; + if( n==0 ){ + *pLo = aScaleLo[g+13]; + return s; + } + x = sqlite3Multiply160(s,aScaleLo[g+13],aBase[n],&lo); + if( (U64_BIT(63) & x)==0 ){ + x = x<<1 | ((lo>>31)&1); + lo = (lo<<1) | 1; + } + *pLo = lo; + return x; +} + +/* +** pow10to2(x) computes floor(log2(pow(10,x))). +** pow2to10(y) computes floor(log10(pow(2,y))). +** +** Conceptually, pow10to2(p) converts a base-10 exponent p into +** a corresponding base-2 exponent, and pow2to10(e) converts a base-2 +** exponent into a base-10 exponent. ** -** Leading and trailing whitespace is ignored for the purpose of determining -** validity. +** The conversions are based on the observation that: ** -** If some prefix of the input string is a valid number, this routine -** returns FALSE but it still converts the prefix and writes the result -** into *pResult. +** ln(10.0)/ln(2.0) == 108853/32768 (approximately) +** ln(2.0)/ln(10.0) == 78913/262144 (approximately) +** +** These ratios are approximate, but they are accurate to 5 digits, +** which is close enough for the usage here. Right-shift is used +** for division so that rounding of negative numbers happens in the +** right direction. */ -#if defined(_MSC_VER) -#pragma warning(disable : 4756) -#endif -SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){ -#ifndef SQLITE_OMIT_FLOATING_POINT - int incr; - const char *zEnd; - /* sign * significand * (10 ^ (esign * exponent)) */ - int sign = 1; /* sign of significand */ - u64 s = 0; /* significand */ - int d = 0; /* adjust exponent for shifting decimal point */ - int esign = 1; /* sign of exponent */ - int e = 0; /* exponent */ - int eValid = 1; /* True exponent is either not used or is well-formed */ - int nDigit = 0; /* Number of digits processed */ - int eType = 1; /* 1: pure integer, 2+: fractional -1 or less: bad UTF16 */ - double rr[2]; - u64 s2; +static int pwr10to2(int p){ return (p*108853) >> 15; } +static int pwr2to10(int p){ return (p*78913) >> 18; } - assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); - *pResult = 0.0; /* Default return value, in case of an error */ - if( length==0 ) return 0; +/* +** Count leading zeros for a 64-bit unsigned integer. +*/ +static int countLeadingZeros(u64 m){ +#if (defined(__GNUC__) || defined(__clang__)) \ + && !defined(SQLITE_DISABLE_INTRINSIC) + return __builtin_clzll(m); +#else + int n = 0; + if( m <= 0x00000000ffffffffULL) { n += 32; m <<= 32; } + if( m <= 0x0000ffffffffffffULL) { n += 16; m <<= 16; } + if( m <= 0x00ffffffffffffffULL) { n += 8; m <<= 8; } + if( m <= 0x0fffffffffffffffULL) { n += 4; m <<= 4; } + if( m <= 0x3fffffffffffffffULL) { n += 2; m <<= 2; } + if( m <= 0x7fffffffffffffffULL) { n += 1; } + return n; +#endif +} - if( enc==SQLITE_UTF8 ){ - incr = 1; - zEnd = z + length; +/* +** Given m and e, which represent a quantity r == m*pow(2,e), +** return values *pD and *pP such that r == (*pD)*pow(10,*pP), +** approximately. *pD should contain at least n significant digits. +** +** The input m is required to have its highest bit set. In other words, +** m should be left-shifted, and e decremented, to maximize the value of m. +*/ +static void sqlite3Fp2Convert10(u64 m, int e, int n, u64 *pD, int *pP){ + int p; + u64 h, d1; + u32 d2; + assert( n>=1 && n<=18 ); + p = n - 1 - pwr2to10(e+63); + h = sqlite3Multiply128(m, powerOfTen(p,&d2), &d1); + assert( -(e + pwr10to2(p) + 2) >= 0 ); + assert( -(e + pwr10to2(p) + 1) <= 63 ); + if( n==18 ){ + h >>= -(e + pwr10to2(p) + 2); + *pD = (h + ((h<<1)&2))>>1; }else{ - int i; - incr = 2; - length &= ~1; - assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); - testcase( enc==SQLITE_UTF16LE ); - testcase( enc==SQLITE_UTF16BE ); - for(i=3-enc; i<length && z[i]==0; i+=2){} - if( i<length ) eType = -100; - zEnd = &z[i^1]; - z += (enc&1); + *pD = h >> -(e + pwr10to2(p) + 1); } + *pP = -p; +} - /* skip leading spaces */ - while( z<zEnd && sqlite3Isspace(*z) ) z+=incr; - if( z>=zEnd ) return 0; - - /* get sign of significand */ - if( *z=='-' ){ - sign = -1; - z+=incr; - }else if( *z=='+' ){ - z+=incr; - } +/* +** Return an IEEE754 floating point value that approximates d*pow(10,p). +** +** The (current) algorithm is adapted from the work of Ross Cox at +** https://github.com/rsc/fpfmt +*/ +static double sqlite3Fp10Convert2(u64 d, int p){ + int b, lp, e, adj, s; + u32 pwr10l, mid1; + u64 pwr10h, x, hi, lo, sticky, u, m; + double r; + if( p<POWERSOF10_FIRST ) return 0.0; + if( p>POWERSOF10_LAST ) return (double)INFINITY; + b = 64 - countLeadingZeros(d); + lp = pwr10to2(p); + e = 53 - b - lp; + if( e > 1074 ){ + if( e>=1130 ) return 0.0; + e = 1074; + } + s = -(e-(64-b) + lp + 3); + pwr10h = powerOfTen(p, &pwr10l); + if( pwr10l!=0 ){ + pwr10h++; + pwr10l = ~pwr10l; + } + x = d<<(64-b); + hi = sqlite3Multiply128(x,pwr10h,&lo); + mid1 = lo>>32; + sticky = 1; + if( (hi & (U64_BIT(s)-1))==0 ) { + u32 mid2 = sqlite3Multiply128(x,((u64)pwr10l)<<32,&lo)>>32; + sticky = (mid1-mid2 > 1); + hi -= mid1 < mid2; + } + u = (hi>>s) | sticky; + adj = (u >= U64_BIT(55)-2); + if( adj ){ + u = (u>>adj) | (u&1); + e -= adj; + } + m = (u + 1 + ((u>>2)&1)) >> 2; + if( e<=(-972) ) return (double)INFINITY; + if((m & U64_BIT(52)) != 0){ + m = (m & ~U64_BIT(52)) | ((u64)(1075-e)<<52); + } + memcpy(&r,&m,8); + return r; +} - /* copy max significant digits to significand */ - while( z<zEnd && sqlite3Isdigit(*z) ){ - s = s*10 + (*z - '0'); - z+=incr; nDigit++; - if( s>=((LARGEST_UINT64-9)/10) ){ - /* skip non-significant significand digits - ** (increase exponent by d to shift decimal left) */ - while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; d++; } +/* +** The string z[] is an text representation of a real number. +** Convert this string to a double and write it into *pResult. +** +** z[] must be UTF-8 and zero-terminated. +** +** Return positive if the result is a valid real number (or integer) and +** zero or negative if the string is empty or contains extraneous text. +** Lower bits of the return value contain addition information about the +** parse: +** +** bit 0 => Set if any prefix of the input is valid. Clear if +** there is no prefix of the input that can be seen as +** a valid floating point number. +** bit 1 => Set if the input contains a decimal point or eNNN +** clause. Zero if the input is an integer. +** bit 2 => The input is exactly 0.0, not an underflow from +** some value near zero. +** bit 3 => Set if there are more than about 19 significant +** digits in the input. +** +** If the input contains a syntax error but begins with text that might +** be a valid number of some kind, then the result is negative. The +** result is only zero if no prefix of the input could be interpreted as +** a number. +** +** Leading and trailing whitespace is ignored. Valid numbers are in +** one of the formats below: +** +** [+-]digits[E[+-]digits] +** [+-]digits.[digits][E[+-]digits] +** [+-].digits[E[+-]digits] +** +** Algorithm sketch: Compute an unsigned 64-bit integer s and a base-10 +** exponent d such that the value encoding by the input is s*pow(10,d). +** Then invoke sqlite3Fp10Convert2() to calculated the closest possible +** IEEE754 double. The sign is added back afterwards, if the input string +** starts with a "-". The use of an unsigned 64-bit s mantissa means that +** only about the first 19 significant digits of the input can contribute +** to the result. This can result in suboptimal rounding decisions when +** correct rounding requires more than 19 input digits. For example, +** this routine renders "3500000000000000.2500001" as +** 3500000000000000.0 instead of 3500000000000000.5 because the decision +** to round up instead of using banker's rounding to round down is determined +** by the 23rd significant digit, which this routine ignores. It is not +** possible to do better without some kind of BigNum. +*/ +SQLITE_PRIVATE int sqlite3AtoF(const char *zIn, double *pResult){ +#ifndef SQLITE_OMIT_FLOATING_POINT + const unsigned char *z = (const unsigned char*)zIn; + int neg = 0; /* True for a negative value */ + u64 s = 0; /* mantissa */ + int d = 0; /* Value is s * pow(10,d) */ + int mState = 0; /* 1: digit seen 2: fp 4: hard-zero */ + unsigned v; /* Value of a single digit */ + + start_of_text: + if( (v = (unsigned)z[0] - '0')<10 ){ + parse_integer_part: + mState = 1; + s = v; + z++; + while( (v = (unsigned)z[0] - '0')<10 ){ + s = s*10 + v; + z++; + if( s>=(LARGEST_UINT64-9)/10 ){ + mState = 9; + while( sqlite3Isdigit(z[0]) ){ z++; d++; } + break; + } } + }else if( z[0]=='-' ){ + neg = 1; + z++; + if( (v = (unsigned)z[0] - '0')<10 ) goto parse_integer_part; + }else if( z[0]=='+' ){ + z++; + if( (v = (unsigned)z[0] - '0')<10 ) goto parse_integer_part; + }else if( sqlite3Isspace(z[0]) ){ + do{ z++; }while( sqlite3Isspace(z[0]) ); + goto start_of_text; + }else{ + s = 0; } - if( z>=zEnd ) goto do_atof_calc; /* if decimal point is present */ if( *z=='.' ){ - z+=incr; - eType++; - /* copy digits from after decimal to significand - ** (decrease exponent by d to shift decimal right) */ - while( z<zEnd && sqlite3Isdigit(*z) ){ - if( s<((LARGEST_UINT64-9)/10) ){ - s = s*10 + (*z - '0'); - d--; - nDigit++; - } - z+=incr; + z++; + if( sqlite3Isdigit(z[0]) ){ + mState |= 1; + do{ + if( s<(LARGEST_UINT64-9)/10 ){ + s = s*10 + z[0] - '0'; + d--; + }else{ + mState = 11; + } + }while( sqlite3Isdigit(*++z) ); + }else if( mState==0 ){ + *pResult = 0.0; + return 0; } + mState |= 2; + }else if( mState==0 ){ + *pResult = 0.0; + return 0; } - if( z>=zEnd ) goto do_atof_calc; /* if exponent is present */ if( *z=='e' || *z=='E' ){ - z+=incr; - eValid = 0; - eType++; - - /* This branch is needed to avoid a (harmless) buffer overread. The - ** special comment alerts the mutation tester that the correct answer - ** is obtained even if the branch is omitted */ - if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/ + int esign; + z++; /* get sign of exponent */ if( *z=='-' ){ esign = -1; - z+=incr; - }else if( *z=='+' ){ - z+=incr; + z++; + }else{ + esign = +1; + if( *z=='+' ){ + z++; + } } /* copy digits to exponent */ - while( z<zEnd && sqlite3Isdigit(*z) ){ - e = e<10000 ? (e*10 + (*z - '0')) : 10000; - z+=incr; - eValid = 1; + if( (v = (unsigned)z[0] - '0')<10 ){ + int exp = v; + z++; + mState |= 2; + while( (v = (unsigned)z[0] - '0')<10 ){ + exp = exp<10000 ? (exp*10 + v) : 10000; + z++; + } + d += esign*exp; + }else{ + z--; /* Leave z[0] at 'e' or '+' or '-', + ** so that the return is 0 or -1 */ } } - /* skip trailing spaces */ - while( z<zEnd && sqlite3Isspace(*z) ) z+=incr; - -do_atof_calc: - /* Zero is a special case */ + /* Convert s*pow(10,d) into real */ if( s==0 ){ - *pResult = sign<0 ? -0.0 : +0.0; - goto atof_return; - } - - /* adjust exponent by d, and update sign */ - e = (e*esign) + d; - - /* Try to adjust the exponent to make it smaller */ - while( e>0 && s<(LARGEST_UINT64/10) ){ - s *= 10; - e--; - } - while( e<0 && (s%10)==0 ){ - s /= 10; - e++; - } - - rr[0] = (double)s; - s2 = (u64)rr[0]; -#if defined(_MSC_VER) && _MSC_VER<1700 - if( s2==0x8000000000000000LL ){ s2 = 2*(u64)(0.5*rr[0]); } -#endif - rr[1] = s>=s2 ? (double)(s - s2) : -(double)(s2 - s); - if( e>0 ){ - while( e>=100 ){ - e -= 100; - dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83); - } - while( e>=10 ){ - e -= 10; - dekkerMul2(rr, 1.0e+10, 0.0); - } - while( e>=1 ){ - e -= 1; - dekkerMul2(rr, 1.0e+01, 0.0); - } + *pResult = 0.0; + mState |= 4; }else{ - while( e<=-100 ){ - e += 100; - dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117); - } - while( e<=-10 ){ - e += 10; - dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27); - } - while( e<=-1 ){ - e += 1; - dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18); - } + *pResult = sqlite3Fp10Convert2(s,d); } - *pResult = rr[0]+rr[1]; - if( sqlite3IsNaN(*pResult) ) *pResult = 1e300*1e300; - if( sign<0 ) *pResult = -*pResult; + if( neg ) *pResult = -*pResult; assert( !sqlite3IsNaN(*pResult) ); -atof_return: /* return true if number and no extra non-whitespace characters after */ - if( z==zEnd && nDigit>0 && eValid && eType>0 ){ - return eType; - }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){ - return -1; - }else{ - return 0; + if( z[0]==0 ){ + return mState; } + if( sqlite3Isspace(z[0]) ){ + do{ z++; }while( sqlite3Isspace(*z) ); + if( z[0]==0 ){ + return mState; + } + } + return 0xfffffff0 | mState; #else - return !sqlite3Atoi64(z, pResult, length, enc); + return sqlite3Atoi64(zIn, pResult, strlen(zIn), SQLITE_UTF8)==0; #endif /* SQLITE_OMIT_FLOATING_POINT */ } -#if defined(_MSC_VER) -#pragma warning(default : 4756) + +/* +** Digit pairs used to convert a U64 or I64 into text, two digits +** at a time. +*/ +static const union { + char a[201]; + short int forceAlignment; +} sqlite3DigitPairs = { + "00010203040506070809" + "10111213141516171819" + "20212223242526272829" + "30313233343536373839" + "40414243444546474849" + "50515253545556575859" + "60616263646566676869" + "70717273747576777879" + "80818283848586878889" + "90919293949596979899" +}; + +/* +** ARMv6, ARMv7, PPC32 are known to not support hardware u64 division. +*/ +#if (defined(__arm__) && !defined(__aarch64__)) || \ + (defined(__ppc__) && !defined(__ppc64__)) +# define SQLITE_AVOID_U64_DIVIDE 1 #endif +#ifdef SQLITE_AVOID_U64_DIVIDE +/* +** Render an unsigned 64-bit integer as text onto the end of a 2-byte +** aligned buffer that is SQLITE_U64_DIGIT+1 bytes long. The last byte +** of the buffer will be filled with a \000 byte. +** +** Return the index into the buffer of the first byte. +** +** This routine is used on platforms where u64-division is slow because +** it is not available in hardware and has to be emulated in software. +** It seeks to minimize the number of u64 divisions and use u32 divisions +** instead. It is slower on platforms that have hardware u64 division, +** but much faster on platforms that do not. +*/ +static int sqlite3UInt64ToText(u64 v, char *zOut){ + u32 x32, kk; + int i; + zOut[SQLITE_U64_DIGITS] = 0; + i = SQLITE_U64_DIGITS; + assert( TWO_BYTE_ALIGNMENT(&sqlite3DigitPairs.a[0]) ); + assert( TWO_BYTE_ALIGNMENT(zOut) ); + while( (v>>32)!=0 ){ + u32 y, x0, x1, y0, y1; + x32 = v % 100000000; + v = v / 100000000; + y = x32 % 10000; + x32 /= 10000; + x1 = x32 / 100; + x0 = x32 % 100; + y1 = y / 100; + y0 = y % 100; + assert( i>=8 ); + i -= 8; + *(u16*)(&zOut[i]) = *(u16*)&sqlite3DigitPairs.a[x1*2]; + *(u16*)(&zOut[i+2]) = *(u16*)&sqlite3DigitPairs.a[x0*2]; + *(u16*)(&zOut[i+4]) = *(u16*)&sqlite3DigitPairs.a[y1*2]; + *(u16*)(&zOut[i+6]) = *(u16*)&sqlite3DigitPairs.a[y0*2]; + } + x32 = v; + while( x32>=10 ){ + kk = x32 % 100; + x32 = x32 / 100; + assert( TWO_BYTE_ALIGNMENT(&sqlite3DigitPairs.a[kk*2]) ); + assert( i>=2 ); + i -= 2; + assert( TWO_BYTE_ALIGNMENT(&zOut[i]) ); + *(u16*)(&zOut[i]) = *(u16*)&sqlite3DigitPairs.a[kk*2]; + } + if( x32 ){ + assert( i>0 ); + zOut[--i] = x32 + '0'; + } + return i; +} +#endif /* defined(SQLITE_AVOID_U64_DIVIDE) */ + /* ** Render an signed 64-bit integer as text. Store the result in zOut[] and ** return the length of the string that was stored, in bytes. The value @@ -35866,23 +37923,39 @@ SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 en SQLITE_PRIVATE int sqlite3Int64ToText(i64 v, char *zOut){ int i; u64 x; - char zTemp[22]; - if( v<0 ){ - x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v; - }else{ + union { + char a[SQLITE_U64_DIGITS+1]; + u16 forceAlignment; + } u; + if( v>0 ){ x = v; + }else if( v==0 ){ + zOut[0] = '0'; + zOut[1] = 0; + return 1; + }else{ + x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v; } - i = sizeof(zTemp)-2; - zTemp[sizeof(zTemp)-1] = 0; - while( 1 /*exit-by-break*/ ){ - zTemp[i] = (x%10) + '0'; - x = x/10; - if( x==0 ) break; - i--; - }; - if( v<0 ) zTemp[--i] = '-'; - memcpy(zOut, &zTemp[i], sizeof(zTemp)-i); - return sizeof(zTemp)-1-i; +#ifdef SQLITE_AVOID_U64_DIVIDE + i = sqlite3UInt64ToText(x, u.a); +#else + i = sizeof(u.a)-1; + u.a[i] = 0; + while( x>=10 ){ + int kk = (x%100)*2; + assert( TWO_BYTE_ALIGNMENT(&sqlite3DigitPairs.a[kk]) ); + assert( TWO_BYTE_ALIGNMENT(&u.a[i-2]) ); + *(u16*)(&u.a[i-2]) = *(u16*)&sqlite3DigitPairs.a[kk]; + i -= 2; + x /= 100; + } + if( x ){ + u.a[--i] = x + '0'; + } +#endif /* SQLITE_AVOID_U64_DIVIDE */ + if( v<0 ) u.a[--i] = '-'; + memcpy(zOut, &u.a[i], sizeof(u.a)-i); + return sizeof(u.a)-1-i; } /* @@ -35936,8 +38009,8 @@ SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc int incr; u64 u = 0; int neg = 0; /* assume positive */ - int i; - int c = 0; + int i, j; + unsigned int c = 0; int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */ int rc; /* Baseline return code */ const char *zStart; @@ -35965,8 +38038,8 @@ SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc } zStart = zNum; while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */ - for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){ - u = u*10 + c - '0'; + for(i=0; &zNum[i]<zEnd && (c=(unsigned)zNum[i]-'0')<=9; i+=incr){ + u = u*10 + c; } testcase( i==18*incr ); testcase( i==19*incr ); @@ -36003,14 +38076,14 @@ SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc return rc; }else{ /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */ - c = i>19*incr ? 1 : compare2pow63(zNum, incr); - if( c<0 ){ + j = i>19*incr ? 1 : compare2pow63(zNum, incr); + if( j<0 ){ /* zNum is less than 9223372036854775808 so it fits */ assert( u<=LARGEST_INT64 ); return rc; }else{ *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64; - if( c>0 ){ + if( j>0 ){ /* zNum is greater than 9223372036854775808 so it overflows */ return 2; }else{ @@ -36139,7 +38212,7 @@ SQLITE_PRIVATE int sqlite3Atoi(const char *z){ ** representation. ** ** If iRound<=0 then round to -iRound significant digits to the -** the left of the decimal point, or to a maximum of mxRound total +** the right of the decimal point, or to a maximum of mxRound total ** significant digits. ** ** If iRound>0 round to min(iRound,mxRound) significant digits total. @@ -36152,13 +38225,14 @@ SQLITE_PRIVATE int sqlite3Atoi(const char *z){ ** The p->z[] array is *not* zero-terminated. */ SQLITE_PRIVATE void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRound){ - int i; - u64 v; - int e, exp = 0; - double rr[2]; + int i; /* Index into zBuf[] where to put next character */ + int n; /* Number of digits */ + u64 v; /* mantissa */ + int e, exp = 0; /* Base-2 and base-10 exponent */ + char *zBuf; /* Local alias for p->zBuf */ + char *z; /* Local alias for p->z */ p->isSpecial = 0; - p->z = p->zBuf; assert( mxRound>0 ); /* Convert negative numbers to positive. Deal with Infinity, 0.0, and @@ -36176,78 +38250,100 @@ SQLITE_PRIVATE void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRou p->sign = '+'; } memcpy(&v,&r,8); - e = v>>52; - if( (e&0x7ff)==0x7ff ){ + e = (v>>52)&0x7ff; + if( e==0x7ff ){ p->isSpecial = 1 + (v!=0x7ff0000000000000LL); p->n = 0; p->iDP = 0; + p->z = p->zBuf; return; } - - /* Multiply r by powers of ten until it lands somewhere in between - ** 1.0e+19 and 1.0e+17. - ** - ** Use Dekker-style double-double computation to increase the - ** precision. - ** - ** The error terms on constants like 1.0e+100 computed using the - ** decimal extension, for example as follows: - ** - ** SELECT decimal_exp(decimal_sub('1.0e+100',decimal(1.0e+100))); - */ - rr[0] = r; - rr[1] = 0.0; - if( rr[0]>9.223372036854774784e+18 ){ - while( rr[0]>9.223372036854774784e+118 ){ - exp += 100; - dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117); - } - while( rr[0]>9.223372036854774784e+28 ){ - exp += 10; - dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27); - } - while( rr[0]>9.223372036854774784e+18 ){ - exp += 1; - dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18); - } + v &= 0x000fffffffffffffULL; + if( e==0 ){ + int nn = countLeadingZeros(v); + v <<= nn; + e = -1074 - nn; }else{ - while( rr[0]<9.223372036854774784e-83 ){ - exp -= 100; - dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83); - } - while( rr[0]<9.223372036854774784e+07 ){ - exp -= 10; - dekkerMul2(rr, 1.0e+10, 0.0); - } - while( rr[0]<9.22337203685477478e+17 ){ - exp -= 1; - dekkerMul2(rr, 1.0e+01, 0.0); - } + v = (v<<11) | U64_BIT(63); + e -= 1086; } - v = rr[1]<0.0 ? (u64)rr[0]-(u64)(-rr[1]) : (u64)rr[0]+(u64)rr[1]; + sqlite3Fp2Convert10(v, e, (iRound<=0||iRound>=18)?18:iRound+1, &v, &exp); - /* Extract significant digits. */ - i = sizeof(p->zBuf)-1; + /* Extract significant digits, start at the right-most slot in p->zBuf + ** and working back to the right. "i" keeps track of the next slot in + ** which to store a digit. */ + assert( sizeof(p->zBuf)==SQLITE_U64_DIGITS+1 ); assert( v>0 ); - while( v ){ p->zBuf[i--] = (v%10) + '0'; v /= 10; } - assert( i>=0 && i<sizeof(p->zBuf)-1 ); - p->n = sizeof(p->zBuf) - 1 - i; - assert( p->n>0 ); - assert( p->n<sizeof(p->zBuf) ); - p->iDP = p->n + exp; + zBuf = p->zBuf; +#ifdef SQLITE_AVOID_U64_DIVIDE + i = sqlite3UInt64ToText(v, zBuf); +#else + i = SQLITE_U64_DIGITS; + while( v>=10 ){ + int kk = (v%100)*2; + assert( TWO_BYTE_ALIGNMENT(&sqlite3DigitPairs.a[kk]) ); + assert( TWO_BYTE_ALIGNMENT(&zBuf[i]) ); + assert( i-2>=0 ); + *(u16*)(&zBuf[i-2]) = *(u16*)&sqlite3DigitPairs.a[kk]; + i -= 2; + v /= 100; + } + if( v ){ + assert( v<10 ); + assert( i>0 ); + zBuf[--i] = v + '0'; + } +#endif /* SQLITE_AVOID_U64_DIVIDE */ + assert( i>=0 && i<SQLITE_U64_DIGITS ); + n = SQLITE_U64_DIGITS - i; /* Total number of digits extracted */ + assert( n>0 ); + assert( n<=SQLITE_U64_DIGITS ); + p->iDP = n + exp; if( iRound<=0 ){ iRound = p->iDP - iRound; - if( iRound==0 && p->zBuf[i+1]>='5' ){ + if( iRound==0 && zBuf[i]>='5' ){ iRound = 1; - p->zBuf[i--] = '0'; - p->n++; + zBuf[--i] = '0'; + n++; p->iDP++; } } - if( iRound>0 && (iRound<p->n || p->n>mxRound) ){ - char *z = &p->zBuf[i+1]; + z = &zBuf[i]; /* z points to the first digit */ + if( iRound>0 && (iRound<n || n>mxRound) ){ if( iRound>mxRound ) iRound = mxRound; - p->n = iRound; + if( iRound==17 ){ + /* If the precision is exactly 17, which only happens with the "!" + ** flag (ex: "%!.17g") then try to reduce the precision if that + ** yields text that will round-trip to the original floating-point. + ** value. Thus, for exaple, 49.47 will render as 49.47, rather than + ** as 49.469999999999999. */ + if( z[15]=='9' && z[14]=='9' ){ + int jj, kk; + u64 v2; + for(jj=14; jj>0 && z[jj-1]=='9'; jj--){} + if( jj==0 ){ + v2 = 1; + }else{ + v2 = z[0] - '0'; + for(kk=1; kk<jj; kk++) v2 = (v2*10) + z[kk] - '0'; + v2++; + } + if( r==sqlite3Fp10Convert2(v2, exp + n - jj) ){ + iRound = jj+1; + } + }else if( p->iDP>=n || (z[15]=='0' && z[14]=='0' && z[13]=='0') ){ + int jj, kk; + u64 v2; + assert( z[0]!='0' ); + for(jj=13; z[jj-1]=='0'; jj--){} + v2 = z[0] - '0'; + for(kk=1; kk<jj; kk++) v2 = (v2*10) + z[kk] - '0'; + if( r==sqlite3Fp10Convert2(v2, exp + n - jj) ){ + iRound = jj+1; + } + } + } + n = iRound; if( z[iRound]>='5' ){ int j = iRound-1; while( 1 /*exit-by-break*/ ){ @@ -36255,8 +38351,9 @@ SQLITE_PRIVATE void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRou if( z[j]<='9' ) break; z[j] = '0'; if( j==0 ){ - p->z[i--] = '1'; - p->n++; + z--; + z[0] = '1'; + n++; p->iDP++; break; }else{ @@ -36265,9 +38362,13 @@ SQLITE_PRIVATE void sqlite3FpDecode(FpDecode *p, double r, int iRound, int mxRou } } } - p->z = &p->zBuf[i+1]; - assert( i+p->n < sizeof(p->zBuf) ); - while( ALWAYS(p->n>0) && p->z[p->n-1]=='0' ){ p->n--; } + assert( n>0 ); + while( z[n-1]=='0' ){ + n--; + assert( n>0 ); + } + p->n = n; + p->z = z; } /* @@ -36281,7 +38382,7 @@ SQLITE_PRIVATE int sqlite3GetUInt32(const char *z, u32 *pI){ int i; for(i=0; sqlite3Isdigit(z[i]); i++){ v = v*10 + z[i] - '0'; - if( v>4294967296LL ){ *pI = 0; return 0; } + if( v>4294967295LL ){ *pI = 0; return 0; } } if( i==0 || z[i]!=0 ){ *pI = 0; return 0; } *pI = (u32)v; @@ -36354,171 +38455,83 @@ SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){ return putVarint64(p,v); } -/* -** Bitmasks used by sqlite3GetVarint(). These precomputed constants -** are defined here rather than simply putting the constant expressions -** inline in order to work around bugs in the RVT compiler. -** -** SLOT_2_0 A mask for (0x7f<<14) | 0x7f -** -** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0 -*/ -#define SLOT_2_0 0x001fc07f -#define SLOT_4_2_0 0xf01fc07f - - /* ** Read a 64-bit variable-length integer from memory starting at p[0]. ** Return the number of bytes read. The value is stored in *v. */ SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){ - u32 a,b,s; - - if( ((signed char*)p)[0]>=0 ){ - *v = *p; - return 1; - } - if( ((signed char*)p)[1]>=0 ){ - *v = ((u32)(p[0]&0x7f)<<7) | p[1]; - return 2; - } - - /* Verify that constants are precomputed correctly */ - assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) ); - assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) ); - - a = ((u32)p[0])<<14; - b = p[1]; - p += 2; - a |= *p; - /* a: p0<<14 | p2 (unmasked) */ - if (!(a&0x80)) - { - a &= SLOT_2_0; - b &= 0x7f; - b = b<<7; - a |= b; - *v = a; - return 3; - } - - /* CSE1 from below */ - a &= SLOT_2_0; - p++; - b = b<<14; - b |= *p; - /* b: p1<<14 | p3 (unmasked) */ - if (!(b&0x80)) - { - b &= SLOT_2_0; - /* moved CSE1 up */ - /* a &= (0x7f<<14)|(0x7f); */ - a = a<<7; - a |= b; - *v = a; - return 4; - } - - /* a: p0<<14 | p2 (masked) */ - /* b: p1<<14 | p3 (unmasked) */ - /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ - /* moved CSE1 up */ - /* a &= (0x7f<<14)|(0x7f); */ - b &= SLOT_2_0; - s = a; - /* s: p0<<14 | p2 (masked) */ - - p++; - a = a<<14; - a |= *p; - /* a: p0<<28 | p2<<14 | p4 (unmasked) */ - if (!(a&0x80)) - { - /* we can skip these cause they were (effectively) done above - ** while calculating s */ - /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ - /* b &= (0x7f<<14)|(0x7f); */ - b = b<<7; - a |= b; - s = s>>18; - *v = ((u64)s)<<32 | a; - return 5; - } - - /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ - s = s<<7; - s |= b; - /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ - - p++; - b = b<<14; - b |= *p; - /* b: p1<<28 | p3<<14 | p5 (unmasked) */ - if (!(b&0x80)) - { - /* we can skip this cause it was (effectively) done above in calc'ing s */ - /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ - a &= SLOT_2_0; - a = a<<7; - a |= b; - s = s>>18; - *v = ((u64)s)<<32 | a; - return 6; - } - - p++; - a = a<<14; - a |= *p; - /* a: p2<<28 | p4<<14 | p6 (unmasked) */ - if (!(a&0x80)) - { - a &= SLOT_4_2_0; - b &= SLOT_2_0; - b = b<<7; - a |= b; - s = s>>11; - *v = ((u64)s)<<32 | a; - return 7; + u64 iKey = p[0]; + const u8 *pStart = p; + if( iKey>=0x80 ){ + u8 x; + iKey = (iKey<<7) ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<7) ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<7) ^ 0x10204000 ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<7) ^ 0x4000 ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<7) ^ 0x4000 ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<7) ^ 0x4000 ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<7) ^ 0x4000 ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<8) ^ 0x8000 ^ (*++p); + } + } + } + } + } + }else{ + iKey ^= 0x204000; + } + }else{ + iKey ^= 0x4000; + } } + *v = iKey; + return (u8)(p - pStart) + 1; +} - /* CSE2 from below */ - a &= SLOT_2_0; - p++; - b = b<<14; - b |= *p; - /* b: p3<<28 | p5<<14 | p7 (unmasked) */ - if (!(b&0x80)) - { - b &= SLOT_4_2_0; - /* moved CSE2 up */ - /* a &= (0x7f<<14)|(0x7f); */ - a = a<<7; - a |= b; - s = s>>4; - *v = ((u64)s)<<32 | a; - return 8; +/* +** Return the value of a variable-length integer without computing +** its length. This is an optimization on sqlite3GetVarint() for the +** cases when the return value of sqlite3GetVarint() is not needed. +*/ +SQLITE_PRIVATE i64 sqlite3VarintValue(const unsigned char *p){ + u64 iKey = p[0]; + if( iKey>=0x80 ){ + u8 x; + iKey = (iKey<<7) ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<7) ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<7) ^ 0x10204000 ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<7) ^ 0x4000 ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<7) ^ 0x4000 ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<7) ^ 0x4000 ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<7) ^ 0x4000 ^ (x = *++p); + if( x>=0x80 ){ + iKey = (iKey<<8) ^ 0x8000 ^ (*++p); + } + } + } + } + } + }else{ + iKey ^= 0x204000; + } + }else{ + iKey ^= 0x4000; + } } - - p++; - a = a<<15; - a |= *p; - /* a: p4<<29 | p6<<15 | p8 (unmasked) */ - - /* moved CSE2 up */ - /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */ - b &= SLOT_2_0; - b = b<<8; - a |= b; - - s = s<<4; - b = p[-4]; - b &= 0x7f; - b = b>>3; - s |= b; - - *v = ((u64)s)<<32 | a; - - return 9; + return *(i64*)&iKey; } /* @@ -36573,7 +38586,7 @@ SQLITE_PRIVATE int sqlite3VarintLen(u64 v){ /* -** Read or write a four-byte big-endian integer value. +** Read an unsigned 32-bit integer from an unaligned big-endian array of bytes. */ SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){ #if SQLITE_BYTEORDER==4321 @@ -36589,10 +38602,14 @@ SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){ memcpy(&x,p,4); return _byteswap_ulong(x); #else + /* Test this limb using -DSQLITE_BYTEORDER=0 */ testcase( p[0]&0x80 ); return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3]; #endif } + +/* Write an unsigned 32-bit integer into an unaligned big-endian array of bytes. +*/ SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){ #if SQLITE_BYTEORDER==4321 memcpy(p,&v,4); @@ -36603,6 +38620,7 @@ SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){ u32 x = _byteswap_ulong(v); memcpy(p,&x,4); #else + /* Test this limb using -DSQLITE_BYTEORDER=0 */ p[0] = (u8)(v>>24); p[1] = (u8)(v>>16); p[2] = (u8)(v>>8); @@ -36610,7 +38628,58 @@ SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){ #endif } +/* +** Read an unsigned 64-bit integer from an unaligned big-endian byte array. +*/ +SQLITE_PRIVATE SQLITE_OPT_INLINE u64 sqlite3Get8byte(const u8 *p){ +#if SQLITE_BYTEORDER==4321 + u64 x; + memcpy(&x,p,8); + return x; +#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 + u64 x; + memcpy(&x,p,8); + return __builtin_bswap64(x); +#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 + u64 x; + memcpy(&x,p,8); + return _byteswap_uint64(x); +#else + /* Test this limb using -DSQLITE_BYTEORDER=0 */ + testcase( p[0]&0x80 ); + return (u64)( + (((u64)p[0]) << 56) + + (((u64)p[1]) << 48) + + (((u64)p[2]) << 40) + + (((u64)p[3]) << 32) + + (((u64)p[4]) << 24) + + (((u64)p[5]) << 16) + + (((u64)p[6]) << 8) + + (((u64)p[7]) << 0) + ); +#endif +} +#if SQLITE_BYTEORDER!=4321 /* Only used for little-endian machines */ +/* +** Byte-swap a 64-bit unsigned integer. +*/ +SQLITE_PRIVATE SQLITE_OPT_INLINE u64 sqlite3BSwap64(u64 x){ +#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 + return __builtin_bswap64(x); +#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 + return _byteswap_uint64(x); +#else + /* Test this limb using -DSQLITE_BYTEORDER=0 */ + x = (x << 32) | (x >> 32); + x = ((x & UINT64_C(0x0000ffff0000ffff)) << 16) | + ((x & UINT64_C(0xffff0000ffff0000)) >> 16); + x = ((x & UINT64_C(0x00ff00ff00ff00ff)) << 8) | + ((x & UINT64_C(0xff00ff00ff00ff00)) >> 8); + return x; +#endif +} +#endif /* SQLITE_BYTEORDER!=4321 */ /* ** Translate a single byte of Hex into an integer. @@ -36772,7 +38841,7 @@ SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){ } /* -** Compute the absolute value of a 32-bit signed integer, of possible. Or +** Compute the absolute value of a 32-bit signed integer, if possible. Or ** if the integer has a value of -2147483648, return +2147483647 */ SQLITE_PRIVATE int sqlite3AbsInt32(int x){ @@ -37053,12 +39122,19 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){ */ static unsigned int strHash(const char *z){ unsigned int h = 0; - unsigned char c; - while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/ + while( z[0] ){ /*OPTIMIZATION-IF-TRUE*/ /* Knuth multiplicative hashing. (Sorting & Searching, p. 510). ** 0x9e3779b1 is 2654435761 which is the closest prime number to - ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */ - h += sqlite3UpperToLower[c]; + ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. + ** + ** Only bits 0xdf for ASCII and bits 0xbf for EBCDIC each octet are + ** hashed since the omitted bits determine the upper/lower case difference. + */ +#ifdef SQLITE_EBCDIC + h += 0xbf & (unsigned char)*(z++); +#else + h += 0xdf & (unsigned char)*(z++); +#endif h *= 0x9e3779b1; } return h; @@ -37131,9 +39207,8 @@ static int rehash(Hash *pH, unsigned int new_size){ pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht); memset(new_ht, 0, new_size*sizeof(struct _ht)); for(elem=pH->first, pH->first=0; elem; elem = next_elem){ - unsigned int h = strHash(elem->pKey) % new_size; next_elem = elem->next; - insertElement(pH, &new_ht[h], elem); + insertElement(pH, &new_ht[elem->h % new_size], elem); } return 1; } @@ -37151,23 +39226,22 @@ static HashElem *findElementWithHash( HashElem *elem; /* Used to loop thru the element list */ unsigned int count; /* Number of elements left to test */ unsigned int h; /* The computed hash */ - static HashElem nullElement = { 0, 0, 0, 0 }; + static HashElem nullElement = { 0, 0, 0, 0, 0 }; + h = strHash(pKey); if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/ struct _ht *pEntry; - h = strHash(pKey) % pH->htsize; - pEntry = &pH->ht[h]; + pEntry = &pH->ht[h % pH->htsize]; elem = pEntry->chain; count = pEntry->count; }else{ - h = 0; elem = pH->first; count = pH->count; } if( pHash ) *pHash = h; while( count ){ assert( elem!=0 ); - if( sqlite3StrICmp(elem->pKey,pKey)==0 ){ + if( h==elem->h && sqlite3StrICmp(elem->pKey,pKey)==0 ){ return elem; } elem = elem->next; @@ -37179,10 +39253,9 @@ static HashElem *findElementWithHash( /* Remove a single entry from the hash table given a pointer to that ** element and a hash on the element's key. */ -static void removeElementGivenHash( +static void removeElement( Hash *pH, /* The pH containing "elem" */ - HashElem* elem, /* The element to be removed from the pH */ - unsigned int h /* Hash value for the element */ + HashElem *elem /* The element to be removed from the pH */ ){ struct _ht *pEntry; if( elem->prev ){ @@ -37194,7 +39267,7 @@ static void removeElementGivenHash( elem->next->prev = elem->prev; } if( pH->ht ){ - pEntry = &pH->ht[h]; + pEntry = &pH->ht[elem->h % pH->htsize]; if( pEntry->chain==elem ){ pEntry->chain = elem->next; } @@ -37245,7 +39318,7 @@ SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){ if( elem->data ){ void *old_data = elem->data; if( data==0 ){ - removeElementGivenHash(pH,elem,h); + removeElement(pH,elem); }else{ elem->data = data; elem->pKey = pKey; @@ -37256,18 +39329,17 @@ SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){ new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) ); if( new_elem==0 ) return data; new_elem->pKey = pKey; + new_elem->h = h; new_elem->data = data; pH->count++; - if( pH->count>=10 && pH->count > 2*pH->htsize ){ - if( rehash(pH, pH->count*2) ){ - assert( pH->htsize>0 ); - h = strHash(pKey) % pH->htsize; - } + if( pH->count>=5 && pH->count > 2*pH->htsize ){ + rehash(pH, pH->count*3); } - insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem); + insertElement(pH, pH->ht ? &pH->ht[new_elem->h % pH->htsize] : 0, new_elem); return 0; } + /************** End of hash.c ************************************************/ /************** Begin file opcodes.c *****************************************/ /* Automatically generated. Do not edit */ @@ -37307,18 +39379,18 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ /* 22 */ "SeekLE" OpHelp("key=r[P3@P4]"), /* 23 */ "SeekGE" OpHelp("key=r[P3@P4]"), /* 24 */ "SeekGT" OpHelp("key=r[P3@P4]"), - /* 25 */ "IfNotOpen" OpHelp("if( !csr[P1] ) goto P2"), - /* 26 */ "IfNoHope" OpHelp("key=r[P3@P4]"), - /* 27 */ "NoConflict" OpHelp("key=r[P3@P4]"), - /* 28 */ "NotFound" OpHelp("key=r[P3@P4]"), - /* 29 */ "Found" OpHelp("key=r[P3@P4]"), - /* 30 */ "SeekRowid" OpHelp("intkey=r[P3]"), - /* 31 */ "NotExists" OpHelp("intkey=r[P3]"), - /* 32 */ "Last" OpHelp(""), - /* 33 */ "IfSizeBetween" OpHelp(""), - /* 34 */ "SorterSort" OpHelp(""), - /* 35 */ "Sort" OpHelp(""), - /* 36 */ "Rewind" OpHelp(""), + /* 25 */ "IfNoHope" OpHelp("key=r[P3@P4]"), + /* 26 */ "NoConflict" OpHelp("key=r[P3@P4]"), + /* 27 */ "NotFound" OpHelp("key=r[P3@P4]"), + /* 28 */ "Found" OpHelp("key=r[P3@P4]"), + /* 29 */ "SeekRowid" OpHelp("intkey=r[P3]"), + /* 30 */ "NotExists" OpHelp("intkey=r[P3]"), + /* 31 */ "Last" OpHelp(""), + /* 32 */ "IfSizeBetween" OpHelp(""), + /* 33 */ "SorterSort" OpHelp(""), + /* 34 */ "Sort" OpHelp(""), + /* 35 */ "Rewind" OpHelp(""), + /* 36 */ "IfEmpty" OpHelp("if( empty(P1) ) goto P2"), /* 37 */ "SorterNext" OpHelp(""), /* 38 */ "Prev" OpHelp(""), /* 39 */ "Next" OpHelp(""), @@ -37328,11 +39400,11 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"), /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"), /* 45 */ "IdxGE" OpHelp("key=r[P3@P4]"), - /* 46 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"), - /* 47 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"), - /* 48 */ "Program" OpHelp(""), - /* 49 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"), - /* 50 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"), + /* 46 */ "IFindKey" OpHelp(""), + /* 47 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"), + /* 48 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"), + /* 49 */ "Program" OpHelp(""), + /* 50 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"), /* 51 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"), /* 52 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"), /* 53 */ "Ne" OpHelp("IF r[P3]!=r[P1]"), @@ -37342,49 +39414,49 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ /* 57 */ "Lt" OpHelp("IF r[P3]<r[P1]"), /* 58 */ "Ge" OpHelp("IF r[P3]>=r[P1]"), /* 59 */ "ElseEq" OpHelp(""), - /* 60 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"), - /* 61 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"), - /* 62 */ "IncrVacuum" OpHelp(""), - /* 63 */ "VNext" OpHelp(""), - /* 64 */ "Filter" OpHelp("if key(P3@P4) not in filter(P1) goto P2"), - /* 65 */ "PureFunc" OpHelp("r[P3]=func(r[P2@NP])"), - /* 66 */ "Function" OpHelp("r[P3]=func(r[P2@NP])"), - /* 67 */ "Return" OpHelp(""), - /* 68 */ "EndCoroutine" OpHelp(""), - /* 69 */ "HaltIfNull" OpHelp("if r[P3]=null halt"), - /* 70 */ "Halt" OpHelp(""), - /* 71 */ "Integer" OpHelp("r[P2]=P1"), - /* 72 */ "Int64" OpHelp("r[P2]=P4"), - /* 73 */ "String" OpHelp("r[P2]='P4' (len=P1)"), - /* 74 */ "BeginSubrtn" OpHelp("r[P2]=NULL"), - /* 75 */ "Null" OpHelp("r[P2..P3]=NULL"), - /* 76 */ "SoftNull" OpHelp("r[P1]=NULL"), - /* 77 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"), - /* 78 */ "Variable" OpHelp("r[P2]=parameter(P1)"), - /* 79 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"), - /* 80 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"), - /* 81 */ "SCopy" OpHelp("r[P2]=r[P1]"), - /* 82 */ "IntCopy" OpHelp("r[P2]=r[P1]"), - /* 83 */ "FkCheck" OpHelp(""), - /* 84 */ "ResultRow" OpHelp("output=r[P1@P2]"), - /* 85 */ "CollSeq" OpHelp(""), - /* 86 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"), - /* 87 */ "RealAffinity" OpHelp(""), - /* 88 */ "Cast" OpHelp("affinity(r[P1])"), - /* 89 */ "Permutation" OpHelp(""), - /* 90 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"), - /* 91 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"), - /* 92 */ "ZeroOrNull" OpHelp("r[P2] = 0 OR NULL"), - /* 93 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"), - /* 94 */ "Column" OpHelp("r[P3]=PX cursor P1 column P2"), - /* 95 */ "TypeCheck" OpHelp("typecheck(r[P1@P2])"), - /* 96 */ "Affinity" OpHelp("affinity(r[P1@P2])"), - /* 97 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"), - /* 98 */ "Count" OpHelp("r[P2]=count()"), - /* 99 */ "ReadCookie" OpHelp(""), - /* 100 */ "SetCookie" OpHelp(""), - /* 101 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"), - /* 102 */ "OpenRead" OpHelp("root=P2 iDb=P3"), + /* 60 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"), + /* 61 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"), + /* 62 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"), + /* 63 */ "IncrVacuum" OpHelp(""), + /* 64 */ "VNext" OpHelp(""), + /* 65 */ "Filter" OpHelp("if key(P3@P4) not in filter(P1) goto P2"), + /* 66 */ "PureFunc" OpHelp("r[P3]=func(r[P2@NP])"), + /* 67 */ "Function" OpHelp("r[P3]=func(r[P2@NP])"), + /* 68 */ "Return" OpHelp(""), + /* 69 */ "EndCoroutine" OpHelp(""), + /* 70 */ "HaltIfNull" OpHelp("if r[P3]=null halt"), + /* 71 */ "Halt" OpHelp(""), + /* 72 */ "Integer" OpHelp("r[P2]=P1"), + /* 73 */ "Int64" OpHelp("r[P2]=PINT13"), + /* 74 */ "String" OpHelp("r[P2]='P4' (len=P1)"), + /* 75 */ "BeginSubrtn" OpHelp("r[P2]=NULL"), + /* 76 */ "Null" OpHelp("r[P2..P3]=NULL"), + /* 77 */ "SoftNull" OpHelp("r[P1]=NULL"), + /* 78 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"), + /* 79 */ "Variable" OpHelp("r[P2]=parameter(P1)"), + /* 80 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"), + /* 81 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"), + /* 82 */ "SCopy" OpHelp("r[P2]=r[P1]"), + /* 83 */ "IntCopy" OpHelp("r[P2]=r[P1]"), + /* 84 */ "FkCheck" OpHelp(""), + /* 85 */ "ResultRow" OpHelp("output=r[P1@P2]"), + /* 86 */ "CollSeq" OpHelp(""), + /* 87 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"), + /* 88 */ "RealAffinity" OpHelp(""), + /* 89 */ "Cast" OpHelp("affinity(r[P1])"), + /* 90 */ "Permutation" OpHelp(""), + /* 91 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"), + /* 92 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"), + /* 93 */ "ZeroOrNull" OpHelp("r[P2] = 0 OR NULL"), + /* 94 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"), + /* 95 */ "Column" OpHelp("r[P3]=PX cursor P1 column P2"), + /* 96 */ "TypeCheck" OpHelp("typecheck(r[P1@P2])"), + /* 97 */ "Affinity" OpHelp("affinity(r[P1@P2])"), + /* 98 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"), + /* 99 */ "Count" OpHelp("r[P2]=count()"), + /* 100 */ "ReadCookie" OpHelp(""), + /* 101 */ "SetCookie" OpHelp(""), + /* 102 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"), /* 103 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"), /* 104 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"), /* 105 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"), @@ -37395,83 +39467,84 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ /* 110 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"), /* 111 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"), /* 112 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"), - /* 113 */ "OpenWrite" OpHelp("root=P2 iDb=P3"), - /* 114 */ "OpenDup" OpHelp(""), + /* 113 */ "OpenRead" OpHelp("root=P2 iDb=P3"), + /* 114 */ "OpenWrite" OpHelp("root=P2 iDb=P3"), /* 115 */ "BitNot" OpHelp("r[P2]= ~r[P1]"), - /* 116 */ "OpenAutoindex" OpHelp("nColumn=P2"), - /* 117 */ "OpenEphemeral" OpHelp("nColumn=P2"), + /* 116 */ "OpenDup" OpHelp(""), + /* 117 */ "OpenAutoindex" OpHelp("nColumn=P2"), /* 118 */ "String8" OpHelp("r[P2]='P4'"), - /* 119 */ "SorterOpen" OpHelp(""), - /* 120 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"), - /* 121 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"), - /* 122 */ "Close" OpHelp(""), - /* 123 */ "ColumnsUsed" OpHelp(""), - /* 124 */ "SeekScan" OpHelp("Scan-ahead up to P1 rows"), - /* 125 */ "SeekHit" OpHelp("set P2<=seekHit<=P3"), - /* 126 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"), - /* 127 */ "NewRowid" OpHelp("r[P2]=rowid"), - /* 128 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"), - /* 129 */ "RowCell" OpHelp(""), - /* 130 */ "Delete" OpHelp(""), - /* 131 */ "ResetCount" OpHelp(""), - /* 132 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"), - /* 133 */ "SorterData" OpHelp("r[P2]=data"), - /* 134 */ "RowData" OpHelp("r[P2]=data"), - /* 135 */ "Rowid" OpHelp("r[P2]=PX rowid of P1"), - /* 136 */ "NullRow" OpHelp(""), - /* 137 */ "SeekEnd" OpHelp(""), - /* 138 */ "IdxInsert" OpHelp("key=r[P2]"), - /* 139 */ "SorterInsert" OpHelp("key=r[P2]"), - /* 140 */ "IdxDelete" OpHelp("key=r[P2@P3]"), - /* 141 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"), - /* 142 */ "IdxRowid" OpHelp("r[P2]=rowid"), - /* 143 */ "FinishSeek" OpHelp(""), - /* 144 */ "Destroy" OpHelp(""), - /* 145 */ "Clear" OpHelp(""), - /* 146 */ "ResetSorter" OpHelp(""), - /* 147 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"), - /* 148 */ "SqlExec" OpHelp(""), - /* 149 */ "ParseSchema" OpHelp(""), - /* 150 */ "LoadAnalysis" OpHelp(""), - /* 151 */ "DropTable" OpHelp(""), - /* 152 */ "DropIndex" OpHelp(""), - /* 153 */ "DropTrigger" OpHelp(""), - /* 154 */ "Real" OpHelp("r[P2]=P4"), - /* 155 */ "IntegrityCk" OpHelp(""), - /* 156 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"), - /* 157 */ "Param" OpHelp(""), - /* 158 */ "FkCounter" OpHelp("fkctr[P1]+=P2"), - /* 159 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"), - /* 160 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"), - /* 161 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"), - /* 162 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"), - /* 163 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"), - /* 164 */ "AggValue" OpHelp("r[P3]=value N=P2"), - /* 165 */ "AggFinal" OpHelp("accum=r[P1] N=P2"), - /* 166 */ "Expire" OpHelp(""), - /* 167 */ "CursorLock" OpHelp(""), - /* 168 */ "CursorUnlock" OpHelp(""), - /* 169 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"), - /* 170 */ "VBegin" OpHelp(""), - /* 171 */ "VCreate" OpHelp(""), - /* 172 */ "VDestroy" OpHelp(""), - /* 173 */ "VOpen" OpHelp(""), - /* 174 */ "VCheck" OpHelp(""), - /* 175 */ "VInitIn" OpHelp("r[P2]=ValueList(P1,P3)"), - /* 176 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"), - /* 177 */ "VRename" OpHelp(""), - /* 178 */ "Pagecount" OpHelp(""), - /* 179 */ "MaxPgcnt" OpHelp(""), - /* 180 */ "ClrSubtype" OpHelp("r[P1].subtype = 0"), - /* 181 */ "GetSubtype" OpHelp("r[P2] = r[P1].subtype"), - /* 182 */ "SetSubtype" OpHelp("r[P2].subtype = r[P1]"), - /* 183 */ "FilterAdd" OpHelp("filter(P1) += key(P3@P4)"), - /* 184 */ "Trace" OpHelp(""), - /* 185 */ "CursorHint" OpHelp(""), - /* 186 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"), - /* 187 */ "Noop" OpHelp(""), - /* 188 */ "Explain" OpHelp(""), - /* 189 */ "Abortable" OpHelp(""), + /* 119 */ "OpenEphemeral" OpHelp("nColumn=P2"), + /* 120 */ "SorterOpen" OpHelp(""), + /* 121 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"), + /* 122 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"), + /* 123 */ "Close" OpHelp(""), + /* 124 */ "ColumnsUsed" OpHelp("Cursor P1 uses columns PHEX23"), + /* 125 */ "SeekScan" OpHelp("Scan-ahead up to P1 rows"), + /* 126 */ "SeekHit" OpHelp("set P2<=seekHit<=P3"), + /* 127 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"), + /* 128 */ "NewRowid" OpHelp("r[P2]=rowid"), + /* 129 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"), + /* 130 */ "RowCell" OpHelp(""), + /* 131 */ "Delete" OpHelp(""), + /* 132 */ "ResetCount" OpHelp(""), + /* 133 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"), + /* 134 */ "SorterData" OpHelp("r[P2]=data"), + /* 135 */ "RowData" OpHelp("r[P2]=data"), + /* 136 */ "Rowid" OpHelp("r[P2]=PX rowid of P1"), + /* 137 */ "NullRow" OpHelp(""), + /* 138 */ "SeekEnd" OpHelp(""), + /* 139 */ "IdxInsert" OpHelp("key=r[P2]"), + /* 140 */ "SorterInsert" OpHelp("key=r[P2]"), + /* 141 */ "IdxDelete" OpHelp("key=r[P2@P5]"), + /* 142 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"), + /* 143 */ "IdxRowid" OpHelp("r[P2]=rowid"), + /* 144 */ "FinishSeek" OpHelp(""), + /* 145 */ "Destroy" OpHelp(""), + /* 146 */ "Clear" OpHelp(""), + /* 147 */ "ResetSorter" OpHelp(""), + /* 148 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"), + /* 149 */ "SqlExec" OpHelp(""), + /* 150 */ "ParseSchema" OpHelp(""), + /* 151 */ "LoadAnalysis" OpHelp(""), + /* 152 */ "DropTable" OpHelp(""), + /* 153 */ "DropIndex" OpHelp(""), + /* 154 */ "Real" OpHelp("r[P2]=PDBL13"), + /* 155 */ "DropTrigger" OpHelp(""), + /* 156 */ "IntegrityCk" OpHelp(""), + /* 157 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"), + /* 158 */ "Param" OpHelp(""), + /* 159 */ "FkCounter" OpHelp("fkctr[P1]+=P2"), + /* 160 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"), + /* 161 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"), + /* 162 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"), + /* 163 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"), + /* 164 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"), + /* 165 */ "AggValue" OpHelp("r[P3]=value N=P2"), + /* 166 */ "AggFinal" OpHelp("accum=r[P1] N=P2"), + /* 167 */ "Expire" OpHelp(""), + /* 168 */ "CursorLock" OpHelp(""), + /* 169 */ "CursorUnlock" OpHelp(""), + /* 170 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"), + /* 171 */ "VBegin" OpHelp(""), + /* 172 */ "VCreate" OpHelp(""), + /* 173 */ "VDestroy" OpHelp(""), + /* 174 */ "VOpen" OpHelp(""), + /* 175 */ "VCheck" OpHelp(""), + /* 176 */ "VInitIn" OpHelp("r[P2]=ValueList(P1,P3)"), + /* 177 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"), + /* 178 */ "VRename" OpHelp(""), + /* 179 */ "Pagecount" OpHelp(""), + /* 180 */ "MaxPgcnt" OpHelp(""), + /* 181 */ "ClrSubtype" OpHelp("r[P1].subtype = 0"), + /* 182 */ "GetSubtype" OpHelp("r[P2] = r[P1].subtype"), + /* 183 */ "SetSubtype" OpHelp("r[P2].subtype = r[P1]"), + /* 184 */ "FilterAdd" OpHelp("filter(P1) += key(P3@P4)"), + /* 185 */ "Trace" OpHelp(""), + /* 186 */ "CursorHint" OpHelp(""), + /* 187 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"), + /* 188 */ "Noop" OpHelp(""), + /* 189 */ "Explain" OpHelp(""), + /* 190 */ "Abortable" OpHelp(""), }; return azName[i]; } @@ -37494,6 +39567,22 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ ** This file contains an experimental VFS layer that operates on a ** Key/Value storage engine where both keys and values must be pure ** text. +** +** DEBUG AND TEST +** +** For testing on Unix, compile using: +** +** make clean sqlite3d CFLAGS='-DSQLITE_OS_KV_OPTIONAL' +** +** Then start up a shell using something like: +** +** ./sqlite3d 'file:dbname?vfs=kvvfs' +** +** Each K/V entry is stored in a separate file in the working +** directory that has a name like "kvvfs-dbname-*". Due to limitations +** on the key size, the name of the database must be very short - just +** a few characters. If the database name is too long, the VFS will +** malfunction and you will get SQLITE_CORRUPT errors. */ /* #include <sqliteInt.h> */ #if SQLITE_OS_KV || (SQLITE_OS_UNIX && defined(SQLITE_OS_KV_OPTIONAL)) @@ -37502,7 +39591,7 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ ** Debugging logic */ -/* SQLITE_KV_TRACE() is used for tracing calls to kvstorage routines. */ +/* SQLITE_KV_TRACE() is used for tracing calls to kvrecord routines. */ #if 0 #define SQLITE_KV_TRACE(X) printf X #else @@ -37516,7 +39605,6 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ #define SQLITE_KV_LOG(X) #endif - /* ** Forward declaration of objects used by this VFS implementation */ @@ -37524,6 +39612,11 @@ typedef struct KVVfsFile KVVfsFile; /* A single open file. There are only two files represented by this ** VFS - the database and the rollback journal. +** +** Maintenance reminder: if this struct changes in any way, the JSON +** rendering of its structure must be updated in +** sqlite3-wasm.c:sqlite3__wasm_enum_json(). There are no binary +** compatibility concerns, so it does not need an iVersion member. */ struct KVVfsFile { sqlite3_file base; /* IO methods */ @@ -37573,7 +39666,7 @@ static int kvvfsCurrentTime(sqlite3_vfs*, double*); static int kvvfsCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*); static sqlite3_vfs sqlite3OsKvvfsObject = { - 1, /* iVersion */ + 2, /* iVersion */ sizeof(KVVfsFile), /* szOsFile */ 1024, /* mxPathname */ 0, /* pNext */ @@ -37649,23 +39742,37 @@ static sqlite3_io_methods kvvfs_jrnl_io_methods = { /* Forward declarations for the low-level storage engine */ -static int kvstorageWrite(const char*, const char *zKey, const char *zData); -static int kvstorageDelete(const char*, const char *zKey); -static int kvstorageRead(const char*, const char *zKey, char *zBuf, int nBuf); -#define KVSTORAGE_KEY_SZ 32 +#ifndef SQLITE_WASM +/* In WASM builds these are implemented in JS. */ +static int kvrecordWrite(const char*, const char *zKey, const char *zData); +static int kvrecordDelete(const char*, const char *zKey); +static int kvrecordRead(const char*, const char *zKey, char *zBuf, int nBuf); +#endif +#ifndef KVRECORD_KEY_SZ +#define KVRECORD_KEY_SZ 32 +#endif /* Expand the key name with an appropriate prefix and put the result -** zKeyOut[]. The zKeyOut[] buffer is assumed to hold at least -** KVSTORAGE_KEY_SZ bytes. +** in zKeyOut[]. The zKeyOut[] buffer is assumed to hold at least +** KVRECORD_KEY_SZ bytes. */ -static void kvstorageMakeKey( +static void kvrecordMakeKey( const char *zClass, const char *zKeyIn, char *zKeyOut ){ - sqlite3_snprintf(KVSTORAGE_KEY_SZ, zKeyOut, "kvvfs-%s-%s", zClass, zKeyIn); + assert( zKeyIn ); + assert( zKeyOut ); + assert( zClass ); + sqlite3_snprintf(KVRECORD_KEY_SZ, zKeyOut, "kvvfs-%s-%s", + zClass, zKeyIn); } +#ifndef SQLITE_WASM +/* In WASM builds do not define APIs which use fopen(), fwrite(), +** and the like because those APIs are a portability issue for +** WASM. +*/ /* Write content into a key. zClass is the particular namespace of the ** underlying key/value store to use - either "local" or "session". ** @@ -37673,14 +39780,14 @@ static void kvstorageMakeKey( ** ** Return the number of errors. */ -static int kvstorageWrite( +static int kvrecordWrite( const char *zClass, const char *zKey, const char *zData ){ FILE *fd; - char zXKey[KVSTORAGE_KEY_SZ]; - kvstorageMakeKey(zClass, zKey, zXKey); + char zXKey[KVRECORD_KEY_SZ]; + kvrecordMakeKey(zClass, zKey, zXKey); fd = fopen(zXKey, "wb"); if( fd ){ SQLITE_KV_TRACE(("KVVFS-WRITE %-15s (%d) %.50s%s\n", zXKey, @@ -37698,9 +39805,9 @@ static int kvstorageWrite( ** namespace given by zClass. If the key does not previously exist, ** this routine is a no-op. */ -static int kvstorageDelete(const char *zClass, const char *zKey){ - char zXKey[KVSTORAGE_KEY_SZ]; - kvstorageMakeKey(zClass, zKey, zXKey); +static int kvrecordDelete(const char *zClass, const char *zKey){ + char zXKey[KVRECORD_KEY_SZ]; + kvrecordMakeKey(zClass, zKey, zXKey); unlink(zXKey); SQLITE_KV_TRACE(("KVVFS-DELETE %-15s\n", zXKey)); return 0; @@ -37714,12 +39821,14 @@ static int kvstorageDelete(const char *zClass, const char *zKey){ ** ** Return the total number of bytes in the data, without truncation, and ** not counting the final zero terminator. Return -1 if the key does -** not exist. +** not exist or its key cannot be read. ** -** If nBuf<=0 then this routine simply returns the size of the data without -** actually reading it. +** If nBuf<=0 then this routine simply returns the size of the data +** without actually reading it. Similarly, if nBuf==1 then it +** zero-terminates zBuf at zBuf[0] and returns the size of the data +** without reading it. */ -static int kvstorageRead( +static int kvrecordRead( const char *zClass, const char *zKey, char *zBuf, @@ -37727,8 +39836,8 @@ static int kvstorageRead( ){ FILE *fd; struct stat buf; - char zXKey[KVSTORAGE_KEY_SZ]; - kvstorageMakeKey(zClass, zKey, zXKey); + char zXKey[KVRECORD_KEY_SZ]; + kvrecordMakeKey(zClass, zKey, zXKey); if( access(zXKey, R_OK)!=0 || stat(zXKey, &buf)!=0 || !S_ISREG(buf.st_mode) @@ -37760,26 +39869,36 @@ static int kvstorageRead( return (int)n; } } +#endif /* #ifndef SQLITE_WASM */ + /* ** An internal level of indirection which enables us to replace the ** kvvfs i/o methods with JavaScript implementations in WASM builds. ** Maintenance reminder: if this struct changes in any way, the JSON ** rendering of its structure must be updated in -** sqlite3_wasm_enum_json(). There are no binary compatibility -** concerns, so it does not need an iVersion member. This file is -** necessarily always compiled together with sqlite3_wasm_enum_json(), -** and JS code dynamically creates the mapping of members based on -** that JSON description. +** sqlite3-wasm.c:sqlite3__wasm_enum_json(). There are no binary +** compatibility concerns, so it does not need an iVersion member. */ typedef struct sqlite3_kvvfs_methods sqlite3_kvvfs_methods; struct sqlite3_kvvfs_methods { - int (*xRead)(const char *zClass, const char *zKey, char *zBuf, int nBuf); - int (*xWrite)(const char *zClass, const char *zKey, const char *zData); - int (*xDelete)(const char *zClass, const char *zKey); + int (*xRcrdRead)(const char*, const char *zKey, char *zBuf, int nBuf); + int (*xRcrdWrite)(const char*, const char *zKey, const char *zData); + int (*xRcrdDelete)(const char*, const char *zKey); const int nKeySize; + const int nBufferSize; +#ifndef SQLITE_WASM +# define MAYBE_CONST const +#else +# define MAYBE_CONST +#endif + MAYBE_CONST sqlite3_vfs * pVfs; + MAYBE_CONST sqlite3_io_methods *pIoDb; + MAYBE_CONST sqlite3_io_methods *pIoJrnl; +#undef MAYBE_CONST }; + /* ** This object holds the kvvfs I/O methods which may be swapped out ** for JavaScript-side implementations in WASM builds. In such builds @@ -37787,17 +39906,27 @@ struct sqlite3_kvvfs_methods { ** the compiler can hopefully optimize this level of indirection out. ** That said, kvvfs is intended primarily for use in WASM builds. ** -** Note that this is not explicitly flagged as static because the -** amalgamation build will tag it with SQLITE_PRIVATE. +** This is not explicitly flagged as static because the amalgamation +** build will tag it with SQLITE_PRIVATE. */ #ifndef SQLITE_WASM const #endif SQLITE_PRIVATE sqlite3_kvvfs_methods sqlite3KvvfsMethods = { -kvstorageRead, -kvstorageWrite, -kvstorageDelete, -KVSTORAGE_KEY_SZ +#ifndef SQLITE_WASM + .xRcrdRead = kvrecordRead, + .xRcrdWrite = kvrecordWrite, + .xRcrdDelete = kvrecordDelete, +#else + .xRcrdRead = 0, + .xRcrdWrite = 0, + .xRcrdDelete = 0, +#endif + .nKeySize = KVRECORD_KEY_SZ, + .nBufferSize = SQLITE_KVOS_SZ, + .pVfs = &sqlite3OsKvvfsObject, + .pIoDb = &kvvfs_db_io_methods, + .pIoJrnl = &kvvfs_jrnl_io_methods }; /****** Utility subroutines ************************************************/ @@ -37824,7 +39953,10 @@ KVSTORAGE_KEY_SZ ** of hexadecimal and base-26 numbers, it is always clear where ** one stops and the next begins. */ -static int kvvfsEncode(const char *aData, int nData, char *aOut){ +#ifndef SQLITE_WASM +static +#endif +int kvvfsEncode(const char *aData, int nData, char *aOut){ int i, j; const unsigned char *a = (const unsigned char*)aData; for(i=j=0; i<nData; i++){ @@ -37875,9 +40007,13 @@ static const signed char kvvfsHexValue[256] = { ** Decode the text encoding back to binary. The binary content is ** written into pOut, which must be at least nOut bytes in length. ** -** The return value is the number of bytes actually written into aOut[]. +** The return value is the number of bytes actually written into aOut[], or +** -1 for malformed inputs. */ -static int kvvfsDecode(const char *a, char *aOut, int nOut){ +#ifndef SQLITE_WASM +static +#endif +int kvvfsDecode(const char *a, char *aOut, int nOut){ int i, j; int c; const unsigned char *aIn = (const unsigned char*)a; @@ -37886,25 +40022,28 @@ static int kvvfsDecode(const char *a, char *aOut, int nOut){ while( 1 ){ c = kvvfsHexValue[aIn[i]]; if( c<0 ){ - int n = 0; - int mult = 1; + sqlite3_int64 n = 0; + sqlite3_int64 mult = 1; c = aIn[i]; if( c==0 ) break; while( c>='a' && c<='z' ){ n += (c - 'a')*mult; + if( n>nOut ) return -1 /* oversized/malformed input */; mult *= 26; c = aIn[++i]; } - if( j+n>nOut ) return -1; + if( j+n>nOut ) return -1 /* oversized/malformed input */; memset(&aOut[j], 0, n); j += n; if( c==0 || mult==1 ) break; /* progress stalled if mult==1 */ - }else{ + }else if( j<nOut ){ aOut[j] = c<<4; c = kvvfsHexValue[aIn[++i]]; - if( c<0 ) break; + if( c<0 ) return -1 /* hex bytes are always in pairs */; aOut[j++] += c; i++; + }else{ + return -1; } } return j; @@ -37926,18 +40065,24 @@ static void kvvfsDecodeJournal( const char *zTxt, /* Text encoding. Zero-terminated */ int nTxt /* Bytes in zTxt, excluding zero terminator */ ){ - unsigned int n = 0; - int c, i, mult; + unsigned int n = 0, mult; + int c, i; i = 0; mult = 1; - while( (c = zTxt[i++])>='a' && c<='z' ){ - n += (zTxt[i] - 'a')*mult; + sqlite3_free(pFile->aJrnl); + pFile->aJrnl = 0; + pFile->nJrnl = 0; + while( (c = zTxt[i])>='a' && c<='z' ){ + n += (c - 'a')*mult; mult *= 26; + ++i; + } + if( ' '!=zTxt[i++] ){ + /* Malformed input */ + return; } - sqlite3_free(pFile->aJrnl); pFile->aJrnl = sqlite3_malloc64( n ); if( pFile->aJrnl==0 ){ - pFile->nJrnl = 0; return; } pFile->nJrnl = n; @@ -37955,13 +40100,14 @@ static void kvvfsDecodeJournal( static sqlite3_int64 kvvfsReadFileSize(KVVfsFile *pFile){ char zData[50]; zData[0] = 0; - sqlite3KvvfsMethods.xRead(pFile->zClass, "sz", zData, sizeof(zData)-1); + sqlite3KvvfsMethods.xRcrdRead(pFile->zClass, "sz", zData, + sizeof(zData)-1); return strtoll(zData, 0, 0); } static int kvvfsWriteFileSize(KVVfsFile *pFile, sqlite3_int64 sz){ char zData[50]; sqlite3_snprintf(sizeof(zData), zData, "%lld", sz); - return sqlite3KvvfsMethods.xWrite(pFile->zClass, "sz", zData); + return sqlite3KvvfsMethods.xRcrdWrite(pFile->zClass, "sz", zData); } /****** sqlite3_io_methods methods ******************************************/ @@ -37976,6 +40122,7 @@ static int kvvfsClose(sqlite3_file *pProtoFile){ pFile->isJournal ? "journal" : "db")); sqlite3_free(pFile->aJrnl); sqlite3_free(pFile->aData); + memset(pFile, 0, sizeof(*pFile)); return SQLITE_OK; } @@ -37992,16 +40139,23 @@ static int kvvfsReadJrnl( assert( pFile->isJournal ); SQLITE_KV_LOG(("xRead('%s-journal',%d,%lld)\n", pFile->zClass, iAmt, iOfst)); if( pFile->aJrnl==0 ){ - int szTxt = kvstorageRead(pFile->zClass, "jrnl", 0, 0); + int rc; + int szTxt = sqlite3KvvfsMethods.xRcrdRead(pFile->zClass, "jrnl", + 0, 0); char *aTxt; if( szTxt<=4 ){ return SQLITE_IOERR; } aTxt = sqlite3_malloc64( szTxt+1 ); if( aTxt==0 ) return SQLITE_NOMEM; - kvstorageRead(pFile->zClass, "jrnl", aTxt, szTxt+1); - kvvfsDecodeJournal(pFile, aTxt, szTxt); + rc = sqlite3KvvfsMethods.xRcrdRead(pFile->zClass, "jrnl", + aTxt, szTxt+1); + if( rc>=0 ){ + kvvfsDecodeJournal(pFile, aTxt, szTxt); + rc = 0; + } sqlite3_free(aTxt); + if( rc ) return rc; if( pFile->aJrnl==0 ) return SQLITE_IOERR; } if( iOfst+iAmt>pFile->nJrnl ){ @@ -38041,8 +40195,8 @@ static int kvvfsReadDb( pgno = 1; } sqlite3_snprintf(sizeof(zKey), zKey, "%u", pgno); - got = sqlite3KvvfsMethods.xRead(pFile->zClass, zKey, - aData, SQLITE_KVOS_SZ-1); + got = sqlite3KvvfsMethods.xRcrdRead(pFile->zClass, zKey, + aData, SQLITE_KVOS_SZ-1); if( got<0 ){ n = 0; }else{ @@ -38110,6 +40264,7 @@ static int kvvfsWriteDb( unsigned int pgno; char zKey[30]; char *aData = pFile->aData; + int rc; SQLITE_KV_LOG(("xWrite('%s-db',%d,%lld)\n", pFile->zClass, iAmt, iOfst)); assert( iAmt>=512 && iAmt<=65536 ); assert( (iAmt & (iAmt-1))==0 ); @@ -38118,13 +40273,13 @@ static int kvvfsWriteDb( pgno = 1 + iOfst/iAmt; sqlite3_snprintf(sizeof(zKey), zKey, "%u", pgno); kvvfsEncode(zBuf, iAmt, aData); - if( sqlite3KvvfsMethods.xWrite(pFile->zClass, zKey, aData) ){ - return SQLITE_IOERR; - } - if( iOfst+iAmt > pFile->szDb ){ - pFile->szDb = iOfst + iAmt; + rc = sqlite3KvvfsMethods.xRcrdWrite(pFile->zClass, zKey, aData); + if( 0==rc ){ + if( iOfst+iAmt > pFile->szDb ){ + pFile->szDb = iOfst + iAmt; + } } - return SQLITE_OK; + return rc; } /* @@ -38134,7 +40289,7 @@ static int kvvfsTruncateJrnl(sqlite3_file *pProtoFile, sqlite_int64 size){ KVVfsFile *pFile = (KVVfsFile *)pProtoFile; SQLITE_KV_LOG(("xTruncate('%s-journal',%lld)\n", pFile->zClass, size)); assert( size==0 ); - sqlite3KvvfsMethods.xDelete(pFile->zClass, "jrnl"); + sqlite3KvvfsMethods.xRcrdDelete(pFile->zClass, "jrnl"); sqlite3_free(pFile->aJrnl); pFile->aJrnl = 0; pFile->nJrnl = 0; @@ -38153,7 +40308,7 @@ static int kvvfsTruncateDb(sqlite3_file *pProtoFile, sqlite_int64 size){ pgnoMax = 2 + pFile->szDb/pFile->szPage; while( pgno<=pgnoMax ){ sqlite3_snprintf(sizeof(zKey), zKey, "%u", pgno); - sqlite3KvvfsMethods.xDelete(pFile->zClass, zKey); + sqlite3KvvfsMethods.xRcrdDelete(pFile->zClass, zKey); pgno++; } pFile->szDb = size; @@ -38185,7 +40340,7 @@ static int kvvfsSyncJrnl(sqlite3_file *pProtoFile, int flags){ }while( n>0 ); zOut[i++] = ' '; kvvfsEncode(pFile->aJrnl, pFile->nJrnl, &zOut[i]); - i = sqlite3KvvfsMethods.xWrite(pFile->zClass, "jrnl", zOut); + i = sqlite3KvvfsMethods.xRcrdWrite(pFile->zClass, "jrnl", zOut); sqlite3_free(zOut); return i ? SQLITE_IOERR : SQLITE_OK; } @@ -38299,33 +40454,44 @@ static int kvvfsOpen( KVVfsFile *pFile = (KVVfsFile*)pProtoFile; if( zName==0 ) zName = ""; SQLITE_KV_LOG(("xOpen(\"%s\")\n", zName)); - if( strcmp(zName, "local")==0 - || strcmp(zName, "session")==0 - ){ - pFile->isJournal = 0; - pFile->base.pMethods = &kvvfs_db_io_methods; - }else - if( strcmp(zName, "local-journal")==0 - || strcmp(zName, "session-journal")==0 - ){ + assert(!pFile->zClass); + assert(!pFile->aData); + assert(!pFile->aJrnl); + assert(!pFile->nJrnl); + assert(!pFile->base.pMethods); + pFile->szPage = -1; + pFile->szDb = -1; + if( 0==sqlite3_strglob("*-journal", zName) ){ pFile->isJournal = 1; pFile->base.pMethods = &kvvfs_jrnl_io_methods; + if( 0==strcmp("session-journal",zName) ){ + pFile->zClass = "session"; + }else if( 0==strcmp("local-journal",zName) ){ + pFile->zClass = "local"; + } }else{ - return SQLITE_CANTOPEN; + pFile->isJournal = 0; + pFile->base.pMethods = &kvvfs_db_io_methods; } - if( zName[0]=='s' ){ - pFile->zClass = "session"; - }else{ - pFile->zClass = "local"; + if( !pFile->zClass ){ +#ifdef SQLITE_WASM + if( strlen(zName) >= (KVRECORD_KEY_SZ + - 6 /* "kvvfs-" */ + - 11 /* "-NNNNNNNNNNN" */) ){ + return SQLITE_CANTOPEN; + } +#else + if( 0!=strcmp(zName, "local") && 0!=strcmp(zName, "session") ){ + /* Historical naming restriction which journaling depends on. */ + return SQLITE_CANTOPEN; + } +#endif + pFile->zClass = zName; } pFile->aData = sqlite3_malloc64(SQLITE_KVOS_SZ); if( pFile->aData==0 ){ return SQLITE_NOMEM; } - pFile->aJrnl = 0; - pFile->nJrnl = 0; - pFile->szPage = -1; - pFile->szDb = -1; return SQLITE_OK; } @@ -38335,13 +40501,17 @@ static int kvvfsOpen( ** returning. */ static int kvvfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ + int rc /* The JS impl can fail with OOM in argument conversion */; if( strcmp(zPath, "local-journal")==0 ){ - sqlite3KvvfsMethods.xDelete("local", "jrnl"); + rc = sqlite3KvvfsMethods.xRcrdDelete("local", "jrnl"); }else if( strcmp(zPath, "session-journal")==0 ){ - sqlite3KvvfsMethods.xDelete("session", "jrnl"); + rc = sqlite3KvvfsMethods.xRcrdDelete("session", "jrnl"); } - return SQLITE_OK; + else{ + rc = 0; + } + return rc; } /* @@ -38355,21 +40525,42 @@ static int kvvfsAccess( int *pResOut ){ SQLITE_KV_LOG(("xAccess(\"%s\")\n", zPath)); +#if 0 && defined(SQLITE_WASM) + /* + ** This is not having the desired effect in the JS bindings. + ** It's ostensibly the same logic as the #else block, but + ** it's not behaving that way. + ** + ** In JS we map all zPaths to Storage objects, and -journal files + ** are mapped to the storage for the main db (which is is exactly + ** what the mapping of "local-journal" -> "local" is doing). + */ + const char *zKey = (0==sqlite3_strglob("*-journal", zPath)) + ? "jrnl" : "sz"; + *pResOut = + sqlite3KvvfsMethods.xRcrdRead(zPath, zKey, 0, 0)>0; +#else if( strcmp(zPath, "local-journal")==0 ){ - *pResOut = sqlite3KvvfsMethods.xRead("local", "jrnl", 0, 0)>0; + *pResOut = + sqlite3KvvfsMethods.xRcrdRead("local", "jrnl", 0, 0)>0; }else if( strcmp(zPath, "session-journal")==0 ){ - *pResOut = sqlite3KvvfsMethods.xRead("session", "jrnl", 0, 0)>0; + *pResOut = + sqlite3KvvfsMethods.xRcrdRead("session", "jrnl", 0, 0)>0; }else if( strcmp(zPath, "local")==0 ){ - *pResOut = sqlite3KvvfsMethods.xRead("local", "sz", 0, 0)>0; + *pResOut = + sqlite3KvvfsMethods.xRcrdRead("local", "sz", 0, 0)>0; }else if( strcmp(zPath, "session")==0 ){ - *pResOut = sqlite3KvvfsMethods.xRead("session", "sz", 0, 0)>0; + *pResOut = + sqlite3KvvfsMethods.xRcrdRead("session", "sz", 0, 0)>0; }else { *pResOut = 0; } + /*all current JS tests avoid triggering: assert( *pResOut == 0 ); */ +#endif SQLITE_KV_LOG(("xAccess returns %d\n",*pResOut)); return SQLITE_OK; } @@ -38676,7 +40867,7 @@ SQLITE_PRIVATE int sqlite3KvvfsInit(void){ # endif #else /* !SQLITE_WASI */ # ifndef HAVE_FCHMOD -# define HAVE_FCHMOD +# define HAVE_FCHMOD 1 # endif #endif /* SQLITE_WASI */ @@ -38747,6 +40938,7 @@ struct unixFile { #endif #ifdef SQLITE_ENABLE_SETLK_TIMEOUT unsigned iBusyTimeout; /* Wait this many millisec on locks */ + int bBlockOnConnect; /* True to block for SHARED locks */ #endif #if OS_VXWORKS struct vxworksFileId *pId; /* Unique file ID */ @@ -38960,10 +41152,11 @@ static struct unix_syscall { #if defined(HAVE_FCHMOD) { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 }, +#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent) #else { "fchmod", (sqlite3_syscall_ptr)0, 0 }, +#define osFchmod(FID,MODE) 0 #endif -#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent) #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 }, @@ -39057,6 +41250,119 @@ static struct unix_syscall { }; /* End of the overrideable system calls */ +#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT) +/* +** Extract Posix Advisory Locking information about file description fd +** from the /proc/PID/fdinfo/FD pseudo-file. Fill the string buffer a[16] +** with characters to indicate which SQLite-relevant locks are held. +** a[16] will be a 15-character zero-terminated string with the following +** schema: +** +** AAA/B.DDD.DDDDD +** +** Each of character A-D will be "w" or "r" or "-" to indicate either a +** write-lock, a read-lock, or no-lock, respectively. The "." and "/" +** characters are delimiters intended to make the string more easily +** readable by humans. Here are the meaning of the specific letters: +** +** AAA -> The main database locks. PENDING_BYTE, RESERVED_BYTE, +** and SHARED_FIRST, respectively. +** +** B -> The deadman switch lock. Offset 128 of the -shm file. +** +** CCC -> WAL locks: WRITE, CKPT, RECOVER +** +** DDDDD -> WAL read-locks 0 through 5 +** +** Note that elements before the "/" apply to the main database file and +** elements after the "/" apply to the -shm file in WAL mode. +** +** Here is another way of thinking about the meaning of the result string: +** +** AAA/B.CCC.DDDDD +** ||| | ||| \___/ +** PENDING--'|| | ||| `----- READ 0-5 +** RESERVED--'| | ||`---- RECOVER +** SHARED ----' | |`----- CKPT +** DMS ------' `------ WRITE +** +** Return SQLITE_OK on success and SQLITE_ERROR_UNABLE if the /proc +** pseudo-filesystem is unavailable. +*/ +static int unixPosixAdvisoryLocks( + int fd, /* The file descriptor to analyze */ + char a[16] /* Write a text description of PALs here */ +){ + int in; + ssize_t n; + char *p, *pNext, *x; + char z[2000]; + + /* 1 */ + /* 012 4 678 01234 */ + memcpy(a, "---/-.---.-----", 16); + sqlite3_snprintf(sizeof(z), z, "/proc/%d/fdinfo/%d", getpid(), fd); + in = osOpen(z, O_RDONLY, 0); + if( in<0 ){ + return SQLITE_ERROR_UNABLE; + } + n = osRead(in, z, sizeof(z)-1); + osClose(in); + if( n<=0 ) return SQLITE_ERROR_UNABLE; + z[n] = 0; + + /* We are looking for lines that begin with "lock:\t". Examples: + ** + ** lock: 1: POSIX ADVISORY READ 494716 08:02:5277597 1073741826 1073742335 + ** lock: 1: POSIX ADVISORY WRITE 494716 08:02:5282282 120 120 + ** lock: 2: POSIX ADVISORY READ 494716 08:02:5282282 123 123 + ** lock: 3: POSIX ADVISORY READ 494716 08:02:5282282 128 128 + */ + pNext = strstr(z, "lock:\t"); + while( pNext ){ + char cType = 0; + sqlite3_int64 iFirst, iLast; + p = pNext+6; + pNext = strstr(p, "lock:\t"); + if( pNext ) pNext[-1] = 0; + if( (x = strstr(p, " READ "))!=0 ){ + cType = 'r'; + x += 6; + }else if( (x = strstr(p, " WRITE "))!=0 ){ + cType = 'w'; + x += 7; + }else{ + continue; + } + x = strrchr(x, ' '); + if( x==0 ) continue; + iLast = strtoll(x+1, 0, 10); + *x = 0; + x = strrchr(p, ' '); + if( x==0 ) continue; + iFirst = strtoll(x+1, 0, 10); + if( iLast>=PENDING_BYTE ){ + if( iFirst<=PENDING_BYTE && iLast>=PENDING_BYTE ) a[0] = cType; + if( iFirst<=PENDING_BYTE+1 && iLast>=PENDING_BYTE+1 ) a[1] = cType; + if( iFirst<=PENDING_BYTE+2 && iLast>=PENDING_BYTE+510 ) a[2] = cType; + }else if( iLast<=128 ){ + if( iFirst<=128 && iLast>=128 ) a[4] = cType; + if( iFirst<=120 && iLast>=120 ) a[6] = cType; + if( iFirst<=121 && iLast>=121 ) a[7] = cType; + if( iFirst<=122 && iLast>=122 ) a[8] = cType; + if( iFirst<=123 && iLast>=123 ) a[10] = cType; + if( iFirst<=124 && iLast>=124 ) a[11] = cType; + if( iFirst<=125 && iLast>=125 ) a[12] = cType; + if( iFirst<=126 && iLast>=126 ) a[13] = cType; + if( iFirst<=127 && iLast>=127 ) a[14] = cType; + } + } + return SQLITE_OK; +} +#else +# define unixPosixAdvisoryLocks(A,B) SQLITE_ERROR_UNABLE +#endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */ + /* ** On some systems, calls to fchown() will trigger a message in a security ** log if they come from non-root processes. So avoid calling fchown() if @@ -39221,9 +41527,8 @@ static int robust_open(const char *z, int f, mode_t m){ /* ** Helper functions to obtain and relinquish the global mutex. The -** global mutex is used to protect the unixInodeInfo and -** vxworksFileId objects used by this file, all of which may be -** shared by multiple threads. +** global mutex is used to protect the unixInodeInfo objects used by +** this file, all of which may be shared by multiple threads. ** ** Function unixMutexHeld() is used to assert() that the global mutex ** is held when required. This function is only used as part of assert() @@ -39425,6 +41730,7 @@ struct vxworksFileId { ** variable: */ static struct vxworksFileId *vxworksFileList = 0; +static sqlite3_mutex *vxworksMutex = 0; /* ** Simplify a filename into its canonical form @@ -39490,14 +41796,14 @@ static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){ ** If found, increment the reference count and return a pointer to ** the existing file ID. */ - unixEnterMutex(); + sqlite3_mutex_enter(vxworksMutex); for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){ if( pCandidate->nName==n && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0 ){ sqlite3_free(pNew); pCandidate->nRef++; - unixLeaveMutex(); + sqlite3_mutex_leave(vxworksMutex); return pCandidate; } } @@ -39507,7 +41813,7 @@ static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){ pNew->nName = n; pNew->pNext = vxworksFileList; vxworksFileList = pNew; - unixLeaveMutex(); + sqlite3_mutex_leave(vxworksMutex); return pNew; } @@ -39516,7 +41822,7 @@ static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){ ** the object when the reference count reaches zero. */ static void vxworksReleaseFileId(struct vxworksFileId *pId){ - unixEnterMutex(); + sqlite3_mutex_enter(vxworksMutex); assert( pId->nRef>0 ); pId->nRef--; if( pId->nRef==0 ){ @@ -39526,7 +41832,7 @@ static void vxworksReleaseFileId(struct vxworksFileId *pId){ *pp = pId->pNext; sqlite3_free(pId); } - unixLeaveMutex(); + sqlite3_mutex_leave(vxworksMutex); } #endif /* OS_VXWORKS */ /*************** End of Unique File ID Utility Used By VxWorks **************** @@ -39914,6 +42220,10 @@ static int findInodeInfo( storeLastErrno(pFile, errno); return SQLITE_IOERR; } + if( fsync(fd) ){ + storeLastErrno(pFile, errno); + return SQLITE_IOERR_FSYNC; + } rc = osFstat(fd, &statbuf); if( rc!=0 ){ storeLastErrno(pFile, errno); @@ -40083,18 +42393,42 @@ static int osSetPosixAdvisoryLock( struct flock *pLock, /* The description of the lock */ unixFile *pFile /* Structure holding timeout value */ ){ - int tm = pFile->iBusyTimeout; - int rc = osFcntl(h,F_SETLK,pLock); - while( rc<0 && tm>0 ){ - /* On systems that support some kind of blocking file lock with a timeout, - ** make appropriate changes here to invoke that blocking file lock. On - ** generic posix, however, there is no such API. So we simply try the - ** lock once every millisecond until either the timeout expires, or until - ** the lock is obtained. */ - unixSleep(0,1000); + int rc = 0; + + if( pFile->iBusyTimeout==0 ){ + /* unixFile->iBusyTimeout is set to 0. In this case, attempt a + ** non-blocking lock. */ rc = osFcntl(h,F_SETLK,pLock); - tm--; + }else{ + /* unixFile->iBusyTimeout is set to greater than zero. In this case, + ** attempt a blocking-lock with a unixFile->iBusyTimeout ms timeout. + ** + ** On systems that support some kind of blocking file lock operation, + ** this block should be replaced by code to attempt a blocking lock + ** with a timeout of unixFile->iBusyTimeout ms. The code below is + ** placeholder code. If SQLITE_TEST is defined, the placeholder code + ** retries the lock once every 1ms until it succeeds or the timeout + ** is reached. Or, if SQLITE_TEST is not defined, the placeholder + ** code attempts a non-blocking lock and sets unixFile->iBusyTimeout + ** to 0. This causes the caller to return SQLITE_BUSY, instead of + ** SQLITE_BUSY_TIMEOUT to SQLite - as required by a VFS that does not + ** support blocking locks. + */ +#ifdef SQLITE_TEST + int tm = pFile->iBusyTimeout; + while( tm>0 ){ + rc = osFcntl(h,F_SETLK,pLock); + if( rc==0 ) break; + unixSleep(0,1000); + tm--; + } +#else + rc = osFcntl(h,F_SETLK,pLock); + pFile->iBusyTimeout = 0; +#endif + /* End of code to replace with real blocking-locks code. */ } + return rc; } #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */ @@ -40127,7 +42461,7 @@ static int unixFileLock(unixFile *pFile, struct flock *pLock){ if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){ if( pInode->bProcessLock==0 ){ struct flock lock; - assert( pInode->nLock==0 ); + /* assert( pInode->nLock==0 ); <-- Not true if unix-excl READONLY used */ lock.l_whence = SEEK_SET; lock.l_start = SHARED_FIRST; lock.l_len = SHARED_SIZE; @@ -40140,11 +42474,25 @@ static int unixFileLock(unixFile *pFile, struct flock *pLock){ rc = 0; } }else{ +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + if( pFile->bBlockOnConnect && pLock->l_type==F_RDLCK + && pLock->l_start==SHARED_FIRST && pLock->l_len==SHARED_SIZE + ){ + rc = osFcntl(pFile->h, F_SETLKW, pLock); + }else +#endif rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile); } return rc; } +#if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL) +/* Forward reference */ +static int unixIsSharingShmNode(unixFile*); +#else +#define unixIsSharingShmNode(pFile) (0) +#endif + /* ** Lock the file with the lock specified by parameter eFileLock - one ** of the following: @@ -40337,6 +42685,14 @@ static int unixLock(sqlite3_file *id, int eFileLock){ /* We are trying for an exclusive lock but another thread in this ** same process is still holding a shared lock. */ rc = SQLITE_BUSY; + }else if( unixIsSharingShmNode(pFile) ){ + /* We are in WAL mode and attempting to delete the SHM and WAL + ** files due to closing the connection or changing out of WAL mode, + ** but another process still holds locks on the SHM file, thus + ** indicating that database locks have been broken, perhaps due + ** to a rogue close(open(dbFile)) or similar. + */ + rc = SQLITE_BUSY; }else{ /* The request was for a RESERVED or EXCLUSIVE lock. It is ** assumed that there is a SHARED or greater lock on the file @@ -42428,6 +44784,10 @@ static int unixGetTempname(int nBuf, char *zBuf); #if !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL) static int unixFcntlExternalReader(unixFile*, int*); #endif +#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT) + static void unixDescribeShm(sqlite3_str*,unixShm*); +#endif + /* ** Information and control of an open file handle. @@ -42450,6 +44810,11 @@ static int unixFileControl(sqlite3_file *id, int op, void *pArg){ } #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */ + case SQLITE_FCNTL_NULL_IO: { + osClose(pFile->h); + pFile->h = -1; + return SQLITE_OK; + } case SQLITE_FCNTL_LOCKSTATE: { *(int*)pArg = pFile->eFileLock; return SQLITE_OK; @@ -42496,8 +44861,9 @@ static int unixFileControl(sqlite3_file *id, int op, void *pArg){ #ifdef SQLITE_ENABLE_SETLK_TIMEOUT case SQLITE_FCNTL_LOCK_TIMEOUT: { int iOld = pFile->iBusyTimeout; + int iNew = *(int*)pArg; #if SQLITE_ENABLE_SETLK_TIMEOUT==1 - pFile->iBusyTimeout = *(int*)pArg; + pFile->iBusyTimeout = iNew<0 ? 0x7FFFFFFF : (unsigned)iNew; #elif SQLITE_ENABLE_SETLK_TIMEOUT==2 pFile->iBusyTimeout = !!(*(int*)pArg); #else @@ -42506,7 +44872,12 @@ static int unixFileControl(sqlite3_file *id, int op, void *pArg){ *(int*)pArg = iOld; return SQLITE_OK; } -#endif + case SQLITE_FCNTL_BLOCK_ON_CONNECT: { + int iNew = *(int*)pArg; + pFile->bBlockOnConnect = iNew; + return SQLITE_OK; + } +#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */ #if SQLITE_MAX_MMAP_SIZE>0 case SQLITE_FCNTL_MMAP_SIZE: { i64 newLimit = *(i64*)pArg; @@ -42559,6 +44930,66 @@ static int unixFileControl(sqlite3_file *id, int op, void *pArg){ return SQLITE_OK; #endif } + +#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT) + case SQLITE_FCNTL_FILESTAT: { + sqlite3_str *pStr = (sqlite3_str*)pArg; + char aLck[16]; + unixInodeInfo *pInode; + static const char *azLock[] = { "SHARED", "RESERVED", + "PENDING", "EXCLUSIVE" }; + sqlite3_str_appendf(pStr, "{\"h\":%d", pFile->h); + sqlite3_str_appendf(pStr, ",\"vfs\":\"%s\"", pFile->pVfs->zName); + if( pFile->eFileLock ){ + sqlite3_str_appendf(pStr, ",\"eFileLock\":\"%s\"", + azLock[pFile->eFileLock-1]); + if( unixPosixAdvisoryLocks(pFile->h, aLck)==SQLITE_OK ){ + sqlite3_str_appendf(pStr, ",\"pal\":\"%s\"", aLck); + } + } + unixEnterMutex(); + if( pFile->pShm ){ + sqlite3_str_appendall(pStr, ",\"shm\":"); + unixDescribeShm(pStr, pFile->pShm); + } +#if SQLITE_MAX_MMAP_SIZE>0 + if( pFile->mmapSize ){ + sqlite3_str_appendf(pStr, ",\"mmapSize\":%lld", pFile->mmapSize); + sqlite3_str_appendf(pStr, ",\"nFetchOut\":%d", pFile->nFetchOut); + } +#endif + if( (pInode = pFile->pInode)!=0 ){ + sqlite3_str_appendf(pStr, ",\"inode\":{\"nRef\":%d",pInode->nRef); + sqlite3_mutex_enter(pInode->pLockMutex); + sqlite3_str_appendf(pStr, ",\"nShared\":%d", pInode->nShared); + if( pInode->eFileLock ){ + sqlite3_str_appendf(pStr, ",\"eFileLock\":\"%s\"", + azLock[pInode->eFileLock-1]); + } + if( pInode->pUnused ){ + char cSep = '['; + UnixUnusedFd *pUFd = pFile->pInode->pUnused; + sqlite3_str_appendall(pStr, ",\"unusedFd\":"); + while( pUFd ){ + sqlite3_str_appendf(pStr, "%c{\"fd\":%d,\"flags\":%d", + cSep, pUFd->fd, pUFd->flags); + cSep = ','; + if( unixPosixAdvisoryLocks(pUFd->fd, aLck)==SQLITE_OK ){ + sqlite3_str_appendf(pStr, ",\"pal\":\"%s\"", aLck); + } + sqlite3_str_append(pStr, "}", 1); + pUFd = pUFd->pNext; + } + sqlite3_str_append(pStr, "]", 1); + } + sqlite3_mutex_leave(pInode->pLockMutex); + sqlite3_str_append(pStr, "}", 1); + } + unixLeaveMutex(); + sqlite3_str_append(pStr, "}", 1); + return SQLITE_OK; + } +#endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */ } return SQLITE_NOTFOUND; } @@ -42591,6 +45022,7 @@ static void setDeviceCharacteristics(unixFile *pFd){ if( pFd->ctrlFlags & UNIXFILE_PSOW ){ pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE; } + pFd->deviceCharacteristics |= SQLITE_IOCAP_SUBPAGE_READ; pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; } @@ -42824,6 +45256,26 @@ struct unixShm { #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */ #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */ +#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT) +/* +** Describe the pShm object using JSON. Used for diagnostics only. +*/ +static void unixDescribeShm(sqlite3_str *pStr, unixShm *pShm){ + unixShmNode *pNode = pShm->pShmNode; + char aLck[16]; + sqlite3_str_appendf(pStr, "{\"h\":%d", pNode->hShm); + assert( unixMutexHeld() ); + sqlite3_str_appendf(pStr, ",\"nRef\":%d", pNode->nRef); + sqlite3_str_appendf(pStr, ",\"id\":%d", pShm->id); + sqlite3_str_appendf(pStr, ",\"sharedMask\":%d", pShm->sharedMask); + sqlite3_str_appendf(pStr, ",\"exclMask\":%d", pShm->exclMask); + if( unixPosixAdvisoryLocks(pNode->hShm, aLck)==SQLITE_OK ){ + sqlite3_str_appendf(pStr, ",\"pal\":\"%s\"", aLck); + } + sqlite3_str_append(pStr, "}", 1); +} +#endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */ + /* ** Use F_GETLK to check whether or not there are any readers with open ** wal-mode transactions in other processes on database file pFile. If @@ -42857,6 +45309,44 @@ static int unixFcntlExternalReader(unixFile *pFile, int *piOut){ return rc; } +/* +** If pFile has a -shm file open and it is sharing that file with some +** other connection, either in the same process or in a separate process, +** then return true. Return false if either pFile does not have a -shm +** file open or if it is the only connection to that -shm file across the +** entire system. +** +** This routine is not required for correct operation. It can always return +** false and SQLite will continue to operate according to spec. However, +** when this routine does its job, it adds extra robustness in cases +** where database file locks have been erroneously deleted in a WAL-mode +** database by doing close(open(DATABASE_PATHNAME)) or similar. +** +** With false negatives, SQLite still operates to spec, though with less +** robustness. With false positives, the last database connection on a +** WAL-mode database will fail to unlink the -wal and -shm files, which +** is annoying but harmless. False positives will also prevent a database +** connection from running "PRAGMA journal_mode=DELETE" in order to take +** the database out of WAL mode, which is perhaps more serious, but is +** still not a disaster. +*/ +static int unixIsSharingShmNode(unixFile *pFile){ + unixShmNode *pShmNode; + struct flock lock; + if( pFile->pShm==0 ) return 0; + if( pFile->ctrlFlags & UNIXFILE_EXCL ) return 0; + pShmNode = pFile->pShm->pShmNode; +#if SQLITE_ATOMIC_INTRINSICS + assert( AtomicLoad(&pShmNode->nRef)==1 ); +#endif + memset(&lock, 0, sizeof(lock)); + lock.l_whence = SEEK_SET; + lock.l_start = UNIX_SHM_DMS; + lock.l_len = 1; + lock.l_type = F_WRLCK; + osFcntl(pShmNode->hShm, F_GETLK, &lock); + return (lock.l_type!=F_UNLCK); +} /* ** Apply posix advisory locks for all bytes from ofst through ofst+n-1. @@ -42902,7 +45392,8 @@ static int unixShmSystemLock( /* Locks are within range */ assert( n>=1 && n<=SQLITE_SHM_NLOCK ); - assert( ofst>=UNIX_SHM_BASE && ofst<=(UNIX_SHM_DMS+SQLITE_SHM_NLOCK) ); + assert( ofst>=UNIX_SHM_BASE && ofst<=UNIX_SHM_DMS ); + assert( ofst+n-1<=UNIX_SHM_DMS ); if( pShmNode->hShm>=0 ){ int res; @@ -43303,9 +45794,9 @@ static int unixShmMap( nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap; if( pShmNode->nRegion<nReqRegion ){ - char **apNew; /* New apRegion[] array */ - int nByte = nReqRegion*szRegion; /* Minimum required file size */ - struct stat sStat; /* Used by fstat() */ + char **apNew; /* New apRegion[] array */ + i64 nByte = nReqRegion*(i64)szRegion; /* Minimum required file size */ + struct stat sStat; /* Used by fstat() */ pShmNode->szRegion = szRegion; @@ -43336,7 +45827,7 @@ static int unixShmMap( */ else{ static const int pgsz = 4096; - int iPg; + i64 iPg; /* Write to the last byte of each newly allocated or extended page */ assert( (nByte % pgsz)==0 ); @@ -43353,7 +45844,7 @@ static int unixShmMap( } /* Map the requested memory region into this processes address space. */ - apNew = (char **)sqlite3_realloc( + apNew = (char **)sqlite3_realloc64( pShmNode->apRegion, nReqRegion*sizeof(char *) ); if( !apNew ){ @@ -43362,8 +45853,8 @@ static int unixShmMap( } pShmNode->apRegion = apNew; while( pShmNode->nRegion<nReqRegion ){ - int nMap = szRegion*nShmPerMap; - int i; + i64 nMap = (i64)szRegion*(i64)nShmPerMap; + i64 i; void *pMem; if( pShmNode->hShm>=0 ){ pMem = osMmap(0, nMap, @@ -43434,7 +45925,7 @@ static int assertLockingArrayOk(unixShmNode *pShmNode){ return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0); #endif } -#endif +#endif /* !defined(SQLITE_WASI) && !defined(SQLITE_OMIT_WAL) */ /* ** Change the lock state for a shared-memory segment. @@ -43478,21 +45969,20 @@ static int unixShmLock( /* Check that, if this to be a blocking lock, no locks that occur later ** in the following list than the lock being obtained are already held: ** - ** 1. Checkpointer lock (ofst==1). - ** 2. Write lock (ofst==0). - ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK). + ** 1. Recovery lock (ofst==2). + ** 2. Checkpointer lock (ofst==1). + ** 3. Write lock (ofst==0). + ** 4. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK). ** ** In other words, if this is a blocking lock, none of the locks that ** occur later in the above list than the lock being obtained may be ** held. - ** - ** It is not permitted to block on the RECOVER lock. */ -#ifdef SQLITE_ENABLE_SETLK_TIMEOUT +#if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && defined(SQLITE_DEBUG) { u16 lockMask = (p->exclMask|p->sharedMask); assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || ( - (ofst!=2) /* not RECOVER */ + (ofst!=2 || lockMask==0) && (ofst!=1 || lockMask==0 || lockMask==2) && (ofst!=0 || lockMask<3) && (ofst<3 || lockMask<(1<<ofst)) @@ -43753,7 +46243,6 @@ static void unixRemapfile( const char *zErr = "mmap"; int h = pFd->h; /* File descriptor open on db file */ u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */ - i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */ u8 *pNew = 0; /* Location of new mapping */ int flags = PROT_READ; /* Flags to pass to mmap() */ @@ -43769,37 +46258,35 @@ static void unixRemapfile( #endif if( pOrig ){ -#if HAVE_MREMAP - i64 nReuse = pFd->mmapSize; -#else - const int szSyspage = osGetpagesize(); - i64 nReuse = (pFd->mmapSize & ~(szSyspage-1)); -#endif - u8 *pReq = &pOrig[nReuse]; + i64 nReuse = pFd->mmapSize & ~((int)osGetpagesize()-1); - /* Unmap any pages of the existing mapping that cannot be reused. */ - if( nReuse!=nOrig ){ - osMunmap(pReq, nOrig-nReuse); + /* Unmap any part of the current mapping that will not be reused */ + if( nReuse<pFd->mmapSizeActual ){ + osMunmap(&pOrig[nReuse], pFd->mmapSizeActual - nReuse); } + /* If nReuse is now zero, then the entire mapping was unmapped by the + ** call above. In this case do not attempt to extend pOrig. */ + if( nReuse>0 ){ #if HAVE_MREMAP - pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE); - zErr = "mremap"; + pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE); + zErr = "mremap"; #else - pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse); - if( pNew!=MAP_FAILED ){ - if( pNew!=pReq ){ - osMunmap(pNew, nNew - nReuse); - pNew = 0; - }else{ - pNew = pOrig; + pNew = osMmap(&pOrig[nReuse], nNew-nReuse, flags, MAP_SHARED, h, nReuse); + if( pNew!=MAP_FAILED ){ + if( pNew!=&pOrig[nReuse] ){ + osMunmap(pNew, nNew - nReuse); + pNew = 0; + }else{ + pNew = pOrig; + } } - } #endif - /* The attempt to extend the existing mapping failed. Free it. */ - if( pNew==MAP_FAILED || pNew==0 ){ - osMunmap(pOrig, nReuse); + /* The attempt to extend the existing mapping failed. Free it. */ + if( pNew==MAP_FAILED || pNew==0 ){ + osMunmap(pOrig, nReuse); + } } } @@ -44397,10 +46884,17 @@ static int fillInUnixFile( storeLastErrno(pNew, 0); #if OS_VXWORKS if( rc!=SQLITE_OK ){ - if( h>=0 ) robust_close(pNew, h, __LINE__); - h = -1; - osUnlink(zFilename); - pNew->ctrlFlags |= UNIXFILE_DELETE; + if( h>=0 ){ + robust_close(pNew, h, __LINE__); + h = -1; + } + if( pNew->ctrlFlags & UNIXFILE_DELETE ){ + osUnlink(zFilename); + } + if( pNew->pId ){ + vxworksReleaseFileId(pNew->pId); + pNew->pId = 0; + } } #endif if( rc!=SQLITE_OK ){ @@ -44413,45 +46907,39 @@ static int fillInUnixFile( return rc; } -/* -** Directories to consider for temp files. -*/ -static const char *azTempDirs[] = { - 0, - 0, - "/var/tmp", - "/usr/tmp", - "/tmp", - "." -}; - -/* -** Initialize first two members of azTempDirs[] array. -*/ -static void unixTempFileInit(void){ - azTempDirs[0] = getenv("SQLITE_TMPDIR"); - azTempDirs[1] = getenv("TMPDIR"); -} - /* ** Return the name of a directory in which to put temporary files. ** If no suitable temporary file directory can be found, return NULL. +** +** The return value might be a string obtained from getenv() and so +** the return value should not be used after any call to setenv() or +** putenv() as that value might have been freed. */ static const char *unixTempFileDir(void){ - unsigned int i = 0; + unsigned int i; struct stat buf; - const char *zDir = sqlite3_temp_directory; + const char *zDir; - while(1){ + for(i=0; i<7; i++){ + switch( i ){ + case 0: zDir = sqlite3_temp_directory; break; + case 1: zDir = getenv("SQLITE_TMPDIR"); break; + case 2: zDir = getenv("TMPDIR"); break; + case 3: zDir = "/var/tmp"; break; + case 4: zDir = "/usr/tmp"; break; + case 5: zDir = "/tmp"; break; + default: zDir = "."; break; + } if( zDir!=0 +#if OS_VXWORKS + && zDir[0]=='/' +#endif && osStat(zDir, &buf)==0 && S_ISDIR(buf.st_mode) && osAccess(zDir, 03)==0 ){ return zDir; } - if( i>=sizeof(azTempDirs)/sizeof(azTempDirs[0]) ) break; - zDir = azTempDirs[i++]; } return 0; } @@ -44758,6 +47246,12 @@ static int unixOpen( || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL ); +#if OS_VXWORKS + /* The file-ID mechanism used in Vxworks requires that all pathnames + ** provided to unixOpen must be absolute pathnames. */ + if( zPath!=0 && zPath[0]!='/' ){ return SQLITE_CANTOPEN; } +#endif + /* Detect a pid change and reset the PRNG. There is a race condition ** here such that two or more threads all trying to open databases at ** the same instant might all reset the PRNG. But multiple resets @@ -44794,7 +47288,22 @@ static int unixOpen( }else if( !zName ){ /* If zName is NULL, the upper layer is requesting a temp file. */ - assert(isDelete && !isNewJrnl); + assert( isDelete ); + assert( !isNewJrnl ); + assert( isExclusive ); + assert( isReadWrite ); +#if defined(__linux__) && defined(O_TMPFILE) + /* On systems that support O_TMPFILE, use that flag to create a more + ** secure temporary file that cannot be accessed by other processes + */ + zName = unixTempFileDir(); + if( zName + && (fd = robust_open(zName, O_RDWR|O_EXCL|O_TMPFILE, 0600))>=0 + ){ + rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags|UNIXFILE_NOLOCK); + goto open_finished; + } +#endif rc = unixGetTempname(pVfs->mxPathname, zTmpname); if( rc!=SQLITE_OK ){ return rc; @@ -44958,8 +47467,11 @@ static int unixOpen( } #endif - assert( zPath==0 || zPath[0]=='/' - || eType==SQLITE_OPEN_SUPER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL + assert( zPath==0 + || zPath[0]=='/' + || eType==SQLITE_OPEN_SUPER_JOURNAL + || eType==SQLITE_OPEN_MAIN_JOURNAL + || eType==SQLITE_OPEN_TEMP_JOURNAL ); rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); @@ -45297,7 +47809,7 @@ static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){ /* Almost all modern unix systems support nanosleep(). But if you are ** compiling for one of the rare exceptions, you can use - ** -DHAVE_NANOSLEEP=0 (perhaps in conjuction with -DHAVE_USLEEP if + ** -DHAVE_NANOSLEEP=0 (perhaps in conjunction with -DHAVE_USLEEP if ** usleep() is available) in order to bypass the use of nanosleep() */ nanosleep(&sp, NULL); @@ -46688,6 +49200,9 @@ SQLITE_API int sqlite3_os_init(void){ sqlite3KvvfsInit(); #endif unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1); +#if OS_VXWORKS + vxworksMutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS2); +#endif #ifndef SQLITE_OMIT_WAL /* Validate lock assumptions */ @@ -46707,9 +49222,6 @@ SQLITE_API int sqlite3_os_init(void){ assert( UNIX_SHM_DMS==128 ); /* Byte offset of the deadman-switch */ #endif - /* Initialize temp file dir array. */ - unixTempFileInit(); - return SQLITE_OK; } @@ -46722,6 +49234,9 @@ SQLITE_API int sqlite3_os_init(void){ */ SQLITE_API int sqlite3_os_end(void){ unixBigLock = 0; +#if OS_VXWORKS + vxworksMutex = 0; +#endif return SQLITE_OK; } @@ -46756,86 +49271,6 @@ SQLITE_API int sqlite3_os_end(void){ */ /* #include "os_win.h" */ -/* -** Compiling and using WAL mode requires several APIs that are only -** available in Windows platforms based on the NT kernel. -*/ -#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL) -# error "WAL mode requires support from the Windows NT kernel, compile\ - with SQLITE_OMIT_WAL." -#endif - -#if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0 -# error "Memory mapped files require support from the Windows NT kernel,\ - compile with SQLITE_MAX_MMAP_SIZE=0." -#endif - -/* -** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions -** based on the sub-platform)? -*/ -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI) -# define SQLITE_WIN32_HAS_ANSI -#endif - -/* -** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions -** based on the sub-platform)? -*/ -#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \ - !defined(SQLITE_WIN32_NO_WIDE) -# define SQLITE_WIN32_HAS_WIDE -#endif - -/* -** Make sure at least one set of Win32 APIs is available. -*/ -#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE) -# error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\ - must be defined." -#endif - -/* -** Define the required Windows SDK version constants if they are not -** already available. -*/ -#ifndef NTDDI_WIN8 -# define NTDDI_WIN8 0x06020000 -#endif - -#ifndef NTDDI_WINBLUE -# define NTDDI_WINBLUE 0x06030000 -#endif - -#ifndef NTDDI_WINTHRESHOLD -# define NTDDI_WINTHRESHOLD 0x06040000 -#endif - -/* -** Check to see if the GetVersionEx[AW] functions are deprecated on the -** target system. GetVersionEx was first deprecated in Win8.1. -*/ -#ifndef SQLITE_WIN32_GETVERSIONEX -# if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE -# define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */ -# else -# define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */ -# endif -#endif - -/* -** Check to see if the CreateFileMappingA function is supported on the -** target system. It is unavailable when using "mincore.lib" on Win10. -** When compiling for Windows 10, always assume "mincore.lib" is in use. -*/ -#ifndef SQLITE_WIN32_CREATEFILEMAPPINGA -# if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD -# define SQLITE_WIN32_CREATEFILEMAPPINGA 0 -# else -# define SQLITE_WIN32_CREATEFILEMAPPINGA 1 -# endif -#endif - /* ** This constant should already be defined (in the "WinDef.h" SDK file). */ @@ -46915,45 +49350,7 @@ SQLITE_API int sqlite3_os_end(void){ #endif /* -** Do we need to manually define the Win32 file mapping APIs for use with WAL -** mode or memory mapped files (e.g. these APIs are available in the Windows -** CE SDK; however, they are not present in the header file)? -*/ -#if SQLITE_WIN32_FILEMAPPING_API && \ - (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) -/* -** Two of the file mapping APIs are different under WinRT. Figure out which -** set we need. -*/ -#if SQLITE_OS_WINRT -WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \ - LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR); - -WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T); -#else -#if defined(SQLITE_WIN32_HAS_ANSI) -WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \ - DWORD, DWORD, DWORD, LPCSTR); -#endif /* defined(SQLITE_WIN32_HAS_ANSI) */ - -#if defined(SQLITE_WIN32_HAS_WIDE) -WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \ - DWORD, DWORD, DWORD, LPCWSTR); -#endif /* defined(SQLITE_WIN32_HAS_WIDE) */ - -WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T); -#endif /* SQLITE_OS_WINRT */ - -/* -** These file mapping APIs are common to both Win32 and WinRT. -*/ - -WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T); -WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID); -#endif /* SQLITE_WIN32_FILEMAPPING_API */ - -/* -** Some Microsoft compilers lack this definition. +** Some older Microsoft compilers lack the following definition. */ #ifndef INVALID_FILE_ATTRIBUTES # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) @@ -46973,19 +49370,6 @@ typedef struct winShm winShm; /* A connection to shared-memory */ typedef struct winShmNode winShmNode; /* A region of shared-memory */ #endif -/* -** WinCE lacks native support for file locking so we have to fake it -** with some code of our own. -*/ -#if SQLITE_OS_WINCE -typedef struct winceLock { - int nReaders; /* Number of reader locks obtained */ - BOOL bPending; /* Indicates a pending lock has been obtained */ - BOOL bReserved; /* Indicates a reserved lock has been obtained */ - BOOL bExclusive; /* Indicates an exclusive lock has been obtained */ -} winceLock; -#endif - /* ** The winFile structure is a subclass of sqlite3_file* specific to the win32 ** portability layer. @@ -47004,13 +49388,6 @@ struct winFile { #endif const char *zPath; /* Full pathname of this file */ int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */ -#if SQLITE_OS_WINCE - LPWSTR zDeleteOnClose; /* Name of file to delete when closing */ - HANDLE hMutex; /* Mutex used to control access to shared lock */ - HANDLE hShared; /* Shared memory segment used for locking */ - winceLock local; /* Locks obtained by this instance of winFile */ - winceLock *shared; /* Global shared lock memory for the file */ -#endif #if SQLITE_MAX_MMAP_SIZE>0 int nFetchOut; /* Number of outstanding xFetch references */ HANDLE hMap; /* Handle for accessing memory mapping */ @@ -47018,8 +49395,18 @@ struct winFile { sqlite3_int64 mmapSize; /* Size of mapped region */ sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */ #endif +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + DWORD iBusyTimeout; /* Wait this many millisec on locks */ + int bBlockOnConnect; +#endif }; +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT +# define winFileBusyTimeout(pDbFd) pDbFd->iBusyTimeout +#else +# define winFileBusyTimeout(pDbFd) 0 +#endif + /* ** The winVfsAppData structure is used for the pAppData member for all of the ** Win32 VFS variants. @@ -47197,36 +49584,10 @@ static void winMemShutdown(void *pAppData); SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void); #endif /* SQLITE_WIN32_MALLOC */ -/* -** The following variable is (normally) set once and never changes -** thereafter. It records whether the operating system is Win9x -** or WinNT. -** -** 0: Operating system unknown. -** 1: Operating system is Win9x. -** 2: Operating system is WinNT. -** -** In order to facilitate testing on a WinNT system, the test fixture -** can manually set this value to 1 to emulate Win98 behavior. -*/ -#ifdef SQLITE_TEST -SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0; -#else -static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0; -#endif - #ifndef SYSCALL # define SYSCALL sqlite3_syscall_ptr #endif -/* -** This function is not available on Windows CE or WinRT. - */ - -#if SQLITE_OS_WINCE || SQLITE_OS_WINRT -# define osAreFileApisANSI() 1 -#endif - /* ** Many system calls are accessed through pointer-to-functions so that ** they may be overridden at runtime to facilitate fault injection during @@ -47238,653 +49599,344 @@ static struct win_syscall { sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ sqlite3_syscall_ptr pDefault; /* Default value */ } aSyscall[] = { -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 }, -#else - { "AreFileApisANSI", (SYSCALL)0, 0 }, -#endif - -#ifndef osAreFileApisANSI #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent) -#endif - -#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE) - { "CharLowerW", (SYSCALL)CharLowerW, 0 }, -#else - { "CharLowerW", (SYSCALL)0, 0 }, -#endif - -#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent) - -#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE) - { "CharUpperW", (SYSCALL)CharUpperW, 0 }, -#else - { "CharUpperW", (SYSCALL)0, 0 }, -#endif - -#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent) { "CloseHandle", (SYSCALL)CloseHandle, 0 }, +#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[1].pCurrent) -#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent) -#if defined(SQLITE_WIN32_HAS_ANSI) - { "CreateFileA", (SYSCALL)CreateFileA, 0 }, -#else - { "CreateFileA", (SYSCALL)0, 0 }, -#endif - -#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \ - LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent) - -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "CreateFileW", (SYSCALL)CreateFileW, 0 }, -#else - { "CreateFileW", (SYSCALL)0, 0 }, -#endif - #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \ - LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent) + LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[2].pCurrent) -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \ - (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \ - SQLITE_WIN32_CREATEFILEMAPPINGA - { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 }, +#if defined(SQLITE_UWP) + { "CreateFileMappingFromApp",(SYSCALL)CreateFileMappingFromApp,0 }, #else - { "CreateFileMappingA", (SYSCALL)0, 0 }, + { "CreateFileMappingFromApp",(SYSCALL)0, 0 }, #endif +#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE,\ + PSECURITY_ATTRIBUTES, \ + ULONG,ULONG64,PCWSTR))aSyscall[3].pCurrent) -#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \ - DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent) - -#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ - (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)) +#if !defined(SQLITE_UWP) { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 }, #else { "CreateFileMappingW", (SYSCALL)0, 0 }, #endif - #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \ - DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent) - -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) - { "CreateMutexW", (SYSCALL)CreateMutexW, 0 }, -#else - { "CreateMutexW", (SYSCALL)0, 0 }, -#endif - -#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \ - LPCWSTR))aSyscall[8].pCurrent) - -#if defined(SQLITE_WIN32_HAS_ANSI) - { "DeleteFileA", (SYSCALL)DeleteFileA, 0 }, -#else - { "DeleteFileA", (SYSCALL)0, 0 }, -#endif - -#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent) + DWORD,DWORD,DWORD,LPCWSTR))aSyscall[4].pCurrent) -#if defined(SQLITE_WIN32_HAS_WIDE) { "DeleteFileW", (SYSCALL)DeleteFileW, 0 }, -#else - { "DeleteFileW", (SYSCALL)0, 0 }, -#endif - -#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent) - -#if SQLITE_OS_WINCE - { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 }, -#else - { "FileTimeToLocalFileTime", (SYSCALL)0, 0 }, -#endif - -#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \ - LPFILETIME))aSyscall[11].pCurrent) - -#if SQLITE_OS_WINCE - { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 }, -#else - { "FileTimeToSystemTime", (SYSCALL)0, 0 }, -#endif - -#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \ - LPSYSTEMTIME))aSyscall[12].pCurrent) +#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[5].pCurrent) { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 }, +#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[6].pCurrent) -#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent) - -#if defined(SQLITE_WIN32_HAS_ANSI) - { "FormatMessageA", (SYSCALL)FormatMessageA, 0 }, -#else - { "FormatMessageA", (SYSCALL)0, 0 }, -#endif - -#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \ - DWORD,va_list*))aSyscall[14].pCurrent) - -#if defined(SQLITE_WIN32_HAS_WIDE) { "FormatMessageW", (SYSCALL)FormatMessageW, 0 }, -#else - { "FormatMessageW", (SYSCALL)0, 0 }, -#endif - #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \ - DWORD,va_list*))aSyscall[15].pCurrent) + DWORD,va_list*))aSyscall[7].pCurrent) -#if !defined(SQLITE_OMIT_LOAD_EXTENSION) +#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_UWP) { "FreeLibrary", (SYSCALL)FreeLibrary, 0 }, #else { "FreeLibrary", (SYSCALL)0, 0 }, #endif -#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent) +#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[8].pCurrent) { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 }, +#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[9].pCurrent) -#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent) - -#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI) - { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 }, -#else - { "GetDiskFreeSpaceA", (SYSCALL)0, 0 }, -#endif - -#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \ - LPDWORD))aSyscall[18].pCurrent) - -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) - { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 }, -#else - { "GetDiskFreeSpaceW", (SYSCALL)0, 0 }, -#endif - -#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \ - LPDWORD))aSyscall[19].pCurrent) - -#if defined(SQLITE_WIN32_HAS_ANSI) - { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 }, -#else - { "GetFileAttributesA", (SYSCALL)0, 0 }, -#endif - -#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent) - -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 }, -#else - { "GetFileAttributesW", (SYSCALL)0, 0 }, -#endif - -#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent) +#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent) -#if defined(SQLITE_WIN32_HAS_WIDE) { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 }, -#else - { "GetFileAttributesExW", (SYSCALL)0, 0 }, -#endif - #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \ - LPVOID))aSyscall[22].pCurrent) + LPVOID))aSyscall[11].pCurrent) -#if !SQLITE_OS_WINRT - { "GetFileSize", (SYSCALL)GetFileSize, 0 }, -#else - { "GetFileSize", (SYSCALL)0, 0 }, -#endif - -#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent) - -#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI) - { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 }, -#else - { "GetFullPathNameA", (SYSCALL)0, 0 }, -#endif + { "GetFileSizeEx", (SYSCALL)GetFileSizeEx, 0 }, +#define osGetFileSizeEx ((BOOL(WINAPI*)(HANDLE, \ + PLARGE_INTEGER))aSyscall[12].pCurrent) -#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \ - LPSTR*))aSyscall[24].pCurrent) - -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 }, -#else - { "GetFullPathNameW", (SYSCALL)0, 0 }, -#endif - #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \ - LPWSTR*))aSyscall[25].pCurrent) + LPWSTR*))aSyscall[13].pCurrent) { "GetLastError", (SYSCALL)GetLastError, 0 }, +#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[14].pCurrent) -#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent) - -#if !defined(SQLITE_OMIT_LOAD_EXTENSION) -#if SQLITE_OS_WINCE - /* The GetProcAddressA() routine is only available on Windows CE. */ - { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 }, -#else - /* All other Windows platforms expect GetProcAddress() to take - ** an ANSI string regardless of the _UNICODE setting */ +#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_UWP) { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 }, -#endif #else { "GetProcAddressA", (SYSCALL)0, 0 }, #endif - #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \ - LPCSTR))aSyscall[27].pCurrent) + LPCSTR))aSyscall[15].pCurrent) -#if !SQLITE_OS_WINRT { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 }, -#else - { "GetSystemInfo", (SYSCALL)0, 0 }, -#endif +#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[16].pCurrent) -#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent) - - { "GetSystemTime", (SYSCALL)GetSystemTime, 0 }, - -#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent) - -#if !SQLITE_OS_WINCE { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 }, -#else - { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 }, -#endif - #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \ - LPFILETIME))aSyscall[30].pCurrent) - -#if defined(SQLITE_WIN32_HAS_ANSI) - { "GetTempPathA", (SYSCALL)GetTempPathA, 0 }, -#else - { "GetTempPathA", (SYSCALL)0, 0 }, -#endif - -#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent) + LPFILETIME))aSyscall[17].pCurrent) -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) - { "GetTempPathW", (SYSCALL)GetTempPathW, 0 }, -#else +#ifdef SQLITE_UWP { "GetTempPathW", (SYSCALL)0, 0 }, -#endif - -#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent) - -#if !SQLITE_OS_WINRT - { "GetTickCount", (SYSCALL)GetTickCount, 0 }, -#else - { "GetTickCount", (SYSCALL)0, 0 }, -#endif - -#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent) - -#if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX - { "GetVersionExA", (SYSCALL)GetVersionExA, 0 }, #else - { "GetVersionExA", (SYSCALL)0, 0 }, + { "GetTempPathW", (SYSCALL)GetTempPathW, 0 }, #endif +#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[18].pCurrent) -#define osGetVersionExA ((BOOL(WINAPI*)( \ - LPOSVERSIONINFOA))aSyscall[34].pCurrent) + { "GetTickCount64", (SYSCALL)GetTickCount64, 0 }, +#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[19].pCurrent) -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ - SQLITE_WIN32_GETVERSIONEX - { "GetVersionExW", (SYSCALL)GetVersionExW, 0 }, +#ifdef SQLITE_UWP + { "HeapAlloc", (SYSCALL)0, 0 }, #else - { "GetVersionExW", (SYSCALL)0, 0 }, -#endif - -#define osGetVersionExW ((BOOL(WINAPI*)( \ - LPOSVERSIONINFOW))aSyscall[35].pCurrent) - { "HeapAlloc", (SYSCALL)HeapAlloc, 0 }, - +#endif #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \ - SIZE_T))aSyscall[36].pCurrent) + SIZE_T))aSyscall[20].pCurrent) -#if !SQLITE_OS_WINRT - { "HeapCreate", (SYSCALL)HeapCreate, 0 }, -#else +#ifdef SQLITE_UWP { "HeapCreate", (SYSCALL)0, 0 }, +#else + { "HeapCreate", (SYSCALL)HeapCreate, 0 }, #endif - #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \ - SIZE_T))aSyscall[37].pCurrent) + SIZE_T))aSyscall[21].pCurrent) -#if !SQLITE_OS_WINRT - { "HeapDestroy", (SYSCALL)HeapDestroy, 0 }, -#else +#ifdef SQLITE_UWP { "HeapDestroy", (SYSCALL)0, 0 }, +#else + { "HeapDestroy", (SYSCALL)HeapDestroy, 0 }, #endif +#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[22].pCurrent) -#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent) - +#ifdef SQLITE_UWP + { "HeapFree", (SYSCALL)0, 0 }, +#else { "HeapFree", (SYSCALL)HeapFree, 0 }, +#endif +#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[23].pCurrent) -#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent) - +#ifdef SQLITE_UWP + { "HeapReAlloc", (SYSCALL)0, 0 }, +#else { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 }, - +#endif #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \ - SIZE_T))aSyscall[40].pCurrent) + SIZE_T))aSyscall[24].pCurrent) +#ifdef SQLITE_UWP + { "HeapSize", (SYSCALL)0, 0 }, +#else { "HeapSize", (SYSCALL)HeapSize, 0 }, - +#endif #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \ - LPCVOID))aSyscall[41].pCurrent) + LPCVOID))aSyscall[25].pCurrent) -#if !SQLITE_OS_WINRT - { "HeapValidate", (SYSCALL)HeapValidate, 0 }, -#else +#ifdef SQLITE_UWP { "HeapValidate", (SYSCALL)0, 0 }, +#else + { "HeapValidate", (SYSCALL)HeapValidate, 0 }, #endif - #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \ - LPCVOID))aSyscall[42].pCurrent) + LPCVOID))aSyscall[26].pCurrent) -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT - { "HeapCompact", (SYSCALL)HeapCompact, 0 }, -#else +#ifdef SQLITE_UWP { "HeapCompact", (SYSCALL)0, 0 }, -#endif - -#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent) - -#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION) - { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 }, #else - { "LoadLibraryA", (SYSCALL)0, 0 }, + { "HeapCompact", (SYSCALL)HeapCompact, 0 }, #endif +#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[27].pCurrent) -#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent) -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \ - !defined(SQLITE_OMIT_LOAD_EXTENSION) +#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_UWP) { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 }, #else { "LoadLibraryW", (SYSCALL)0, 0 }, #endif +#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[28].pCurrent) -#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent) - -#if !SQLITE_OS_WINRT { "LocalFree", (SYSCALL)LocalFree, 0 }, -#else - { "LocalFree", (SYSCALL)0, 0 }, -#endif - -#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent) +#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[29].pCurrent) -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT - { "LockFile", (SYSCALL)LockFile, 0 }, -#else - { "LockFile", (SYSCALL)0, 0 }, -#endif - -#ifndef osLockFile -#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ - DWORD))aSyscall[47].pCurrent) -#endif - -#if !SQLITE_OS_WINCE { "LockFileEx", (SYSCALL)LockFileEx, 0 }, -#else - { "LockFileEx", (SYSCALL)0, 0 }, -#endif - -#ifndef osLockFileEx #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \ - LPOVERLAPPED))aSyscall[48].pCurrent) -#endif + LPOVERLAPPED))aSyscall[30].pCurrent) -#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \ - (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)) +#if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \ + && !defined(SQLITE_UWP) { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 }, #else { "MapViewOfFile", (SYSCALL)0, 0 }, #endif - #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ - SIZE_T))aSyscall[49].pCurrent) + SIZE_T))aSyscall[31].pCurrent) - { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 }, +#if (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) \ + && defined(SQLITE_UWP) + { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 }, +#else + { "MapViewOfFileFromApp", (SYSCALL)0, 0 }, +#endif +#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \ + SIZE_T))aSyscall[32].pCurrent) + { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 }, #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \ - int))aSyscall[50].pCurrent) + int))aSyscall[33].pCurrent) { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 }, - #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \ - LARGE_INTEGER*))aSyscall[51].pCurrent) + LARGE_INTEGER*))aSyscall[34].pCurrent) { "ReadFile", (SYSCALL)ReadFile, 0 }, - #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \ - LPOVERLAPPED))aSyscall[52].pCurrent) + LPOVERLAPPED))aSyscall[35].pCurrent) { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 }, +#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[36].pCurrent) -#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent) - -#if !SQLITE_OS_WINRT - { "SetFilePointer", (SYSCALL)SetFilePointer, 0 }, -#else - { "SetFilePointer", (SYSCALL)0, 0 }, -#endif - -#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \ - DWORD))aSyscall[54].pCurrent) + { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 }, +#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER,\ + PLARGE_INTEGER,DWORD))aSyscall[37].pCurrent) -#if !SQLITE_OS_WINRT { "Sleep", (SYSCALL)Sleep, 0 }, -#else - { "Sleep", (SYSCALL)0, 0 }, -#endif - -#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent) - - { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 }, - -#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \ - LPFILETIME))aSyscall[56].pCurrent) - -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT - { "UnlockFile", (SYSCALL)UnlockFile, 0 }, -#else - { "UnlockFile", (SYSCALL)0, 0 }, -#endif +#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[38].pCurrent) -#ifndef osUnlockFile -#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ - DWORD))aSyscall[57].pCurrent) -#endif - -#if !SQLITE_OS_WINCE { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 }, -#else - { "UnlockFileEx", (SYSCALL)0, 0 }, -#endif - #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \ - LPOVERLAPPED))aSyscall[58].pCurrent) + LPOVERLAPPED))aSyscall[39].pCurrent) -#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 +#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 }, #else { "UnmapViewOfFile", (SYSCALL)0, 0 }, #endif - -#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent) +#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[40].pCurrent) { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 }, - #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \ - LPCSTR,LPBOOL))aSyscall[60].pCurrent) + LPCSTR,LPBOOL))aSyscall[41].pCurrent) { "WriteFile", (SYSCALL)WriteFile, 0 }, - #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \ - LPOVERLAPPED))aSyscall[61].pCurrent) - -#if SQLITE_OS_WINRT - { "CreateEventExW", (SYSCALL)CreateEventExW, 0 }, -#else - { "CreateEventExW", (SYSCALL)0, 0 }, -#endif - -#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \ - DWORD,DWORD))aSyscall[62].pCurrent) + LPOVERLAPPED))aSyscall[42].pCurrent) -#if !SQLITE_OS_WINRT { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 }, -#else - { "WaitForSingleObject", (SYSCALL)0, 0 }, -#endif - #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \ - DWORD))aSyscall[63].pCurrent) + DWORD))aSyscall[43].pCurrent) -#if !SQLITE_OS_WINCE { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 }, -#else - { "WaitForSingleObjectEx", (SYSCALL)0, 0 }, -#endif - #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \ - BOOL))aSyscall[64].pCurrent) + BOOL))aSyscall[44].pCurrent) -#if SQLITE_OS_WINRT - { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 }, -#else - { "SetFilePointerEx", (SYSCALL)0, 0 }, -#endif + { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 }, +#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[45].pCurrent) -#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \ - PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent) + { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 }, +#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[46].pCurrent) -#if SQLITE_OS_WINRT - { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 }, +/* +** NOTE: On some sub-platforms, the InterlockedCompareExchange "function" +** is really just a macro that uses a compiler intrinsic (e.g. x64). +** So do not try to make this is into a redefinable interface. +*/ +#if defined(InterlockedCompareExchange) + { "InterlockedCompareExchange", (SYSCALL)0, 0 }, +#define osInterlockedCompareExchange InterlockedCompareExchange #else - { "GetFileInformationByHandleEx", (SYSCALL)0, 0 }, -#endif - -#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \ - FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent) + { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 }, +#define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG volatile*,\ + LONG,LONG))aSyscall[47].pCurrent) +#endif /* defined(InterlockedCompareExchange) */ -#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) - { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 }, +#if SQLITE_WIN32_USE_UUID + { "UuidCreate", (SYSCALL)UuidCreate, 0 }, #else - { "MapViewOfFileFromApp", (SYSCALL)0, 0 }, + { "UuidCreate", (SYSCALL)0, 0 }, #endif +#define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[48].pCurrent) -#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \ - SIZE_T))aSyscall[67].pCurrent) - -#if SQLITE_OS_WINRT - { "CreateFile2", (SYSCALL)CreateFile2, 0 }, +#if SQLITE_WIN32_USE_UUID + { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 }, #else - { "CreateFile2", (SYSCALL)0, 0 }, + { "UuidCreateSequential", (SYSCALL)0, 0 }, #endif +#define osUuidCreateSequential \ + ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[49].pCurrent) -#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \ - LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent) - -#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION) - { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 }, +#if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0 + { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 }, #else - { "LoadPackagedLibrary", (SYSCALL)0, 0 }, + { "FlushViewOfFile", (SYSCALL)0, 0 }, #endif +#define osFlushViewOfFile \ + ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[50].pCurrent) -#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \ - DWORD))aSyscall[69].pCurrent) - -#if SQLITE_OS_WINRT - { "GetTickCount64", (SYSCALL)GetTickCount64, 0 }, +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + { "CreateEvent", (SYSCALL)CreateEvent, 0 }, #else - { "GetTickCount64", (SYSCALL)0, 0 }, + { "CreateEvent", (SYSCALL)0, 0 }, #endif +#define osCreateEvent ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \ + BOOL,LPCSTR))aSyscall[51].pCurrent) -#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent) - -#if SQLITE_OS_WINRT - { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 }, +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + { "CancelIo", (SYSCALL)CancelIo, 0 }, #else - { "GetNativeSystemInfo", (SYSCALL)0, 0 }, + { "CancelIo", (SYSCALL)0, 0 }, #endif +#define osCancelIo ((BOOL(WINAPI*)(HANDLE))aSyscall[52].pCurrent) -#define osGetNativeSystemInfo ((VOID(WINAPI*)( \ - LPSYSTEM_INFO))aSyscall[71].pCurrent) - -#if defined(SQLITE_WIN32_HAS_ANSI) - { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 }, +#ifndef _WIN32 + { "getenv", (SYSCALL)getenv, 0 }, #else - { "OutputDebugStringA", (SYSCALL)0, 0 }, + { "getenv", (SYSCALL)0, 0 }, #endif +#define osGetenv ((const char *(*)(const char *))aSyscall[53].pCurrent) -#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent) - -#if defined(SQLITE_WIN32_HAS_WIDE) - { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 }, +#ifndef _WIN32 + { "getcwd", (SYSCALL)getcwd, 0 }, #else - { "OutputDebugStringW", (SYSCALL)0, 0 }, + { "getcwd", (SYSCALL)0, 0 }, #endif +#define osGetcwd ((char*(*)(char*,size_t))aSyscall[54].pCurrent) -#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent) - - { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 }, - -#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent) - -#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) - { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 }, +#ifndef _WIN32 + { "readlink", (SYSCALL)readlink, 0 }, #else - { "CreateFileMappingFromApp", (SYSCALL)0, 0 }, + { "readlink", (SYSCALL)0, 0 }, #endif +#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[55].pCurrent) -#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \ - LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent) - -/* -** NOTE: On some sub-platforms, the InterlockedCompareExchange "function" -** is really just a macro that uses a compiler intrinsic (e.g. x64). -** So do not try to make this is into a redefinable interface. -*/ -#if defined(InterlockedCompareExchange) - { "InterlockedCompareExchange", (SYSCALL)0, 0 }, - -#define osInterlockedCompareExchange InterlockedCompareExchange -#else - { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 }, - -#define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \ - SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent) -#endif /* defined(InterlockedCompareExchange) */ - -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID - { "UuidCreate", (SYSCALL)UuidCreate, 0 }, +#ifndef _WIN32 + { "lstat", (SYSCALL)lstat, 0 }, #else - { "UuidCreate", (SYSCALL)0, 0 }, + { "lstat", (SYSCALL)0, 0 }, #endif +#define osLstat ((int(*)(const char*,struct stat*))aSyscall[56].pCurrent) -#define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent) - -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID - { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 }, +#ifndef _WIN32 + { "__errno", (SYSCALL)__errno, 0 }, #else - { "UuidCreateSequential", (SYSCALL)0, 0 }, + { "__errno", (SYSCALL)0, 0 }, #endif +#define osErrno (*((int*(*)(void))aSyscall[57].pCurrent)()) -#define osUuidCreateSequential \ - ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent) - -#if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0 - { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 }, +#ifndef _WIN32 + { "cygwin_conv_path", (SYSCALL)cygwin_conv_path, 0 }, #else - { "FlushViewOfFile", (SYSCALL)0, 0 }, + { "cygwin_conv_path", (SYSCALL)0, 0 }, #endif +#define osCygwin_conv_path ((size_t(*)(unsigned int, \ + const void *, void *, size_t))aSyscall[58].pCurrent) -#define osFlushViewOfFile \ - ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent) + { "GetDriveTypeW", (SYSCALL)GetDriveTypeW, 0 }, +#define osGetDriveTypeW ((UINT(WINAPI*)(LPCWSTR))aSyscall[59].pCurrent) }; /* End of the overrideable system calls */ @@ -47972,6 +50024,9 @@ static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){ } #ifdef SQLITE_WIN32_MALLOC +#ifdef SQLITE_UWP +# error SQLITE_WIN32_MALLOC is incompatible with SQLITE_UWP +#endif /* ** If a Win32 native heap has been configured, this function will attempt to ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one @@ -47988,10 +50043,9 @@ SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){ hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) +#if defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); #endif -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){ DWORD lastErrno = osGetLastError(); if( lastErrno==NO_ERROR ){ @@ -48004,11 +50058,6 @@ SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){ rc = SQLITE_ERROR; } } -#else - sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p", - (void*)hHeap); - rc = SQLITE_NOTFOUND; -#endif if( pnLargest ) *pnLargest = nLargest; return rc; } @@ -48059,11 +50108,11 @@ SQLITE_API int sqlite3_win32_reset_heap(){ } #endif /* SQLITE_WIN32_MALLOC */ +#ifdef _WIN32 /* ** This function outputs the specified (ANSI) string to the Win32 debugger -** (if available). +** (if available). Undocumented. Might go away at any moment. */ - SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){ char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE]; int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */ @@ -48075,7 +50124,6 @@ SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){ return; } #endif -#if defined(SQLITE_WIN32_HAS_ANSI) if( nMin>0 ){ memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); memcpy(zDbgBuf, zBuf, nMin); @@ -48083,48 +50131,13 @@ SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){ }else{ osOutputDebugStringA(zBuf); } -#elif defined(SQLITE_WIN32_HAS_WIDE) - memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); - if ( osMultiByteToWideChar( - osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf, - nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){ - return; - } - osOutputDebugStringW((LPCWSTR)zDbgBuf); -#else - if( nMin>0 ){ - memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE); - memcpy(zDbgBuf, zBuf, nMin); - fprintf(stderr, "%s", zDbgBuf); - }else{ - fprintf(stderr, "%s", zBuf); - } -#endif } -/* -** The following routine suspends the current thread for at least ms -** milliseconds. This is equivalent to the Win32 Sleep() interface. -*/ -#if SQLITE_OS_WINRT -static HANDLE sleepObj = NULL; -#endif - SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){ -#if SQLITE_OS_WINRT - if ( sleepObj==NULL ){ - sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET, - SYNCHRONIZE); - } - assert( sleepObj!=NULL ); - osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE); -#else osSleep(milliseconds); -#endif } -#if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \ - SQLITE_THREADSAFE>0 +#if SQLITE_MAX_WORKER_THREADS>0 && SQLITE_THREADSAFE>0 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){ DWORD rc; while( (rc = osWaitForSingleObjectEx(hObject, INFINITE, @@ -48132,67 +50145,7 @@ SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){ return rc; } #endif - -/* -** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, -** or WinCE. Return false (zero) for Win95, Win98, or WinME. -** -** Here is an interesting observation: Win95, Win98, and WinME lack -** the LockFileEx() API. But we can still statically link against that -** API as long as we don't call it when running Win95/98/ME. A call to -** this routine is used to determine if the host is Win95/98/ME or -** WinNT/2K/XP so that we will know whether or not we can safely call -** the LockFileEx() API. -*/ - -#if !SQLITE_WIN32_GETVERSIONEX -# define osIsNT() (1) -#elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI) -# define osIsNT() (1) -#elif !defined(SQLITE_WIN32_HAS_WIDE) -# define osIsNT() (0) -#else -# define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt()) -#endif - -/* -** This function determines if the machine is running a version of Windows -** based on the NT kernel. -*/ -SQLITE_API int sqlite3_win32_is_nt(void){ -#if SQLITE_OS_WINRT - /* - ** NOTE: The WinRT sub-platform is always assumed to be based on the NT - ** kernel. - */ - return 1; -#elif SQLITE_WIN32_GETVERSIONEX - if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){ -#if defined(SQLITE_WIN32_HAS_ANSI) - OSVERSIONINFOA sInfo; - sInfo.dwOSVersionInfoSize = sizeof(sInfo); - osGetVersionExA(&sInfo); - osInterlockedCompareExchange(&sqlite3_os_type, - (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0); -#elif defined(SQLITE_WIN32_HAS_WIDE) - OSVERSIONINFOW sInfo; - sInfo.dwOSVersionInfoSize = sizeof(sInfo); - osGetVersionExW(&sInfo); - osInterlockedCompareExchange(&sqlite3_os_type, - (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0); -#endif - } - return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2; -#elif SQLITE_TEST - return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2; -#else - /* - ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are - ** deprecated are always assumed to be based on the NT kernel. - */ - return 1; -#endif -} +#endif /* _WIN32 */ #ifdef SQLITE_WIN32_MALLOC /* @@ -48206,7 +50159,7 @@ static void *winMemMalloc(int nBytes){ hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) +#if defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); #endif assert( nBytes>=0 ); @@ -48228,7 +50181,7 @@ static void winMemFree(void *pPrior){ hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) +#if defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); #endif if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */ @@ -48249,7 +50202,7 @@ static void *winMemRealloc(void *pPrior, int nBytes){ hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) +#if defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ); #endif assert( nBytes>=0 ); @@ -48277,7 +50230,7 @@ static int winMemSize(void *p){ hHeap = winMemGetHeap(); assert( hHeap!=0 ); assert( hHeap!=INVALID_HANDLE_VALUE ); -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) +#if defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) ); #endif if( !p ) return 0; @@ -48307,7 +50260,7 @@ static int winMemInit(void *pAppData){ assert( pWinMemData->magic1==WINMEM_MAGIC1 ); assert( pWinMemData->magic2==WINMEM_MAGIC2 ); -#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE +#if SQLITE_WIN32_HEAP_CREATE if( !pWinMemData->hHeap ){ DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE; DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap; @@ -48340,7 +50293,7 @@ static int winMemInit(void *pAppData){ #endif assert( pWinMemData->hHeap!=0 ); assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE ); -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) +#if defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); #endif return SQLITE_OK; @@ -48358,7 +50311,7 @@ static void winMemShutdown(void *pAppData){ if( pWinMemData->hHeap ){ assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE ); -#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE) +#if defined(SQLITE_WIN32_MALLOC_VALIDATE) assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); #endif if( pWinMemData->bOwned ){ @@ -48399,6 +50352,7 @@ SQLITE_PRIVATE void sqlite3MemSetDefault(void){ } #endif /* SQLITE_WIN32_MALLOC */ +#ifdef _WIN32 /* ** Convert a UTF-8 string to Microsoft Unicode. ** @@ -48424,6 +50378,7 @@ static LPWSTR winUtf8ToUnicode(const char *zText){ } return zWideText; } +#endif /* _WIN32 */ /* ** Convert a Microsoft Unicode string to UTF-8. @@ -48451,6 +50406,7 @@ static char *winUnicodeToUtf8(LPCWSTR zWideText){ return zText; } +#ifdef _WIN32 /* ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM ** code page. @@ -48458,22 +50414,22 @@ static char *winUnicodeToUtf8(LPCWSTR zWideText){ ** Space to hold the returned string is obtained from sqlite3_malloc(). */ static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){ - int nByte; + int nWideChar; LPWSTR zMbcsText; int codepage = useAnsi ? CP_ACP : CP_OEMCP; - nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL, - 0)*sizeof(WCHAR); - if( nByte==0 ){ + nWideChar = osMultiByteToWideChar(codepage, 0, zText, -1, NULL, + 0); + if( nWideChar==0 ){ return 0; } - zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) ); + zMbcsText = sqlite3MallocZero( nWideChar*sizeof(WCHAR) ); if( zMbcsText==0 ){ return 0; } - nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText, - nByte); - if( nByte==0 ){ + nWideChar = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText, + nWideChar); + if( nWideChar==0 ){ sqlite3_free(zMbcsText); zMbcsText = 0; } @@ -48716,6 +50672,7 @@ SQLITE_API int sqlite3_win32_set_directory( ){ return sqlite3_win32_set_directory16(type, zValue); } +#endif /* _WIN32 */ /* ** The return value of winGetLastErrorMsg @@ -48729,63 +50686,24 @@ static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){ */ DWORD dwLen = 0; char *zOut = 0; - - if( osIsNT() ){ -#if SQLITE_OS_WINRT - WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1]; - dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - lastErrno, - 0, - zTempWide, - SQLITE_WIN32_MAX_ERRMSG_CHARS, - 0); -#else - LPWSTR zTempWide = NULL; - dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - lastErrno, - 0, - (LPWSTR) &zTempWide, - 0, - 0); -#endif - if( dwLen > 0 ){ - /* allocate a buffer and convert to UTF8 */ - sqlite3BeginBenignMalloc(); - zOut = winUnicodeToUtf8(zTempWide); - sqlite3EndBenignMalloc(); -#if !SQLITE_OS_WINRT - /* free the system buffer allocated by FormatMessage */ - osLocalFree(zTempWide); -#endif - } - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - char *zTemp = NULL; - dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - lastErrno, - 0, - (LPSTR) &zTemp, - 0, - 0); - if( dwLen > 0 ){ - /* allocate a buffer and convert to UTF8 */ - sqlite3BeginBenignMalloc(); - zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI()); - sqlite3EndBenignMalloc(); - /* free the system buffer allocated by FormatMessage */ - osLocalFree(zTemp); - } + LPWSTR zTempWide = NULL; + dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + lastErrno, + 0, + (LPWSTR) &zTempWide, + 0, + 0); + if( dwLen > 0 ){ + /* allocate a buffer and convert to UTF8 */ + sqlite3BeginBenignMalloc(); + zOut = winUnicodeToUtf8(zTempWide); + sqlite3EndBenignMalloc(); + /* free the system buffer allocated by FormatMessage */ + osLocalFree(zTempWide); } -#endif if( 0 == dwLen ){ sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno); }else{ @@ -48892,13 +50810,13 @@ static int winRetryIoerr(int *pnRetry, DWORD *pError){ return 0; } if( winIoerrCanRetry1(e) ){ - sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry)); + osSleep(winIoerrRetryDelay*(1+*pnRetry)); ++*pnRetry; return 1; } #if defined(winIoerrCanRetry2) else if( winIoerrCanRetry2(e) ){ - sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry)); + osSleep(winIoerrRetryDelay*(1+*pnRetry)); ++*pnRetry; return 1; } @@ -48921,355 +50839,102 @@ static void winLogIoerr(int nRetry, int lineno){ } } -/* -** This #if does not rely on the SQLITE_OS_WINCE define because the -** corresponding section in "date.c" cannot use it. -*/ -#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \ - (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API) -/* -** The MSVC CRT on Windows CE may not have a localtime() function. -** So define a substitute. -*/ -/* # include <time.h> */ -struct tm *__cdecl localtime(const time_t *t) -{ - static struct tm y; - FILETIME uTm, lTm; - SYSTEMTIME pTm; - sqlite3_int64 t64; - t64 = *t; - t64 = (t64 + 11644473600)*10000000; - uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF); - uTm.dwHighDateTime= (DWORD)(t64 >> 32); - osFileTimeToLocalFileTime(&uTm,&lTm); - osFileTimeToSystemTime(&lTm,&pTm); - y.tm_year = pTm.wYear - 1900; - y.tm_mon = pTm.wMonth - 1; - y.tm_wday = pTm.wDayOfWeek; - y.tm_mday = pTm.wDay; - y.tm_hour = pTm.wHour; - y.tm_min = pTm.wMinute; - y.tm_sec = pTm.wSecond; - return &y; -} -#endif - -#if SQLITE_OS_WINCE -/************************************************************************* -** This section contains code for WinCE only. -*/ -#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)] - -/* -** Acquire a lock on the handle h -*/ -static void winceMutexAcquire(HANDLE h){ - DWORD dwErr; - do { - dwErr = osWaitForSingleObject(h, INFINITE); - } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED); -} -/* -** Release a lock acquired by winceMutexAcquire() -*/ -#define winceMutexRelease(h) ReleaseMutex(h) - -/* -** Create the mutex and shared memory used for locking in the file -** descriptor pFile -*/ -static int winceCreateLock(const char *zFilename, winFile *pFile){ - LPWSTR zTok; - LPWSTR zName; - DWORD lastErrno; - BOOL bLogged = FALSE; - BOOL bInit = TRUE; - - zName = winUtf8ToUnicode(zFilename); - if( zName==0 ){ - /* out of memory */ - return SQLITE_IOERR_NOMEM_BKPT; - } - - /* Initialize the local lockdata */ - memset(&pFile->local, 0, sizeof(pFile->local)); - - /* Replace the backslashes from the filename and lowercase it - ** to derive a mutex name. */ - zTok = osCharLowerW(zName); - for (;*zTok;zTok++){ - if (*zTok == '\\') *zTok = '_'; - } - - /* Create/open the named mutex */ - pFile->hMutex = osCreateMutexW(NULL, FALSE, zName); - if (!pFile->hMutex){ - pFile->lastErrno = osGetLastError(); - sqlite3_free(zName); - return winLogError(SQLITE_IOERR, pFile->lastErrno, - "winceCreateLock1", zFilename); - } - - /* Acquire the mutex before continuing */ - winceMutexAcquire(pFile->hMutex); - - /* Since the names of named mutexes, semaphores, file mappings etc are - ** case-sensitive, take advantage of that by uppercasing the mutex name - ** and using that as the shared filemapping name. - */ - osCharUpperW(zName); - pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL, - PAGE_READWRITE, 0, sizeof(winceLock), - zName); - - /* Set a flag that indicates we're the first to create the memory so it - ** must be zero-initialized */ - lastErrno = osGetLastError(); - if (lastErrno == ERROR_ALREADY_EXISTS){ - bInit = FALSE; - } - - sqlite3_free(zName); - - /* If we succeeded in making the shared memory handle, map it. */ - if( pFile->hShared ){ - pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, - FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock)); - /* If mapping failed, close the shared memory handle and erase it */ - if( !pFile->shared ){ - pFile->lastErrno = osGetLastError(); - winLogError(SQLITE_IOERR, pFile->lastErrno, - "winceCreateLock2", zFilename); - bLogged = TRUE; - osCloseHandle(pFile->hShared); - pFile->hShared = NULL; - } - } - - /* If shared memory could not be created, then close the mutex and fail */ - if( pFile->hShared==NULL ){ - if( !bLogged ){ - pFile->lastErrno = lastErrno; - winLogError(SQLITE_IOERR, pFile->lastErrno, - "winceCreateLock3", zFilename); - bLogged = TRUE; - } - winceMutexRelease(pFile->hMutex); - osCloseHandle(pFile->hMutex); - pFile->hMutex = NULL; - return SQLITE_IOERR; - } - - /* Initialize the shared memory if we're supposed to */ - if( bInit ){ - memset(pFile->shared, 0, sizeof(winceLock)); - } - - winceMutexRelease(pFile->hMutex); - return SQLITE_OK; -} /* -** Destroy the part of winFile that deals with wince locks +** Lock a file region. */ -static void winceDestroyLock(winFile *pFile){ - if (pFile->hMutex){ - /* Acquire the mutex */ - winceMutexAcquire(pFile->hMutex); - - /* The following blocks should probably assert in debug mode, but they - are to cleanup in case any locks remained open */ - if (pFile->local.nReaders){ - pFile->shared->nReaders --; - } - if (pFile->local.bReserved){ - pFile->shared->bReserved = FALSE; - } - if (pFile->local.bPending){ - pFile->shared->bPending = FALSE; - } - if (pFile->local.bExclusive){ - pFile->shared->bExclusive = FALSE; - } - - /* De-reference and close our copy of the shared memory handle */ - osUnmapViewOfFile(pFile->shared); - osCloseHandle(pFile->hShared); - - /* Done with the mutex */ - winceMutexRelease(pFile->hMutex); - osCloseHandle(pFile->hMutex); - pFile->hMutex = NULL; - } +static BOOL winLockFile( + LPHANDLE phFile, + DWORD flags, + DWORD offsetLow, + DWORD offsetHigh, + DWORD numBytesLow, + DWORD numBytesHigh +){ + OVERLAPPED ovlp; + memset(&ovlp, 0, sizeof(OVERLAPPED)); + ovlp.Offset = offsetLow; + ovlp.OffsetHigh = offsetHigh; + return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp); } +#ifndef SQLITE_OMIT_WAL /* -** An implementation of the LockFile() API of Windows for CE +** Lock a region of nByte bytes starting at offset offset of file hFile. +** Take an EXCLUSIVE lock if parameter bExclusive is true, or a SHARED lock +** otherwise. If nMs is greater than zero and the lock cannot be obtained +** immediately, block for that many ms before giving up. +** +** This function returns SQLITE_OK if the lock is obtained successfully. If +** some other process holds the lock, SQLITE_BUSY is returned if nMs==0, or +** SQLITE_BUSY_TIMEOUT otherwise. Or, if an error occurs, SQLITE_IOERR. */ -static BOOL winceLockFile( - LPHANDLE phFile, - DWORD dwFileOffsetLow, - DWORD dwFileOffsetHigh, - DWORD nNumberOfBytesToLockLow, - DWORD nNumberOfBytesToLockHigh +static int winHandleLockTimeout( + HANDLE hFile, + DWORD offset, + DWORD nByte, + int bExcl, + DWORD nMs ){ - winFile *pFile = HANDLE_TO_WINFILE(phFile); - BOOL bReturn = FALSE; - - UNUSED_PARAMETER(dwFileOffsetHigh); - UNUSED_PARAMETER(nNumberOfBytesToLockHigh); - - if (!pFile->hMutex) return TRUE; - winceMutexAcquire(pFile->hMutex); - - /* Wanting an exclusive lock? */ - if (dwFileOffsetLow == (DWORD)SHARED_FIRST - && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){ - if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){ - pFile->shared->bExclusive = TRUE; - pFile->local.bExclusive = TRUE; - bReturn = TRUE; - } - } - - /* Want a read-only lock? */ - else if (dwFileOffsetLow == (DWORD)SHARED_FIRST && - nNumberOfBytesToLockLow == 1){ - if (pFile->shared->bExclusive == 0){ - pFile->local.nReaders ++; - if (pFile->local.nReaders == 1){ - pFile->shared->nReaders ++; - } - bReturn = TRUE; - } - } + DWORD flags = LOCKFILE_FAIL_IMMEDIATELY | (bExcl?LOCKFILE_EXCLUSIVE_LOCK:0); + int rc = SQLITE_OK; + BOOL ret; + OVERLAPPED ovlp; + memset(&ovlp, 0, sizeof(OVERLAPPED)); + ovlp.Offset = offset; - /* Want a pending lock? */ - else if (dwFileOffsetLow == (DWORD)PENDING_BYTE - && nNumberOfBytesToLockLow == 1){ - /* If no pending lock has been acquired, then acquire it */ - if (pFile->shared->bPending == 0) { - pFile->shared->bPending = TRUE; - pFile->local.bPending = TRUE; - bReturn = TRUE; - } +#if defined(SQLITE_ENABLE_SETLK_TIMEOUT) + if( nMs!=0 ){ + flags &= ~LOCKFILE_FAIL_IMMEDIATELY; } - - /* Want a reserved lock? */ - else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE - && nNumberOfBytesToLockLow == 1){ - if (pFile->shared->bReserved == 0) { - pFile->shared->bReserved = TRUE; - pFile->local.bReserved = TRUE; - bReturn = TRUE; - } + ovlp.hEvent = osCreateEvent(NULL, TRUE, FALSE, NULL); + if( ovlp.hEvent==NULL ){ + return SQLITE_IOERR_LOCK; } - - winceMutexRelease(pFile->hMutex); - return bReturn; -} - -/* -** An implementation of the UnlockFile API of Windows for CE -*/ -static BOOL winceUnlockFile( - LPHANDLE phFile, - DWORD dwFileOffsetLow, - DWORD dwFileOffsetHigh, - DWORD nNumberOfBytesToUnlockLow, - DWORD nNumberOfBytesToUnlockHigh -){ - winFile *pFile = HANDLE_TO_WINFILE(phFile); - BOOL bReturn = FALSE; - - UNUSED_PARAMETER(dwFileOffsetHigh); - UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh); - - if (!pFile->hMutex) return TRUE; - winceMutexAcquire(pFile->hMutex); - - /* Releasing a reader lock or an exclusive lock */ - if (dwFileOffsetLow == (DWORD)SHARED_FIRST){ - /* Did we have an exclusive lock? */ - if (pFile->local.bExclusive){ - assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE); - pFile->local.bExclusive = FALSE; - pFile->shared->bExclusive = FALSE; - bReturn = TRUE; - } - - /* Did we just have a reader lock? */ - else if (pFile->local.nReaders){ - assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE - || nNumberOfBytesToUnlockLow == 1); - pFile->local.nReaders --; - if (pFile->local.nReaders == 0) - { - pFile->shared->nReaders --; - } - bReturn = TRUE; +#endif + ret = osLockFileEx(hFile, flags, 0, nByte, 0, &ovlp); +#if defined(SQLITE_ENABLE_SETLK_TIMEOUT) + /* If SQLITE_ENABLE_SETLK_TIMEOUT is defined, then the file-handle was + ** opened with FILE_FLAG_OVERHEAD specified. In this case, the call to + ** LockFileEx() may fail because the request is still pending. This can + ** happen even if LOCKFILE_FAIL_IMMEDIATELY was specified. + ** + ** If nMs is 0, then LOCKFILE_FAIL_IMMEDIATELY was set in the flags + ** passed to LockFileEx(). In this case, if the operation is pending, + ** block indefinitely until it is finished. + ** + ** Otherwise, wait for up to nMs ms for the operation to finish. nMs + ** may be set to INFINITE. + */ + if( !ret && GetLastError()==ERROR_IO_PENDING ){ + DWORD nDelay = (nMs==0 ? INFINITE : nMs); + DWORD res = osWaitForSingleObject(ovlp.hEvent, nDelay); + if( res==WAIT_OBJECT_0 ){ + ret = TRUE; + }else if( res==WAIT_TIMEOUT ){ +#if SQLITE_ENABLE_SETLK_TIMEOUT==1 + rc = SQLITE_BUSY_TIMEOUT; +#else + rc = SQLITE_BUSY; +#endif + }else{ + /* Some other error has occurred */ + rc = SQLITE_IOERR_LOCK; } - } - /* Releasing a pending lock */ - else if (dwFileOffsetLow == (DWORD)PENDING_BYTE - && nNumberOfBytesToUnlockLow == 1){ - if (pFile->local.bPending){ - pFile->local.bPending = FALSE; - pFile->shared->bPending = FALSE; - bReturn = TRUE; - } - } - /* Releasing a reserved lock */ - else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE - && nNumberOfBytesToUnlockLow == 1){ - if (pFile->local.bReserved) { - pFile->local.bReserved = FALSE; - pFile->shared->bReserved = FALSE; - bReturn = TRUE; - } + /* If it is still pending, cancel the LockFileEx() call. */ + osCancelIo(hFile); } - winceMutexRelease(pFile->hMutex); - return bReturn; -} -/* -** End of the special code for wince -*****************************************************************************/ -#endif /* SQLITE_OS_WINCE */ + osCloseHandle(ovlp.hEvent); +#endif /* defined(SQLITE_ENABLE_SETLK_TIMEOUT) */ -/* -** Lock a file region. -*/ -static BOOL winLockFile( - LPHANDLE phFile, - DWORD flags, - DWORD offsetLow, - DWORD offsetHigh, - DWORD numBytesLow, - DWORD numBytesHigh -){ -#if SQLITE_OS_WINCE - /* - ** NOTE: Windows CE is handled differently here due its lack of the Win32 - ** API LockFile. - */ - return winceLockFile(phFile, offsetLow, offsetHigh, - numBytesLow, numBytesHigh); -#else - if( osIsNT() ){ - OVERLAPPED ovlp; - memset(&ovlp, 0, sizeof(OVERLAPPED)); - ovlp.Offset = offsetLow; - ovlp.OffsetHigh = offsetHigh; - return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp); - }else{ - return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow, - numBytesHigh); + if( rc==SQLITE_OK && !ret ){ + rc = SQLITE_BUSY; } -#endif + return rc; } +#endif /* #ifndef SQLITE_OMIT_WAL */ /* ** Unlock a file region. @@ -49281,26 +50946,22 @@ static BOOL winUnlockFile( DWORD numBytesLow, DWORD numBytesHigh ){ -#if SQLITE_OS_WINCE - /* - ** NOTE: Windows CE is handled differently here due its lack of the Win32 - ** API UnlockFile. - */ - return winceUnlockFile(phFile, offsetLow, offsetHigh, - numBytesLow, numBytesHigh); -#else - if( osIsNT() ){ - OVERLAPPED ovlp; - memset(&ovlp, 0, sizeof(OVERLAPPED)); - ovlp.Offset = offsetLow; - ovlp.OffsetHigh = offsetHigh; - return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp); - }else{ - return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow, - numBytesHigh); - } -#endif + OVERLAPPED ovlp; + memset(&ovlp, 0, sizeof(OVERLAPPED)); + ovlp.Offset = offsetLow; + ovlp.OffsetHigh = offsetHigh; + return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp); +} + +#ifndef SQLITE_OMIT_WAL +/* +** Remove an nByte lock starting at offset iOff from HANDLE h. +*/ +static int winHandleUnlock(HANDLE h, int iOff, int nByte){ + BOOL ret = winUnlockFile(&h, iOff, 0, nByte, 0); + return (ret ? SQLITE_OK : SQLITE_IOERR_UNLOCK); } +#endif /***************************************************************************** ** The next group of routines implement the I/O methods specified @@ -49314,67 +50975,41 @@ static BOOL winUnlockFile( # define INVALID_SET_FILE_POINTER ((DWORD)-1) #endif +/* +** Seek the file handle h to offset nByte of the file. +** +** If successful, return SQLITE_OK. Or, if an error occurs, return an SQLite +** error code. +*/ +static int winHandleSeek(HANDLE h, sqlite3_int64 iOffset){ + int rc = SQLITE_OK; /* Return value */ + LARGE_INTEGER x; /* The offset */ + + x.QuadPart = iOffset; + if( osSetFilePointerEx(h, x, 0, FILE_BEGIN)==0 ){ + rc = SQLITE_IOERR_SEEK; + } + OSTRACE(("SEEK file=%p, offset=%lld rc=%s\n", h, iOffset,sqlite3ErrName(rc))); + return rc; +} + /* ** Move the current position of the file handle passed as the first ** argument to offset iOffset within the file. If successful, return 0. ** Otherwise, set pFile->lastErrno and return non-zero. */ static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){ -#if !SQLITE_OS_WINRT - LONG upperBits; /* Most sig. 32 bits of new offset */ - LONG lowerBits; /* Least sig. 32 bits of new offset */ - DWORD dwRet; /* Value returned by SetFilePointer() */ - DWORD lastErrno; /* Value returned by GetLastError() */ - - OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset)); - - upperBits = (LONG)((iOffset>>32) & 0x7fffffff); - lowerBits = (LONG)(iOffset & 0xffffffff); - - /* API oddity: If successful, SetFilePointer() returns a dword - ** containing the lower 32-bits of the new file-offset. Or, if it fails, - ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, - ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine - ** whether an error has actually occurred, it is also necessary to call - ** GetLastError(). - */ - dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN); - - if( (dwRet==INVALID_SET_FILE_POINTER - && ((lastErrno = osGetLastError())!=NO_ERROR)) ){ - pFile->lastErrno = lastErrno; - winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno, - "winSeekFile", pFile->zPath); - OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h)); - return 1; - } - - OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h)); - return 0; -#else - /* - ** Same as above, except that this implementation works for WinRT. - */ - - LARGE_INTEGER x; /* The new offset */ - BOOL bRet; /* Value returned by SetFilePointerEx() */ - - x.QuadPart = iOffset; - bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN); + int rc; - if(!bRet){ + rc = winHandleSeek(pFile->h, iOffset); + if( rc!=SQLITE_OK ){ pFile->lastErrno = osGetLastError(); - winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno, - "winSeekFile", pFile->zPath); - OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h)); - return 1; + winLogError(rc, pFile->lastErrno, "winSeekFile", pFile->zPath); } - - OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h)); - return 0; -#endif + return rc; } + #if SQLITE_MAX_MMAP_SIZE>0 /* Forward references to VFS helper methods used for memory mapped files */ static int winMapfile(winFile*, sqlite3_int64); @@ -49411,27 +51046,7 @@ static int winClose(sqlite3_file *id){ do{ rc = osCloseHandle(pFile->h); /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */ - }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) ); -#if SQLITE_OS_WINCE -#define WINCE_DELETION_ATTEMPTS 3 - { - winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData; - if( pAppData==NULL || !pAppData->bNoLock ){ - winceDestroyLock(pFile); - } - } - if( pFile->zDeleteOnClose ){ - int cnt = 0; - while( - osDeleteFileW(pFile->zDeleteOnClose)==0 - && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff - && cnt++ < WINCE_DELETION_ATTEMPTS - ){ - sqlite3_win32_sleep(100); /* Wait a little before trying again */ - } - sqlite3_free(pFile->zDeleteOnClose); - } -#endif + }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (osSleep(100), 1) ); if( rc ){ pFile->h = NULL; } @@ -49454,7 +51069,7 @@ static int winRead( int amt, /* Number of bytes to read */ sqlite3_int64 offset /* Begin reading at this offset */ ){ -#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) +#if !defined(SQLITE_WIN32_NO_OVERLAPPED) OVERLAPPED overlapped; /* The offset for ReadFile. */ #endif winFile *pFile = (winFile*)id; /* file handle */ @@ -49488,7 +51103,7 @@ static int winRead( } #endif -#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED) +#if defined(SQLITE_WIN32_NO_OVERLAPPED) if( winSeekFile(pFile, offset) ){ OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n", osGetCurrentProcessId(), pFile, pFile->h)); @@ -49566,13 +51181,13 @@ static int winWrite( } #endif -#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED) +#if defined(SQLITE_WIN32_NO_OVERLAPPED) rc = winSeekFile(pFile, offset); if( rc==0 ){ #else { #endif -#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) +#if !defined(SQLITE_WIN32_NO_OVERLAPPED) OVERLAPPED overlapped; /* The offset for WriteFile. */ #endif u8 *aRem = (u8 *)pBuf; /* Data yet to be written */ @@ -49580,14 +51195,14 @@ static int winWrite( DWORD nWrite; /* Bytes written by each WriteFile() call */ DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */ -#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) +#if !defined(SQLITE_WIN32_NO_OVERLAPPED) memset(&overlapped, 0, sizeof(OVERLAPPED)); overlapped.Offset = (LONG)(offset & 0xffffffff); overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); #endif while( nRem>0 ){ -#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED) +#if defined(SQLITE_WIN32_NO_OVERLAPPED) if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){ #else if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){ @@ -49600,7 +51215,7 @@ static int winWrite( lastErrno = osGetLastError(); break; } -#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED) +#if !defined(SQLITE_WIN32_NO_OVERLAPPED) offset += nWrite; overlapped.Offset = (LONG)(offset & 0xffffffff); overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff); @@ -49634,6 +51249,48 @@ static int winWrite( return SQLITE_OK; } +#ifndef SQLITE_OMIT_WAL +/* +** Truncate the file opened by handle h to nByte bytes in size. +*/ +static int winHandleTruncate(HANDLE h, sqlite3_int64 nByte){ + int rc = SQLITE_OK; /* Return code */ + rc = winHandleSeek(h, nByte); + if( rc==SQLITE_OK ){ + if( 0==osSetEndOfFile(h) ){ + rc = SQLITE_IOERR_TRUNCATE; + } + } + return rc; +} + +/* +** Determine the size in bytes of the file opened by the handle passed as +** the first argument. +*/ +static int winHandleSize(HANDLE h, sqlite3_int64 *pnByte){ + int rc = SQLITE_OK; + LARGE_INTEGER x; + assert( pnByte ); + if( osGetFileSizeEx(h, &x)==0 ){ + rc = SQLITE_IOERR_FSTAT; + *pnByte = 0; + }else{ + *pnByte = x.QuadPart; + } + return rc; +} + +/* +** Close the handle passed as the only argument. +*/ +static void winHandleClose(HANDLE h){ + if( h!=INVALID_HANDLE_VALUE ){ + osCloseHandle(h); + } +} +#endif /* #ifndef SQLITE_OMIT_WAL */ + /* ** Truncate an open file to a specified size */ @@ -49819,35 +51476,17 @@ static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){ assert( pSize!=0 ); SimulateIOError(return SQLITE_IOERR_FSTAT); OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize)); - -#if SQLITE_OS_WINRT { - FILE_STANDARD_INFO info; - if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo, - &info, sizeof(info)) ){ - *pSize = info.EndOfFile.QuadPart; - }else{ + LARGE_INTEGER x; + if( osGetFileSizeEx(pFile->h, &x)==0 ){ + *pSize = 0; pFile->lastErrno = osGetLastError(); rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno, "winFileSize", pFile->zPath); + }else{ + *pSize = x.QuadPart; } } -#else - { - DWORD upperBits; - DWORD lowerBits; - DWORD lastErrno; - - lowerBits = osGetFileSize(pFile->h, &upperBits); - *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits; - if( (lowerBits == INVALID_FILE_SIZE) - && ((lastErrno = osGetLastError())!=NO_ERROR) ){ - pFile->lastErrno = lastErrno; - rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno, - "winFileSize", pFile->zPath); - } - } -#endif OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n", pFile->h, pSize, *pSize, sqlite3ErrName(rc))); return rc; @@ -49889,30 +51528,12 @@ static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){ ** Different API routines are called depending on whether or not this ** is Win9x or WinNT. */ -static int winGetReadLock(winFile *pFile){ +static int winGetReadLock(winFile *pFile, int bBlock){ int res; + DWORD mask = ~(bBlock ? LOCKFILE_FAIL_IMMEDIATELY : 0); OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); - if( osIsNT() ){ -#if SQLITE_OS_WINCE - /* - ** NOTE: Windows CE is handled differently here due its lack of the Win32 - ** API LockFileEx. - */ - res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0); -#else - res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0, - SHARED_SIZE, 0); -#endif - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - int lk; - sqlite3_randomness(sizeof(lk), &lk); - pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1)); - res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, - SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0); - } -#endif + res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS&mask, SHARED_FIRST, 0, + SHARED_SIZE, 0); if( res == 0 ){ pFile->lastErrno = osGetLastError(); /* No need to log a failure to lock */ @@ -49928,14 +51549,7 @@ static int winUnlockReadLock(winFile *pFile){ int res; DWORD lastErrno; OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); - if( osIsNT() ){ - res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0); - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0); - } -#endif + res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0); if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){ pFile->lastErrno = lastErrno; winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno, @@ -50004,46 +51618,62 @@ static int winLock(sqlite3_file *id, int locktype){ assert( locktype!=PENDING_LOCK ); assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK ); - /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or + /* Lock the PENDING_LOCK byte if we need to acquire an EXCLUSIVE lock or ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of ** the PENDING_LOCK byte is temporary. */ newLocktype = pFile->locktype; - if( pFile->locktype==NO_LOCK - || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK) + if( locktype==SHARED_LOCK + || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK) ){ int cnt = 3; - while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, - PENDING_BYTE, 0, 1, 0))==0 ){ + + /* Flags for the LockFileEx() call. This should be an exclusive lock if + ** this call is to obtain EXCLUSIVE, or a shared lock if this call is to + ** obtain SHARED. */ + int flags = LOCKFILE_FAIL_IMMEDIATELY; + if( locktype==EXCLUSIVE_LOCK ){ + flags |= LOCKFILE_EXCLUSIVE_LOCK; + } + while( cnt>0 ){ /* Try 3 times to get the pending lock. This is needed to work ** around problems caused by indexing and/or anti-virus software on ** Windows systems. + ** ** If you are using this code as a model for alternative VFSes, do not - ** copy this retry logic. It is a hack intended for Windows only. - */ + ** copy this retry logic. It is a hack intended for Windows only. */ + res = winLockFile(&pFile->h, flags, PENDING_BYTE, 0, 1, 0); + if( res ) break; + lastErrno = osGetLastError(); OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n", - pFile->h, cnt, res)); + pFile->h, cnt, res + )); + if( lastErrno==ERROR_INVALID_HANDLE ){ pFile->lastErrno = lastErrno; rc = SQLITE_IOERR_LOCK; OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n", - pFile->h, cnt, sqlite3ErrName(rc))); + pFile->h, cnt, sqlite3ErrName(rc) + )); return rc; } - if( cnt ) sqlite3_win32_sleep(1); + + cnt--; + if( cnt>0 ) osSleep(1); } gotPendingLock = res; - if( !res ){ - lastErrno = osGetLastError(); - } } /* Acquire a shared lock */ if( locktype==SHARED_LOCK && res ){ assert( pFile->locktype==NO_LOCK ); - res = winGetReadLock(pFile); +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + res = winGetReadLock(pFile, pFile->bBlockOnConnect); +#else + res = winGetReadLock(pFile, 0); +#endif if( res ){ newLocktype = SHARED_LOCK; }else{ @@ -50081,7 +51711,7 @@ static int winLock(sqlite3_file *id, int locktype){ newLocktype = EXCLUSIVE_LOCK; }else{ lastErrno = osGetLastError(); - winGetReadLock(pFile); + winGetReadLock(pFile, 0); } } @@ -50161,7 +51791,7 @@ static int winUnlock(sqlite3_file *id, int locktype){ type = pFile->locktype; if( type>=EXCLUSIVE_LOCK ){ winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0); - if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){ + if( locktype==SHARED_LOCK && !winGetReadLock(pFile, 0) ){ /* This should never happen. We should always be able to ** reacquire the read lock */ rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(), @@ -50239,7 +51869,7 @@ static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){ /* Forward references to VFS helper methods used for temporary files */ static int winGetTempname(sqlite3_vfs *, char **); -static int winIsDir(const void *); +static int winIsDir(LPCWSTR); static BOOL winIsLongPathPrefix(const char *); static BOOL winIsDriveLetterAndColon(const char *); @@ -50330,6 +51960,11 @@ static int winFileControl(sqlite3_file *id, int op, void *pArg){ return SQLITE_OK; } #endif + case SQLITE_FCNTL_NULL_IO: { + (void)osCloseHandle(pFile->h); + pFile->h = NULL; + return SQLITE_OK; + } case SQLITE_FCNTL_TEMPFILENAME: { char *zTFile = 0; int rc = winGetTempname(pFile->pVfs, &zTFile); @@ -50366,6 +52001,50 @@ static int winFileControl(sqlite3_file *id, int op, void *pArg){ return rc; } #endif + +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + case SQLITE_FCNTL_LOCK_TIMEOUT: { + int iOld = pFile->iBusyTimeout; + int iNew = *(int*)pArg; +#if SQLITE_ENABLE_SETLK_TIMEOUT==1 + pFile->iBusyTimeout = (iNew < 0) ? INFINITE : (DWORD)iNew; +#elif SQLITE_ENABLE_SETLK_TIMEOUT==2 + pFile->iBusyTimeout = (DWORD)(!!iNew); +#else +# error "SQLITE_ENABLE_SETLK_TIMEOUT must be set to 1 or 2" +#endif + *(int*)pArg = iOld; + return SQLITE_OK; + } + case SQLITE_FCNTL_BLOCK_ON_CONNECT: { + int iNew = *(int*)pArg; + pFile->bBlockOnConnect = iNew; + return SQLITE_OK; + } +#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */ + +#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT) + case SQLITE_FCNTL_FILESTAT: { + sqlite3_str *pStr = (sqlite3_str*)pArg; + sqlite3_str_appendf(pStr, "{\"h\":%llu", (sqlite3_uint64)pFile->h); + sqlite3_str_appendf(pStr, ",\"vfs\":\"%s\"", pFile->pVfs->zName); + if( pFile->locktype ){ + static const char *azLock[] = { "SHARED", "RESERVED", + "PENDING", "EXCLUSIVE" }; + sqlite3_str_appendf(pStr, ",\"locktype\":\"%s\"", + azLock[pFile->locktype-1]); + } +#if SQLITE_MAX_MMAP_SIZE>0 + if( pFile->mmapSize ){ + sqlite3_str_appendf(pStr, ",\"mmapSize\":%lld", pFile->mmapSize); + sqlite3_str_appendf(pStr, ",\"nFetchOut\":%d", pFile->nFetchOut); + } +#endif + sqlite3_str_append(pStr, "}", 1); + return SQLITE_OK; + } +#endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */ + } OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h)); return SQLITE_NOTFOUND; @@ -50391,7 +52070,7 @@ static int winSectorSize(sqlite3_file *id){ */ static int winDeviceCharacteristics(sqlite3_file *id){ winFile *p = (winFile*)id; - return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | + return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | SQLITE_IOCAP_SUBPAGE_READ | ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0); } @@ -50403,6 +52082,93 @@ static int winDeviceCharacteristics(sqlite3_file *id){ */ static SYSTEM_INFO winSysInfo; +/* +** Convert a UTF-8 filename into whatever form the underlying +** operating system wants filenames in. Space to hold the result +** is obtained from malloc and must be freed by the calling +** function +** +** On Cygwin, 3 possible input forms are accepted: +** - If the filename starts with "<drive>:/" or "<drive>:\", +** it is converted to UTF-16 as-is. +** - If the filename contains '/', it is assumed to be a +** Cygwin absolute path, it is converted to a win32 +** absolute path in UTF-16. +** - Otherwise it must be a filename only, the win32 filename +** is returned in UTF-16. +** Note: If the function cygwin_conv_path() fails, only +** UTF-8 -> UTF-16 conversion will be done. This can only +** happen when the file path >32k, in which case winUtf8ToUnicode() +** will fail too. +*/ +static LPWSTR winConvertFromUtf8Filename(const char *zFilename){ + LPWSTR zConverted = 0; +#ifdef __CYGWIN__ + int nChar; + + if( osCygwin_conv_path && !(winIsDriveLetterAndColon(zFilename) + && winIsDirSep(zFilename[2])) ){ + i64 nByte; + int convertflag = CCP_POSIX_TO_WIN_W; + if( !strchr(zFilename, '/') ) convertflag |= CCP_RELATIVE; + nByte = (i64)osCygwin_conv_path(convertflag, + zFilename, 0, 0); + if( nByte>0 ){ + zConverted = sqlite3MallocZero(12+(u64)nByte); + if ( zConverted==0 ){ + return zConverted; + } + /* Filenames should be prefixed, except when converted + * full path already starts with "\\?\". */ + if( osCygwin_conv_path(convertflag, zFilename, + zConverted+4, nByte)==0 ){ + if( (convertflag&CCP_RELATIVE) ){ + memmove(zConverted, zConverted+4, nByte); + }else if( memcmp(zConverted+4, L"\\\\", 4) ){ + memcpy(zConverted, L"\\\\?\\", 8); + }else if( zConverted[6]!='?' ){ + memmove(zConverted+6, zConverted+4, nByte); + memcpy(zConverted, L"\\\\?\\UNC", 14); + }else{ + memmove(zConverted, zConverted+4, nByte); + } + return zConverted; + } + sqlite3_free(zConverted); + } + } + nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0); + if( nChar==0 ){ + return 0; + } + zConverted = sqlite3MallocZero( ((u64)nChar+6)*sizeof(WCHAR) ); + if( zConverted==0 ){ + return 0; + } + nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, + zConverted, nChar); + if( nChar==0 ){ + sqlite3_free(zConverted); + zConverted = 0; + }else if( nChar>MAX_PATH + && winIsDriveLetterAndColon(zFilename) + && winIsDirSep(zFilename[2]) ){ + memmove(zConverted+4, zConverted, nChar*sizeof(WCHAR)); + zConverted[2] = '\\'; + memcpy(zConverted, L"\\\\?\\", 8); + }else if( nChar>MAX_PATH + && winIsDirSep(zFilename[0]) && winIsDirSep(zFilename[1]) + && zFilename[2] != '?' ){ + memmove(zConverted+6, zConverted, nChar*sizeof(WCHAR)); + memcpy(zConverted, L"\\\\?\\UNC", 14); + } +#else /* if !defined(__CYGWIN__) */ + zConverted = winUtf8ToUnicode(zFilename); +#endif /* __CYGWIN__ */ + /* caller will handle out of memory */ + return zConverted; +} + #ifndef SQLITE_OMIT_WAL /* @@ -50439,30 +52205,40 @@ static int winShmMutexHeld(void) { ** log-summary is opened only once per process. ** ** winShmMutexHeld() must be true when creating or destroying -** this object or while reading or writing the following fields: +** this object, or while editing the global linked list that starts +** at winShmNodeList. ** -** nRef -** pNext +** When reading or writing the linked list starting at winShmNode.pWinShmList, +** pShmNode->mutex must be held. ** -** The following fields are read-only after the object is created: +** The following fields are constant after the object is created: ** -** fid ** zFilename +** hSharedShm +** mutex +** bUseSharedLockHandle ** -** Either winShmNode.mutex must be held or winShmNode.nRef==0 and +** Either winShmNode.mutex must be held or winShmNode.pWinShmList==0 and ** winShmMutexHeld() is true when reading or writing any other field ** in this structure. ** +** File-handle hSharedShm is always used to (a) take the DMS lock, (b) +** truncate the *-shm file if the DMS-locking protocol demands it, and +** (c) map regions of the *-shm file into memory using MapViewOfFile() +** or similar. If bUseSharedLockHandle is true, then other locks are also +** taken on hSharedShm. Or, if bUseSharedLockHandle is false, then other +** locks are taken using each connection's winShm.hShm handles. */ struct winShmNode { sqlite3_mutex *mutex; /* Mutex to access this object */ char *zFilename; /* Name of the file */ - winFile hFile; /* File handle from winOpen */ + HANDLE hSharedShm; /* File handle open on zFilename */ + int bUseSharedLockHandle; /* True to use hSharedShm for everything */ + int isUnlocked; /* DMS lock has not yet been obtained */ + int isReadonly; /* True if read-only */ int szRegion; /* Size of shared-memory regions */ int nRegion; /* Size of array apRegion */ - u8 isReadonly; /* True if read-only */ - u8 isUnlocked; /* True if no DMS lock held */ struct ShmRegion { HANDLE hMap; /* File handle from CreateFileMapping */ @@ -50470,8 +52246,8 @@ struct winShmNode { } *aRegion; DWORD lastErrno; /* The Windows errno from the last I/O error */ - int nRef; /* Number of winShm objects pointing to this */ - winShm *pFirst; /* All winShm objects pointing to this */ + winShm *pWinShmList; /* List of winShm objects with ptrs to this */ + winShmNode *pNext; /* Next in list of all winShmNode objects */ #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) u8 nextShmId; /* Next available winShm.id value */ @@ -50487,26 +52263,19 @@ static winShmNode *winShmNodeList = 0; /* ** Structure used internally by this VFS to record the state of an -** open shared memory connection. -** -** The following fields are initialized when this object is created and -** are read-only thereafter: -** -** winShm.pShmNode -** winShm.id -** -** All other fields are read/write. The winShm.pShmNode->mutex must be held -** while accessing any read/write fields. +** open shared memory connection. There is one such structure for each +** winFile open on a wal mode database. */ struct winShm { winShmNode *pShmNode; /* The underlying winShmNode object */ - winShm *pNext; /* Next winShm with the same winShmNode */ - u8 hasMutex; /* True if holding the winShmNode mutex */ u16 sharedMask; /* Mask of shared locks held */ u16 exclMask; /* Mask of exclusive locks held */ + HANDLE hShm; /* File-handle on *-shm file. For locking. */ + int bReadonly; /* True if hShm is opened read-only */ #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) u8 id; /* Id of this connection with its winShmNode */ #endif + winShm *pWinShmNext; /* Next winShm object on same winShmNode */ }; /* @@ -50515,56 +52284,12 @@ struct winShm { #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */ #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */ -/* -** Apply advisory locks for all n bytes beginning at ofst. -*/ -#define WINSHM_UNLCK 1 -#define WINSHM_RDLCK 2 -#define WINSHM_WRLCK 3 -static int winShmSystemLock( - winShmNode *pFile, /* Apply locks to this open shared-memory segment */ - int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */ - int ofst, /* Offset to first byte to be locked/unlocked */ - int nByte /* Number of bytes to lock or unlock */ -){ - int rc = 0; /* Result code form Lock/UnlockFileEx() */ - - /* Access to the winShmNode object is serialized by the caller */ - assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) ); - - OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n", - pFile->hFile.h, lockType, ofst, nByte)); - - /* Release/Acquire the system-level lock */ - if( lockType==WINSHM_UNLCK ){ - rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0); - }else{ - /* Initialize the locking parameters */ - DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY; - if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK; - rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0); - } - - if( rc!= 0 ){ - rc = SQLITE_OK; - }else{ - pFile->lastErrno = osGetLastError(); - rc = SQLITE_BUSY; - } - - OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n", - pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" : - "winLockFile", pFile->lastErrno, sqlite3ErrName(rc))); - - return rc; -} - /* Forward references to VFS methods */ static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*); static int winDelete(sqlite3_vfs *,const char*,int); /* -** Purge the winShmNodeList list of all entries with winShmNode.nRef==0. +** Purge the winShmNodeList list of all entries with winShmNode.pWinShmList==0. ** ** This is not a VFS shared-memory method; it is a utility function called ** by VFS shared-memory methods. @@ -50577,7 +52302,7 @@ static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ osGetCurrentProcessId(), deleteFlag)); pp = &winShmNodeList; while( (p = *pp)!=0 ){ - if( p->nRef==0 ){ + if( p->pWinShmList==0 ){ int i; if( p->mutex ){ sqlite3_mutex_free(p->mutex); } for(i=0; i<p->nRegion; i++){ @@ -50590,11 +52315,7 @@ static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ osGetCurrentProcessId(), i, bRc ? "ok" : "failed")); UNUSED_VARIABLE_VALUE(bRc); } - if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){ - SimulateIOErrorBenign(1); - winClose((sqlite3_file *)&p->hFile); - SimulateIOErrorBenign(0); - } + winHandleClose(p->hSharedShm); if( deleteFlag ){ SimulateIOErrorBenign(1); sqlite3BeginBenignMalloc(); @@ -50612,42 +52333,228 @@ static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){ } /* -** The DMS lock has not yet been taken on shm file pShmNode. Attempt to -** take it now. Return SQLITE_OK if successful, or an SQLite error -** code otherwise. -** -** If the DMS cannot be locked because this is a readonly_shm=1 -** connection and no other process already holds a lock, return -** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1. +** Handle h is open on the *-shm file. This function zeroes the first +** 8 bytes of the file. If SQLITE_ENABLE_SETLK_TIMEOUT is defined, h may +** have been opened with FILE_FLAG_OVERLAPPED. +*/ +static int winZeroSharedMemory(HANDLE h){ + u8 aZero[8] = {0,0,0,0,0,0,0,0}; + DWORD nWrite = 0; + OVERLAPPED ovlp; + memset(&ovlp, 0, sizeof(OVERLAPPED)); + if( !osWriteFile(h, aZero, sizeof(aZero), &nWrite, &ovlp) ){ + /* If the file was opened with FILE_FLAG_OVERLAPPED, the write may still + ** be pending. Wait for it with GetOverlappedResult(). */ + if( osGetLastError()!=ERROR_IO_PENDING + || !GetOverlappedResult(h, &ovlp, &nWrite, TRUE) + ){ + nWrite = 0; + } + } + return (nWrite==sizeof(aZero) ? SQLITE_OK : SQLITE_IOERR_WRITE); +} + +/* +** The DMS lock has not yet been taken on the shm file associated with +** pShmNode. Take the lock. Truncate the *-shm file if required. +** Return SQLITE_OK if successful, or an SQLite error code otherwise. */ -static int winLockSharedMemory(winShmNode *pShmNode){ - int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1); +static int winLockSharedMemory(winShmNode *pShmNode, DWORD nMs){ + HANDLE h = pShmNode->hSharedShm; + int rc = SQLITE_OK; + assert( sqlite3_mutex_held(pShmNode->mutex) ); + rc = winHandleLockTimeout(h, WIN_SHM_DMS, 1, 1, 0); if( rc==SQLITE_OK ){ + /* We have an EXCLUSIVE lock on the DMS byte. This means that this + ** is the first process to open the file. Truncate it to zero bytes + ** in this case. */ if( pShmNode->isReadonly ){ - pShmNode->isUnlocked = 1; - winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); - return SQLITE_READONLY_CANTINIT; - }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){ - winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); - return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(), - "winLockSharedMemory", pShmNode->zFilename); + rc = SQLITE_READONLY_CANTINIT; + }else{ + if( SQLITE_OK!=winHandleTruncate(h, 0) ){ + /* Sometimes the truncate operation may fail because some other + ** process is still holding an open mapping. So try to write + ** zeroes into the start of the file instead. */ + rc = winZeroSharedMemory(h); + } } + + /* Release the EXCLUSIVE lock acquired above. */ + winUnlockFile(&h, WIN_SHM_DMS, 0, 1, 0); + }else if( (rc & 0xFF)==SQLITE_BUSY ){ + rc = SQLITE_OK; } if( rc==SQLITE_OK ){ - winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); + /* Take a SHARED lock on the DMS byte. */ + rc = winHandleLockTimeout(h, WIN_SHM_DMS, 1, 0, nMs); + if( rc==SQLITE_OK ){ + pShmNode->isUnlocked = 0; + } + } + + return rc; +} + + +/* +** This function is used to open a handle on a *-shm file. +** +** If SQLITE_ENABLE_SETLK_TIMEOUT is defined at build time, then the file +** is opened with FILE_FLAG_OVERLAPPED specified. If not, it is not. +*/ +static int winHandleOpen( + const char *zUtf8, /* File to open */ + int *pbReadonly, /* IN/OUT: True for readonly handle */ + HANDLE *ph /* OUT: New HANDLE for file */ +){ + int rc = SQLITE_OK; + LPWSTR zConverted = 0; + int bReadonly = *pbReadonly; + HANDLE h = INVALID_HANDLE_VALUE; + +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + const DWORD flag_overlapped = FILE_FLAG_OVERLAPPED; +#else + const DWORD flag_overlapped = 0; +#endif + + /* Convert the filename to the system encoding. */ + zConverted = winConvertFromUtf8Filename(zUtf8); + if( zConverted==0 ){ + OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8)); + rc = SQLITE_IOERR_NOMEM_BKPT; + goto winopenfile_out; } - return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1); + /* Ensure the file we are trying to open is not actually a directory. */ + if( winIsDir(zConverted) ){ + OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8)); + rc = SQLITE_CANTOPEN_ISDIR; + goto winopenfile_out; + } + + /* TODO: platforms. + ** TODO: retry-on-ioerr. + */ + h = osCreateFileW(zConverted, /* lpFileName */ + (GENERIC_READ | (bReadonly ? 0 : GENERIC_WRITE)), /* dwDesiredAccess */ + FILE_SHARE_READ | FILE_SHARE_WRITE, /* dwShareMode */ + NULL, /* lpSecurityAttributes */ + OPEN_ALWAYS, /* dwCreationDisposition */ + FILE_ATTRIBUTE_NORMAL|flag_overlapped, + NULL + ); + + if( h==INVALID_HANDLE_VALUE ){ + if( bReadonly==0 ){ + bReadonly = 1; + rc = winHandleOpen(zUtf8, &bReadonly, &h); + }else{ + rc = SQLITE_CANTOPEN_BKPT; + } + } + + winopenfile_out: + sqlite3_free(zConverted); + *pbReadonly = bReadonly; + *ph = h; + return rc; } /* -** Open the shared-memory area associated with database file pDbFd. +** Close pDbFd's connection to shared-memory. Delete the underlying +** *-shm file if deleteFlag is true. +*/ +static int winCloseSharedMemory(winFile *pDbFd, int deleteFlag){ + winShm *p; /* The connection to be closed */ + winShm **pp; /* Iterator for pShmNode->pWinShmList */ + winShmNode *pShmNode; /* The underlying shared-memory file */ + + p = pDbFd->pShm; + if( p==0 ) return SQLITE_OK; + if( p->hShm!=INVALID_HANDLE_VALUE ){ + osCloseHandle(p->hShm); + } + + winShmEnterMutex(); + pShmNode = p->pShmNode; + + /* Remove this connection from the winShmNode.pWinShmList list */ + sqlite3_mutex_enter(pShmNode->mutex); + for(pp=&pShmNode->pWinShmList; *pp!=p; pp=&(*pp)->pWinShmNext){} + *pp = p->pWinShmNext; + sqlite3_mutex_leave(pShmNode->mutex); + + winShmPurge(pDbFd->pVfs, deleteFlag); + winShmLeaveMutex(); + + /* Free the connection p */ + sqlite3_free(p); + pDbFd->pShm = 0; + return SQLITE_OK; +} + +/* +** testfixture builds may set this global variable to true via a +** Tcl interface. This forces the VFS to use the locking normally +** only used for UNC paths for all files. +*/ +#ifdef SQLITE_TEST +SQLITE_API int sqlite3_win_test_unc_locking = 0; +#else +# define sqlite3_win_test_unc_locking 0 +#endif + +/* +** Return true if the string passed as the only argument is likely +** to be a UNC path. Return false if not. ** -** When opening a new shared-memory file, if no other instances of that -** file are currently open, in this process or in other processes, then -** the file must be truncated to zero length or have its header cleared. +** Return true if: +** +** (1) The name begins with "\\" +** (2) But does not begin with "\\?\C:\" where C can be any alphabetic +** character. +** +** For testing, also return true in all cases if the global variable +** sqlite3_win_test_unc_locking is true. +*/ +static int winIsUNCPath(const char *zFile){ + if( zFile[0]=='\\' && zFile[1]=='\\' ){ + if( zFile[2]=='?' + && zFile[3]=='\\' + && sqlite3Isalpha(zFile[4]) + && zFile[5]==':' + && winIsDirSep(zFile[6]) + ){ + return sqlite3_win_test_unc_locking; + }else{ + return 1; + } + } + return sqlite3_win_test_unc_locking; +} + +/* +** Return true if the string passed in is the name of a file on a +** remote (network-mounted) volume. +*/ +static int winIsRemoteVolume(const char *zFile){ + WCHAR zRoot[4]; + if( strncmp(zFile, "\\\\?\\",4)==0 ) zFile += 4; + if( !sqlite3Isalpha(zFile[0]) ) return 0; + if( zFile[1]!=':' ) return 0; + if( !winIsDirSep(zFile[2]) ) return 0; + zRoot[0] = (WCHAR)zFile[0]; + zRoot[1] = ':'; + zRoot[2] = '\\'; + zRoot[3] = 0; + return osGetDriveTypeW(zRoot)==DRIVE_REMOTE; +} + +/* +** Open the shared-memory area associated with database file pDbFd. */ static int winOpenSharedMemory(winFile *pDbFd){ struct winShm *p; /* The connection to be opened */ @@ -50659,98 +52566,97 @@ static int winOpenSharedMemory(winFile *pDbFd){ assert( pDbFd->pShm==0 ); /* Not previously opened */ /* Allocate space for the new sqlite3_shm object. Also speculatively - ** allocate space for a new winShmNode and filename. - */ + ** allocate space for a new winShmNode and filename. */ p = sqlite3MallocZero( sizeof(*p) ); if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT; nName = sqlite3Strlen30(pDbFd->zPath); - pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 ); + pNew = sqlite3MallocZero( sizeof(*pShmNode) + (i64)nName + 17 ); if( pNew==0 ){ sqlite3_free(p); return SQLITE_IOERR_NOMEM_BKPT; } pNew->zFilename = (char*)&pNew[1]; + pNew->hSharedShm = INVALID_HANDLE_VALUE; + pNew->isUnlocked = 1; + if( winIsUNCPath(pDbFd->zPath) || winIsRemoteVolume(pDbFd->zPath) ){ + pNew->bUseSharedLockHandle = 1; + }else{ + pNew->bUseSharedLockHandle = 0; + } sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath); sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); /* Look to see if there is an existing winShmNode that can be used. - ** If no matching winShmNode currently exists, create a new one. - */ + ** If no matching winShmNode currently exists, then create a new one. */ winShmEnterMutex(); for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){ /* TBD need to come up with better match here. Perhaps - ** use FILE_ID_BOTH_DIR_INFO Structure. - */ + ** use FILE_ID_BOTH_DIR_INFO Structure. */ if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break; } - if( pShmNode ){ - sqlite3_free(pNew); - }else{ - int inFlags = SQLITE_OPEN_WAL; - int outFlags = 0; - + if( pShmNode==0 ){ pShmNode = pNew; - pNew = 0; - ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE; - pShmNode->pNext = winShmNodeList; - winShmNodeList = pShmNode; + /* Allocate a mutex for this winShmNode object, if one is required. */ if( sqlite3GlobalConfig.bCoreMutex ){ pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); - if( pShmNode->mutex==0 ){ - rc = SQLITE_IOERR_NOMEM_BKPT; - goto shm_open_err; - } + if( pShmNode->mutex==0 ) rc = SQLITE_IOERR_NOMEM_BKPT; } - if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){ - inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; - }else{ - inFlags |= SQLITE_OPEN_READONLY; - } - rc = winOpen(pDbFd->pVfs, pShmNode->zFilename, - (sqlite3_file*)&pShmNode->hFile, - inFlags, &outFlags); - if( rc!=SQLITE_OK ){ - rc = winLogError(rc, osGetLastError(), "winOpenShm", - pShmNode->zFilename); - goto shm_open_err; + /* Open a file-handle to use for mappings, and for the DMS lock. */ + if( rc==SQLITE_OK ){ + HANDLE h = INVALID_HANDLE_VALUE; + pShmNode->isReadonly = sqlite3_uri_boolean(pDbFd->zPath,"readonly_shm",0); + rc = winHandleOpen(pNew->zFilename, &pShmNode->isReadonly, &h); + pShmNode->hSharedShm = h; } - if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1; - rc = winLockSharedMemory(pShmNode); - if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err; + /* If successful, link the new winShmNode into the global list. If an + ** error occurred, free the object. */ + if( rc==SQLITE_OK ){ + pShmNode->pNext = winShmNodeList; + winShmNodeList = pShmNode; + pNew = 0; + }else{ + sqlite3_mutex_free(pShmNode->mutex); + if( pShmNode->hSharedShm!=INVALID_HANDLE_VALUE ){ + osCloseHandle(pShmNode->hSharedShm); + } + } } - /* Make the new connection a child of the winShmNode */ - p->pShmNode = pShmNode; + /* If no error has occurred, link the winShm object to the winShmNode and + ** the winShm to pDbFd. */ + if( rc==SQLITE_OK ){ + sqlite3_mutex_enter(pShmNode->mutex); + p->pShmNode = pShmNode; + p->pWinShmNext = pShmNode->pWinShmList; + pShmNode->pWinShmList = p; #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) - p->id = pShmNode->nextShmId++; + p->id = pShmNode->nextShmId++; #endif - pShmNode->nRef++; - pDbFd->pShm = p; + pDbFd->pShm = p; + sqlite3_mutex_leave(pShmNode->mutex); + }else if( p ){ + sqlite3_free(p); + } + + assert( rc!=SQLITE_OK || pShmNode->isUnlocked==0 || pShmNode->nRegion==0 ); winShmLeaveMutex(); + sqlite3_free(pNew); - /* The reference count on pShmNode has already been incremented under - ** the cover of the winShmEnterMutex() mutex and the pointer from the - ** new (struct winShm) object to the pShmNode has been set. All that is - ** left to do is to link the new object into the linked list starting - ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex - ** mutex. - */ - sqlite3_mutex_enter(pShmNode->mutex); - p->pNext = pShmNode->pFirst; - pShmNode->pFirst = p; - sqlite3_mutex_leave(pShmNode->mutex); - return rc; + /* Open a file-handle on the *-shm file for this connection. This file-handle + ** is only used for locking. The mapping of the *-shm file is created using + ** the shared file handle in winShmNode.hSharedShm. */ + if( rc==SQLITE_OK && pShmNode->bUseSharedLockHandle==0 ){ + p->bReadonly = sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0); + rc = winHandleOpen(pShmNode->zFilename, &p->bReadonly, &p->hShm); + if( rc!=SQLITE_OK ){ + assert( p->hShm==INVALID_HANDLE_VALUE ); + winCloseSharedMemory(pDbFd, 0); + } + } - /* Jump here on any error */ -shm_open_err: - winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); - winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */ - sqlite3_free(p); - sqlite3_free(pNew); - winShmLeaveMutex(); return rc; } @@ -50762,38 +52668,7 @@ static int winShmUnmap( sqlite3_file *fd, /* Database holding shared memory */ int deleteFlag /* Delete after closing if true */ ){ - winFile *pDbFd; /* Database holding shared-memory */ - winShm *p; /* The connection to be closed */ - winShmNode *pShmNode; /* The underlying shared-memory file */ - winShm **pp; /* For looping over sibling connections */ - - pDbFd = (winFile*)fd; - p = pDbFd->pShm; - if( p==0 ) return SQLITE_OK; - pShmNode = p->pShmNode; - - /* Remove connection p from the set of connections associated - ** with pShmNode */ - sqlite3_mutex_enter(pShmNode->mutex); - for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){} - *pp = p->pNext; - - /* Free the connection p */ - sqlite3_free(p); - pDbFd->pShm = 0; - sqlite3_mutex_leave(pShmNode->mutex); - - /* If pShmNode->nRef has reached 0, then close the underlying - ** shared-memory file, too */ - winShmEnterMutex(); - assert( pShmNode->nRef>0 ); - pShmNode->nRef--; - if( pShmNode->nRef==0 ){ - winShmPurge(pDbFd->pVfs, deleteFlag); - } - winShmLeaveMutex(); - - return SQLITE_OK; + return winCloseSharedMemory((winFile*)fd, deleteFlag); } /* @@ -50807,10 +52682,9 @@ static int winShmLock( ){ winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */ winShm *p = pDbFd->pShm; /* The shared memory being locked */ - winShm *pX; /* For looping over all siblings */ winShmNode *pShmNode; int rc = SQLITE_OK; /* Result code */ - u16 mask; /* Mask of locks to take or release */ + u16 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst)); /* Mask of locks to [un]take */ if( p==0 ) return SQLITE_IOERR_SHMLOCK; pShmNode = p->pShmNode; @@ -50824,85 +52698,127 @@ static int winShmLock( || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) ); assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 ); - mask = (u16)((1U<<(ofst+n)) - (1U<<ofst)); - assert( n>1 || mask==(1<<ofst) ); - sqlite3_mutex_enter(pShmNode->mutex); - if( flags & SQLITE_SHM_UNLOCK ){ - u16 allMask = 0; /* Mask of locks held by siblings */ + /* Check that, if this to be a blocking lock, no locks that occur later + ** in the following list than the lock being obtained are already held: + ** + ** 1. Recovery lock (ofst==2). + ** 2. Checkpointer lock (ofst==1). + ** 3. Write lock (ofst==0). + ** 4. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK). + ** + ** In other words, if this is a blocking lock, none of the locks that + ** occur later in the above list than the lock being obtained may be + ** held. + */ +#if defined(SQLITE_ENABLE_SETLK_TIMEOUT) && defined(SQLITE_DEBUG) + { + u16 lockMask = (p->exclMask|p->sharedMask); + assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || ( + (ofst!=2 || lockMask==0) + && (ofst!=1 || lockMask==0 || lockMask==2) + && (ofst!=0 || lockMask<3) + && (ofst<3 || lockMask<(1<<ofst)) + )); + } +#endif - /* See if any siblings hold this same lock */ - for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ - if( pX==p ) continue; - assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 ); - allMask |= pX->sharedMask; - } + /* Check if there is any work to do. There are three cases: + ** + ** a) An unlock operation where there are locks to unlock, + ** b) An shared lock where the requested lock is not already held + ** c) An exclusive lock where the requested lock is not already held + ** + ** The SQLite core never requests an exclusive lock that it already holds. + ** This is assert()ed immediately below. */ + assert( flags!=(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK) + || 0==(p->exclMask & mask) + ); + if( ((flags & SQLITE_SHM_UNLOCK) && ((p->exclMask|p->sharedMask) & mask)) + || (flags==(SQLITE_SHM_SHARED|SQLITE_SHM_LOCK) && 0==(p->sharedMask & mask)) + || (flags==(SQLITE_SHM_EXCLUSIVE|SQLITE_SHM_LOCK)) + ){ + HANDLE h = p->hShm; - /* Unlock the system-level locks */ - if( (mask & allMask)==0 ){ - rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n); - }else{ - rc = SQLITE_OK; - } + if( flags & SQLITE_SHM_UNLOCK ){ + /* Case (a) - unlock. */ - /* Undo the local locks */ - if( rc==SQLITE_OK ){ - p->exclMask &= ~mask; - p->sharedMask &= ~mask; - } - }else if( flags & SQLITE_SHM_SHARED ){ - u16 allShared = 0; /* Union of locks held by connections other than "p" */ + assert( (p->exclMask & p->sharedMask)==0 ); + assert( !(flags & SQLITE_SHM_EXCLUSIVE) || (p->exclMask & mask)==mask ); + assert( !(flags & SQLITE_SHM_SHARED) || (p->sharedMask & mask)==mask ); - /* Find out which shared locks are already held by sibling connections. - ** If any sibling already holds an exclusive lock, go ahead and return - ** SQLITE_BUSY. - */ - for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ - if( (pX->exclMask & mask)!=0 ){ - rc = SQLITE_BUSY; - break; + assert( !(flags & SQLITE_SHM_SHARED) || n==1 ); + if( pShmNode->bUseSharedLockHandle ){ + h = pShmNode->hSharedShm; + if( flags & SQLITE_SHM_SHARED ){ + winShm *pShm; + sqlite3_mutex_enter(pShmNode->mutex); + for(pShm=pShmNode->pWinShmList; pShm; pShm=pShm->pWinShmNext){ + if( pShm!=p && (pShm->sharedMask & mask) ){ + /* Another connection within this process is also holding this + ** SHARED lock. So do not actually release the OS lock. */ + h = INVALID_HANDLE_VALUE; + break; + } + } + sqlite3_mutex_leave(pShmNode->mutex); + } } - allShared |= pX->sharedMask; - } - /* Get shared locks at the system level, if necessary */ - if( rc==SQLITE_OK ){ - if( (allShared & mask)==0 ){ - rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n); - }else{ - rc = SQLITE_OK; + if( h!=INVALID_HANDLE_VALUE ){ + rc = winHandleUnlock(h, ofst+WIN_SHM_BASE, n); } - } - /* Get the local shared locks */ - if( rc==SQLITE_OK ){ - p->sharedMask |= mask; - } - }else{ - /* Make sure no sibling connections hold locks that will block this - ** lock. If any do, return SQLITE_BUSY right away. - */ - for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ - if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){ - rc = SQLITE_BUSY; - break; + /* If successful, also clear the bits in sharedMask/exclMask */ + if( rc==SQLITE_OK ){ + p->exclMask = (p->exclMask & ~mask); + p->sharedMask = (p->sharedMask & ~mask); + } + }else{ + int bExcl = ((flags & SQLITE_SHM_EXCLUSIVE) ? 1 : 0); + DWORD nMs = winFileBusyTimeout(pDbFd); + + if( pShmNode->bUseSharedLockHandle ){ + winShm *pShm; + h = pShmNode->hSharedShm; + sqlite3_mutex_enter(pShmNode->mutex); + for(pShm=pShmNode->pWinShmList; pShm; pShm=pShm->pWinShmNext){ + if( bExcl ){ + if( (pShm->sharedMask|pShm->exclMask) & mask ){ + rc = SQLITE_BUSY; + h = INVALID_HANDLE_VALUE; + } + }else{ + if( pShm->sharedMask & mask ){ + h = INVALID_HANDLE_VALUE; + }else if( pShm->exclMask & mask ){ + rc = SQLITE_BUSY; + h = INVALID_HANDLE_VALUE; + } + } + } + sqlite3_mutex_leave(pShmNode->mutex); } - } - /* Get the exclusive locks at the system level. Then if successful - ** also mark the local connection as being locked. - */ - if( rc==SQLITE_OK ){ - rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n); + if( h!=INVALID_HANDLE_VALUE ){ + rc = winHandleLockTimeout(h, ofst+WIN_SHM_BASE, n, bExcl, nMs); + } if( rc==SQLITE_OK ){ - assert( (p->sharedMask & mask)==0 ); - p->exclMask |= mask; + if( bExcl ){ + p->exclMask = (p->exclMask | mask); + }else{ + p->sharedMask = (p->sharedMask | mask); + } } } } - sqlite3_mutex_leave(pShmNode->mutex); - OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n", - osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask, - sqlite3ErrName(rc))); + + OSTRACE(( + "SHM-LOCK(%d,%d,%d) pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x," + " rc=%s\n", + ofst, n, flags, + osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask, + sqlite3ErrName(rc)) + ); return rc; } @@ -50964,15 +52880,17 @@ static int winShmMap( sqlite3_mutex_enter(pShmNode->mutex); if( pShmNode->isUnlocked ){ - rc = winLockSharedMemory(pShmNode); + /* Take the DMS lock. */ + assert( pShmNode->nRegion==0 ); + rc = winLockSharedMemory(pShmNode, winFileBusyTimeout(pDbFd)); if( rc!=SQLITE_OK ) goto shmpage_out; - pShmNode->isUnlocked = 0; } - assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); + assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); if( pShmNode->nRegion<=iRegion ){ + HANDLE hShared = pShmNode->hSharedShm; struct ShmRegion *apNew; /* New aRegion[] array */ - int nByte = (iRegion+1)*szRegion; /* Minimum required file size */ + i64 nByte = ((i64)iRegion+1)*(i64)szRegion; /* Minimum file size */ sqlite3_int64 sz; /* Current size of wal-index file */ pShmNode->szRegion = szRegion; @@ -50981,10 +52899,9 @@ static int winShmMap( ** Check to see if it has been allocated (i.e. if the wal-index file is ** large enough to contain the requested region). */ - rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz); + rc = winHandleSize(hShared, &sz); if( rc!=SQLITE_OK ){ - rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(), - "winShmMap1", pDbFd->zPath); + rc = winLogError(rc, osGetLastError(), "winShmMap1", pDbFd->zPath); goto shmpage_out; } @@ -50993,20 +52910,18 @@ static int winShmMap( ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned. ** ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate - ** the requested memory region. - */ + ** the requested memory region. */ if( !isWrite ) goto shmpage_out; - rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte); + rc = winHandleTruncate(hShared, nByte); if( rc!=SQLITE_OK ){ - rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(), - "winShmMap2", pDbFd->zPath); + rc = winLogError(rc, osGetLastError(), "winShmMap2", pDbFd->zPath); goto shmpage_out; } } /* Map the requested memory region into this processes address space. */ - apNew = (struct ShmRegion *)sqlite3_realloc64( - pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0]) + apNew = (struct ShmRegion*)sqlite3_realloc64( + pShmNode->aRegion, ((i64)iRegion+1)*sizeof(apNew[0]) ); if( !apNew ){ rc = SQLITE_IOERR_NOMEM_BKPT; @@ -51023,32 +52938,24 @@ static int winShmMap( HANDLE hMap = NULL; /* file-mapping handle */ void *pMap = 0; /* Mapped memory region */ -#if SQLITE_OS_WINRT - hMap = osCreateFileMappingFromApp(pShmNode->hFile.h, - NULL, protect, nByte, NULL - ); -#elif defined(SQLITE_WIN32_HAS_WIDE) - hMap = osCreateFileMappingW(pShmNode->hFile.h, - NULL, protect, 0, nByte, NULL - ); -#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA - hMap = osCreateFileMappingA(pShmNode->hFile.h, - NULL, protect, 0, nByte, NULL - ); +#ifdef SQLITE_UWP + hMap = osCreateFileMappingFromApp(hShared, NULL, protect, nByte, NULL); +#else + hMap = osCreateFileMappingW(hShared, NULL, protect, 0, nByte, NULL); #endif - OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n", + OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%lld, rc=%s\n", osGetCurrentProcessId(), pShmNode->nRegion, nByte, hMap ? "ok" : "failed")); if( hMap ){ - int iOffset = pShmNode->nRegion*szRegion; + i64 iOffset = pShmNode->nRegion*szRegion; int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; -#if SQLITE_OS_WINRT +#ifdef SQLITE_UWP pMap = osMapViewOfFileFromApp(hMap, flags, - iOffset - iOffsetShift, szRegion + iOffsetShift + iOffset - iOffsetShift, (i64)szRegion + iOffsetShift ); #else pMap = osMapViewOfFile(hMap, flags, - 0, iOffset - iOffsetShift, szRegion + iOffsetShift + 0, iOffset - iOffsetShift, (i64)szRegion + iOffsetShift ); #endif OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n", @@ -51071,14 +52978,16 @@ static int winShmMap( shmpage_out: if( pShmNode->nRegion>iRegion ){ - int iOffset = iRegion*szRegion; + i64 iOffset = (i64)iRegion*(i64)szRegion; int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity; char *p = (char *)pShmNode->aRegion[iRegion].pMap; *pp = (void *)&p[iOffsetShift]; }else{ *pp = 0; } - if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY; + if( pShmNode->isReadonly && rc==SQLITE_OK ){ + rc = SQLITE_READONLY; + } sqlite3_mutex_leave(pShmNode->mutex); return rc; } @@ -51181,16 +53090,12 @@ static int winMapfile(winFile *pFd, sqlite3_int64 nByte){ flags |= FILE_MAP_WRITE; } #endif -#if SQLITE_OS_WINRT +#ifdef SQLITE_UWP pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL); -#elif defined(SQLITE_WIN32_HAS_WIDE) +#else pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect, (DWORD)((nMap>>32) & 0xffffffff), (DWORD)(nMap & 0xffffffff), NULL); -#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA - pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect, - (DWORD)((nMap>>32) & 0xffffffff), - (DWORD)(nMap & 0xffffffff), NULL); #endif if( pFd->hMap==NULL ){ pFd->lastErrno = osGetLastError(); @@ -51203,7 +53108,7 @@ static int winMapfile(winFile *pFd, sqlite3_int64 nByte){ } assert( (nMap % winSysInfo.dwPageSize)==0 ); assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff ); -#if SQLITE_OS_WINRT +#ifdef SQLITE_UWP pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap); #else pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap); @@ -51398,47 +53303,6 @@ static winVfsAppData winNolockAppData = { ** sqlite3_vfs object. */ -#if defined(__CYGWIN__) -/* -** Convert a filename from whatever the underlying operating system -** supports for filenames into UTF-8. Space to hold the result is -** obtained from malloc and must be freed by the calling function. -*/ -static char *winConvertToUtf8Filename(const void *zFilename){ - char *zConverted = 0; - if( osIsNT() ){ - zConverted = winUnicodeToUtf8(zFilename); - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI()); - } -#endif - /* caller will handle out of memory */ - return zConverted; -} -#endif - -/* -** Convert a UTF-8 filename into whatever form the underlying -** operating system wants filenames in. Space to hold the result -** is obtained from malloc and must be freed by the calling -** function. -*/ -static void *winConvertFromUtf8Filename(const char *zFilename){ - void *zConverted = 0; - if( osIsNT() ){ - zConverted = winUtf8ToUnicode(zFilename); - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI()); - } -#endif - /* caller will handle out of memory */ - return zConverted; -} - /* ** This function returns non-zero if the specified UTF-8 string buffer ** ends with a directory separator character or one was successfully @@ -51451,7 +53315,14 @@ static int winMakeEndInDirSep(int nBuf, char *zBuf){ if( winIsDirSep(zBuf[nLen-1]) ){ return 1; }else if( nLen+1<nBuf ){ - zBuf[nLen] = winGetDirSep(); + if( !osGetenv ){ + zBuf[nLen] = winGetDirSep(); + }else if( winIsDriveLetterAndColon(zBuf) && winIsDirSep(zBuf[2]) ){ + zBuf[nLen] = '\\'; + zBuf[2]='\\'; + }else{ + zBuf[nLen] = '/'; + } zBuf[nLen+1] = '\0'; return 1; } @@ -51478,14 +53349,14 @@ static int winTempDirDefined(void){ ** The pointer returned in pzBuf must be freed via sqlite3_free(). */ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ - static char zChars[] = + static const char zChars[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789"; size_t i, j; DWORD pid; int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX); - int nMax, nBuf, nDir, nLen; + i64 nMax, nBuf, nDir, nLen; char *zBuf; /* It's odd to simulate an io-error here, but really this is just @@ -51497,7 +53368,8 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ /* Allocate a temporary buffer to store the fully qualified file ** name for the temporary file. If this fails, we cannot continue. */ - nMax = pVfs->mxPathname; nBuf = nMax + 2; + nMax = pVfs->mxPathname; + nBuf = 2 + (i64)nMax; zBuf = sqlite3MallocZero( nBuf ); if( !zBuf ){ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); @@ -51528,7 +53400,7 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ } #if defined(__CYGWIN__) - else{ + else if( osGetenv!=NULL ){ static const char *azDirs[] = { 0, /* getenv("SQLITE_TMPDIR") */ 0, /* getenv("TMPDIR") */ @@ -51544,20 +53416,20 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ unsigned int i; const char *zDir = 0; - if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR"); - if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR"); - if( !azDirs[2] ) azDirs[2] = getenv("TMP"); - if( !azDirs[3] ) azDirs[3] = getenv("TEMP"); - if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE"); + if( !azDirs[0] ) azDirs[0] = osGetenv("SQLITE_TMPDIR"); + if( !azDirs[1] ) azDirs[1] = osGetenv("TMPDIR"); + if( !azDirs[2] ) azDirs[2] = osGetenv("TMP"); + if( !azDirs[3] ) azDirs[3] = osGetenv("TEMP"); + if( !azDirs[4] ) azDirs[4] = osGetenv("USERPROFILE"); for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){ - void *zConverted; + LPWSTR zConverted; if( zDir==0 ) continue; /* If the path starts with a drive letter followed by the colon ** character, assume it is already a native Win32 path; otherwise, ** it must be converted to a native Win32 path via the Cygwin API ** prior to using it. */ - if( winIsDriveLetterAndColon(zDir) ){ + { zConverted = winConvertFromUtf8Filename(zDir); if( !zConverted ){ sqlite3_free(zBuf); @@ -51570,45 +53442,12 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ break; } sqlite3_free(zConverted); - }else{ - zConverted = sqlite3MallocZero( nMax+1 ); - if( !zConverted ){ - sqlite3_free(zBuf); - OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); - return SQLITE_IOERR_NOMEM_BKPT; - } - if( cygwin_conv_path( - osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir, - zConverted, nMax+1)<0 ){ - sqlite3_free(zConverted); - sqlite3_free(zBuf); - OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n")); - return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno, - "winGetTempname2", zDir); - } - if( winIsDir(zConverted) ){ - /* At this point, we know the candidate directory exists and should - ** be used. However, we may need to convert the string containing - ** its name into UTF-8 (i.e. if it is UTF-16 right now). - */ - char *zUtf8 = winConvertToUtf8Filename(zConverted); - if( !zUtf8 ){ - sqlite3_free(zConverted); - sqlite3_free(zBuf); - OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); - return SQLITE_IOERR_NOMEM_BKPT; - } - sqlite3_snprintf(nMax, zBuf, "%s", zUtf8); - sqlite3_free(zUtf8); - sqlite3_free(zConverted); - break; - } - sqlite3_free(zConverted); } } } -#elif !SQLITE_OS_WINRT && !defined(__CYGWIN__) - else if( osIsNT() ){ +#endif + + else{ char *zMulti; LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) ); if( !zWidePath ){ @@ -51616,7 +53455,7 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } - if( osGetTempPathW(nMax, zWidePath)==0 ){ + if( osGetTempPathW==0 || osGetTempPathW(nMax, zWidePath)==0 ){ sqlite3_free(zWidePath); sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n")); @@ -51624,44 +53463,16 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ "winGetTempname2", 0); } zMulti = winUnicodeToUtf8(zWidePath); + sqlite3_free(zWidePath); if( zMulti ){ sqlite3_snprintf(nMax, zBuf, "%s", zMulti); sqlite3_free(zMulti); - sqlite3_free(zWidePath); }else{ - sqlite3_free(zWidePath); sqlite3_free(zBuf); OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); return SQLITE_IOERR_NOMEM_BKPT; } } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - char *zUtf8; - char *zMbcsPath = sqlite3MallocZero( nMax ); - if( !zMbcsPath ){ - sqlite3_free(zBuf); - OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); - return SQLITE_IOERR_NOMEM_BKPT; - } - if( osGetTempPathA(nMax, zMbcsPath)==0 ){ - sqlite3_free(zBuf); - OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n")); - return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(), - "winGetTempname3", 0); - } - zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI()); - if( zUtf8 ){ - sqlite3_snprintf(nMax, zBuf, "%s", zUtf8); - sqlite3_free(zUtf8); - }else{ - sqlite3_free(zBuf); - OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); - return SQLITE_IOERR_NOMEM_BKPT; - } - } -#endif /* SQLITE_WIN32_HAS_ANSI */ -#endif /* !SQLITE_OS_WINRT */ /* ** Check to make sure the temporary directory ends with an appropriate @@ -51715,27 +53526,20 @@ static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){ ** it is something other than a directory, or if there is any kind of memory ** allocation failure. */ -static int winIsDir(const void *zConverted){ +static int winIsDir(LPCWSTR zConverted){ DWORD attr; int rc = 0; DWORD lastErrno; - - if( osIsNT() ){ - int cnt = 0; - WIN32_FILE_ATTRIBUTE_DATA sAttrData; - memset(&sAttrData, 0, sizeof(sAttrData)); - while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted, - GetFileExInfoStandard, - &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){} - if( !rc ){ - return 0; /* Invalid name? */ - } - attr = sAttrData.dwFileAttributes; -#if SQLITE_OS_WINCE==0 - }else{ - attr = osGetFileAttributesA((char*)zConverted); -#endif + int cnt = 0; + WIN32_FILE_ATTRIBUTE_DATA sAttrData; + memset(&sAttrData, 0, sizeof(sAttrData)); + while( !(rc = osGetFileAttributesExW(zConverted, + GetFileExInfoStandard, + &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){} + if( !rc ){ + return 0; /* Invalid name? */ } + attr = sAttrData.dwFileAttributes; return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY); } @@ -51747,6 +53551,12 @@ static int winAccess( int *pResOut /* OUT: Result */ ); +/* +** The Windows version of xAccess() accepts an extra bit in the flags +** parameter that prevents an anti-virus retry loop. +*/ +#define NORETRY 0x4000 + /* ** Open a file. */ @@ -51763,14 +53573,12 @@ static int winOpen( DWORD dwShareMode; DWORD dwCreationDisposition; DWORD dwFlagsAndAttributes = 0; -#if SQLITE_OS_WINCE - int isTemp = 0; -#endif winVfsAppData *pAppData; winFile *pFile = (winFile*)id; - void *zConverted; /* Filename in OS encoding */ + LPWSTR zConverted; /* Filename in OS encoding */ const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */ int cnt = 0; + int isRO = 0; /* file is known to be accessible readonly */ /* If argument zPath is a NULL pointer, this function is required to open ** a temporary file. Use this buffer to store the file name in. @@ -51778,8 +53586,8 @@ static int winOpen( char *zTmpname = 0; /* For temporary filename, if necessary. */ int rc = SQLITE_OK; /* Function Return Code */ -#if !defined(NDEBUG) || SQLITE_OS_WINCE - int eType = flags&0xFFFFFF00; /* Type of file to open */ +#if !defined(NDEBUG) + int eType = flags&0x0FFF00; /* Type of file to open */ #endif int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); @@ -51829,13 +53637,6 @@ static int winOpen( memset(pFile, 0, sizeof(winFile)); pFile->h = INVALID_HANDLE_VALUE; -#if SQLITE_OS_WINRT - if( !zUtf8Name && !sqlite3_temp_directory ){ - sqlite3_log(SQLITE_ERROR, - "sqlite3_temp_directory variable should be set for WinRT"); - } -#endif - /* If the second argument to this function is NULL, generate a ** temporary file name to use */ @@ -51900,87 +53701,28 @@ static int winOpen( } if( isDelete ){ -#if SQLITE_OS_WINCE - dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN; - isTemp = 1; -#else dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY | FILE_ATTRIBUTE_HIDDEN | FILE_FLAG_DELETE_ON_CLOSE; -#endif }else{ dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; } - /* Reports from the internet are that performance is always - ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */ -#if SQLITE_OS_WINCE - dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS; -#endif - - if( osIsNT() ){ -#if SQLITE_OS_WINRT - CREATEFILE2_EXTENDED_PARAMETERS extendedParameters; - extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS); - extendedParameters.dwFileAttributes = - dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK; - extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK; - extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS; - extendedParameters.lpSecurityAttributes = NULL; - extendedParameters.hTemplateFile = NULL; - do{ - h = osCreateFile2((LPCWSTR)zConverted, - dwDesiredAccess, - dwShareMode, - dwCreationDisposition, - &extendedParameters); - if( h!=INVALID_HANDLE_VALUE ) break; - if( isReadWrite ){ - int rc2, isRO = 0; - sqlite3BeginBenignMalloc(); - rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO); - sqlite3EndBenignMalloc(); - if( rc2==SQLITE_OK && isRO ) break; - } - }while( winRetryIoerr(&cnt, &lastErrno) ); -#else - do{ - h = osCreateFileW((LPCWSTR)zConverted, - dwDesiredAccess, - dwShareMode, NULL, - dwCreationDisposition, - dwFlagsAndAttributes, - NULL); - if( h!=INVALID_HANDLE_VALUE ) break; - if( isReadWrite ){ - int rc2, isRO = 0; - sqlite3BeginBenignMalloc(); - rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO); - sqlite3EndBenignMalloc(); - if( rc2==SQLITE_OK && isRO ) break; - } - }while( winRetryIoerr(&cnt, &lastErrno) ); -#endif - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - do{ - h = osCreateFileA((LPCSTR)zConverted, - dwDesiredAccess, - dwShareMode, NULL, - dwCreationDisposition, - dwFlagsAndAttributes, - NULL); - if( h!=INVALID_HANDLE_VALUE ) break; - if( isReadWrite ){ - int rc2, isRO = 0; - sqlite3BeginBenignMalloc(); - rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ, &isRO); - sqlite3EndBenignMalloc(); - if( rc2==SQLITE_OK && isRO ) break; - } - }while( winRetryIoerr(&cnt, &lastErrno) ); - } -#endif + do{ + h = osCreateFileW(zConverted, + dwDesiredAccess, + dwShareMode, NULL, + dwCreationDisposition, + dwFlagsAndAttributes, + NULL); + if( h!=INVALID_HANDLE_VALUE ) break; + if( isReadWrite ){ + int rc2; + sqlite3BeginBenignMalloc(); + rc2 = winAccess(pVfs, zUtf8Name, SQLITE_ACCESS_READ|NORETRY, &isRO); + sqlite3EndBenignMalloc(); + if( rc2==SQLITE_OK && isRO ) break; + } + }while( winRetryIoerr(&cnt, &lastErrno) ); winLogIoerr(cnt, __LINE__); OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name, @@ -51989,7 +53731,7 @@ static int winOpen( if( h==INVALID_HANDLE_VALUE ){ sqlite3_free(zConverted); sqlite3_free(zTmpname); - if( isReadWrite && !isExclusive ){ + if( isReadWrite && isRO && !isExclusive ){ return winOpen(pVfs, zName, id, ((flags|SQLITE_OPEN_READONLY) & ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), @@ -52015,27 +53757,7 @@ static int winOpen( pAppData = (winVfsAppData*)pVfs->pAppData; -#if SQLITE_OS_WINCE - { - if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB - && ((pAppData==NULL) || !pAppData->bNoLock) - && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK - ){ - osCloseHandle(h); - sqlite3_free(zConverted); - sqlite3_free(zTmpname); - OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc))); - return rc; - } - } - if( isTemp ){ - pFile->zDeleteOnClose = zConverted; - }else -#endif - { - sqlite3_free(zConverted); - } - + sqlite3_free(zConverted); sqlite3_free(zTmpname); id->pMethods = pAppData ? pAppData->pMethod : &winIoMethod; pFile->pVfs = pVfs; @@ -52082,7 +53804,7 @@ static int winDelete( int rc; DWORD attr; DWORD lastErrno = 0; - void *zConverted; + LPWSTR zConverted; UNUSED_PARAMETER(pVfs); UNUSED_PARAMETER(syncDir); @@ -52094,80 +53816,31 @@ static int winDelete( OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); return SQLITE_IOERR_NOMEM_BKPT; } - if( osIsNT() ){ - do { -#if SQLITE_OS_WINRT - WIN32_FILE_ATTRIBUTE_DATA sAttrData; - memset(&sAttrData, 0, sizeof(sAttrData)); - if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard, - &sAttrData) ){ - attr = sAttrData.dwFileAttributes; + do { + attr = osGetFileAttributesW(zConverted); + if ( attr==INVALID_FILE_ATTRIBUTES ){ + lastErrno = osGetLastError(); + if( lastErrno==ERROR_FILE_NOT_FOUND + || lastErrno==ERROR_PATH_NOT_FOUND ){ + rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ }else{ - lastErrno = osGetLastError(); - if( lastErrno==ERROR_FILE_NOT_FOUND - || lastErrno==ERROR_PATH_NOT_FOUND ){ - rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ - }else{ - rc = SQLITE_ERROR; - } - break; - } -#else - attr = osGetFileAttributesW(zConverted); -#endif - if ( attr==INVALID_FILE_ATTRIBUTES ){ - lastErrno = osGetLastError(); - if( lastErrno==ERROR_FILE_NOT_FOUND - || lastErrno==ERROR_PATH_NOT_FOUND ){ - rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ - }else{ - rc = SQLITE_ERROR; - } - break; - } - if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ - rc = SQLITE_ERROR; /* Files only. */ - break; - } - if ( osDeleteFileW(zConverted) ){ - rc = SQLITE_OK; /* Deleted OK. */ - break; - } - if ( !winRetryIoerr(&cnt, &lastErrno) ){ - rc = SQLITE_ERROR; /* No more retries. */ - break; - } - } while(1); - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - do { - attr = osGetFileAttributesA(zConverted); - if ( attr==INVALID_FILE_ATTRIBUTES ){ - lastErrno = osGetLastError(); - if( lastErrno==ERROR_FILE_NOT_FOUND - || lastErrno==ERROR_PATH_NOT_FOUND ){ - rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ - }else{ - rc = SQLITE_ERROR; - } - break; - } - if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ - rc = SQLITE_ERROR; /* Files only. */ - break; - } - if ( osDeleteFileA(zConverted) ){ - rc = SQLITE_OK; /* Deleted OK. */ - break; - } - if ( !winRetryIoerr(&cnt, &lastErrno) ){ - rc = SQLITE_ERROR; /* No more retries. */ - break; + rc = SQLITE_ERROR; } - } while(1); - } -#endif + break; + } + if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ + rc = SQLITE_ERROR; /* Files only. */ + break; + } + if ( osDeleteFileW(zConverted) ){ + rc = SQLITE_OK; /* Deleted OK. */ + break; + } + if ( !winRetryIoerr(&cnt, &lastErrno) ){ + rc = SQLITE_ERROR; /* No more retries. */ + break; + } + } while(1); if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){ rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename); }else{ @@ -52189,10 +53862,18 @@ static int winAccess( ){ DWORD attr; int rc = 0; + int cnt = 0; DWORD lastErrno = 0; - void *zConverted; + LPWSTR zConverted; + int noRetry = 0; /* Do not use winRetryIoerr() */ + WIN32_FILE_ATTRIBUTE_DATA sAttrData; UNUSED_PARAMETER(pVfs); + if( (flags & NORETRY)!=0 ){ + noRetry = 1; + flags &= ~NORETRY; + } + SimulateIOError( return SQLITE_IOERR_ACCESS; ); OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n", zFilename, flags, pResOut)); @@ -52209,40 +53890,35 @@ static int winAccess( OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); return SQLITE_IOERR_NOMEM_BKPT; } - if( osIsNT() ){ - int cnt = 0; - WIN32_FILE_ATTRIBUTE_DATA sAttrData; - memset(&sAttrData, 0, sizeof(sAttrData)); - while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted, - GetFileExInfoStandard, - &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){} - if( rc ){ - /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file - ** as if it does not exist. - */ - if( flags==SQLITE_ACCESS_EXISTS - && sAttrData.nFileSizeHigh==0 - && sAttrData.nFileSizeLow==0 ){ - attr = INVALID_FILE_ATTRIBUTES; - }else{ - attr = sAttrData.dwFileAttributes; - } + memset(&sAttrData, 0, sizeof(sAttrData)); + while( !(rc = osGetFileAttributesExW(zConverted, + GetFileExInfoStandard, + &sAttrData)) + && !noRetry + && winRetryIoerr(&cnt, &lastErrno) + ){ /* Loop until true */} + if( rc ){ + /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file + ** as if it does not exist. + */ + if( flags==SQLITE_ACCESS_EXISTS + && sAttrData.nFileSizeHigh==0 + && sAttrData.nFileSizeLow==0 ){ + attr = INVALID_FILE_ATTRIBUTES; }else{ - winLogIoerr(cnt, __LINE__); - if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){ - sqlite3_free(zConverted); - return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", - zFilename); - }else{ - attr = INVALID_FILE_ATTRIBUTES; - } + attr = sAttrData.dwFileAttributes; + } + }else{ + if( noRetry ) lastErrno = osGetLastError(); + winLogIoerr(cnt, __LINE__); + if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){ + sqlite3_free(zConverted); + return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", + zFilename); + }else{ + attr = INVALID_FILE_ATTRIBUTES; } } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - attr = osGetFileAttributesA((char*)zConverted); - } -#endif sqlite3_free(zConverted); switch( flags ){ case SQLITE_ACCESS_READ: @@ -52283,6 +53959,7 @@ static BOOL winIsDriveLetterAndColon( return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ); } +#ifdef _WIN32 /* ** Returns non-zero if the specified path name should be used verbatim. If ** non-zero is returned from this function, the calling function must simply @@ -52319,6 +53996,70 @@ static BOOL winIsVerbatimPathname( */ return FALSE; } +#endif /* _WIN32 */ + +#ifdef __CYGWIN__ +/* +** Simplify a filename into its canonical form +** by making the following changes: +** +** * convert any '/' to '\' (win32) or reverse (Cygwin) +** * removing any trailing and duplicate / (except for UNC paths) +** * convert /./ into just / +** +** Changes are made in-place. Return the new name length. +** +** The original filename is in z[0..]. If the path is shortened, +** no-longer used bytes will be written by '\0'. +*/ +static void winSimplifyName(char *z){ + int i, j; + for(i=j=0; z[i]; ++i){ + if( winIsDirSep(z[i]) ){ +#if !defined(SQLITE_TEST) + /* Some test-cases assume that "./foo" and "foo" are different */ + if( z[i+1]=='.' && winIsDirSep(z[i+2]) ){ + ++i; + continue; + } +#endif + if( !z[i+1] || (winIsDirSep(z[i+1]) && (i!=0)) ){ + continue; + } + z[j++] = osGetenv?'/':'\\'; + }else{ + z[j++] = z[i]; + } + } + while(j<i) z[j++] = '\0'; +} + +#define SQLITE_MAX_SYMLINKS 100 + +static int mkFullPathname( + const char *zPath, /* Input path */ + char *zOut, /* Output buffer */ + int nOut /* Allocated size of buffer zOut */ +){ + int nPath = sqlite3Strlen30(zPath); + int iOff = 0; + if( zPath[0]!='/' ){ + if( osGetcwd(zOut, nOut-2)==0 ){ + return winLogError(SQLITE_CANTOPEN_BKPT, (DWORD)osErrno, "getcwd", zPath); + } + iOff = sqlite3Strlen30(zOut); + zOut[iOff++] = '/'; + } + if( (iOff+nPath+1)>nOut ){ + /* SQLite assumes that xFullPathname() nul-terminates the output buffer + ** even if it returns an error. */ + zOut[iOff] = '\0'; + return SQLITE_CANTOPEN_BKPT; + } + sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath); + return SQLITE_OK; +} +#endif /* __CYGWIN__ */ /* ** Turn a relative pathname into a full pathname. Write the full @@ -52331,11 +54072,9 @@ static int winFullPathnameNoMutex( int nFull, /* Size of output buffer in bytes */ char *zFull /* Output buffer */ ){ -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__) - DWORD nByte; - void *zConverted; + int nByte; + LPWSTR zConverted; char *zOut; -#endif /* If this path name begins with "/X:" or "\\?\", where "X" is any ** alphabetic character, discard the initial "/" from the pathname. @@ -52345,83 +54084,84 @@ static int winFullPathnameNoMutex( zRelative++; } -#if defined(__CYGWIN__) SimulateIOError( return SQLITE_ERROR ); - UNUSED_PARAMETER(nFull); - assert( nFull>=pVfs->mxPathname ); - if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ - /* - ** NOTE: We are dealing with a relative path name and the data - ** directory has been set. Therefore, use it as the basis - ** for converting the relative path name to an absolute - ** one by prepending the data directory and a slash. - */ - char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 ); - if( !zOut ){ - return SQLITE_IOERR_NOMEM_BKPT; - } - if( cygwin_conv_path( - (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) | - CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){ - sqlite3_free(zOut); - return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno, - "winFullPathname1", zRelative); - }else{ - char *zUtf8 = winConvertToUtf8Filename(zOut); - if( !zUtf8 ){ - sqlite3_free(zOut); - return SQLITE_IOERR_NOMEM_BKPT; - } - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", - sqlite3_data_directory, winGetDirSep(), zUtf8); - sqlite3_free(zUtf8); - sqlite3_free(zOut); - } - }else{ - char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 ); - if( !zOut ){ - return SQLITE_IOERR_NOMEM_BKPT; - } - if( cygwin_conv_path( - (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A), - zRelative, zOut, pVfs->mxPathname+1)<0 ){ - sqlite3_free(zOut); - return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno, - "winFullPathname2", zRelative); - }else{ - char *zUtf8 = winConvertToUtf8Filename(zOut); - if( !zUtf8 ){ - sqlite3_free(zOut); - return SQLITE_IOERR_NOMEM_BKPT; - } - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8); - sqlite3_free(zUtf8); - sqlite3_free(zOut); - } - } - return SQLITE_OK; -#endif -#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__) - SimulateIOError( return SQLITE_ERROR ); - /* WinCE has no concept of a relative pathname, or so I am told. */ - /* WinRT has no way to convert a relative path to an absolute one. */ - if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ - /* - ** NOTE: We are dealing with a relative path name and the data - ** directory has been set. Therefore, use it as the basis - ** for converting the relative path name to an absolute - ** one by prepending the data directory and a backslash. - */ - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", - sqlite3_data_directory, winGetDirSep(), zRelative); - }else{ - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative); +#ifdef __CYGWIN__ + if( osGetcwd ){ + zFull[nFull-1] = '\0'; + if( !winIsDriveLetterAndColon(zRelative) || !winIsDirSep(zRelative[2]) ){ + int rc = SQLITE_OK; + int nLink = 1; /* Number of symbolic links followed so far */ + const char *zIn = zRelative; /* Input path for each iteration of loop */ + char *zDel = 0; + struct stat buf; + + UNUSED_PARAMETER(pVfs); + + do { + /* Call lstat() on path zIn. Set bLink to true if the path + ** is a symbolic link, or false otherwise. */ + int bLink = 0; + if( osLstat && osReadlink ) { + if( osLstat(zIn, &buf)!=0 ){ + int myErrno = osErrno; + if( myErrno!=ENOENT ){ + rc = winLogError(SQLITE_CANTOPEN_BKPT, (DWORD)myErrno, + "lstat", zIn); + } + }else{ + bLink = ((buf.st_mode & 0170000) == 0120000); + } + + if( bLink ){ + if( zDel==0 ){ + zDel = sqlite3MallocZero(nFull); + if( zDel==0 ) rc = SQLITE_NOMEM; + }else if( ++nLink>SQLITE_MAX_SYMLINKS ){ + rc = SQLITE_CANTOPEN_BKPT; + } + + if( rc==SQLITE_OK ){ + nByte = osReadlink(zIn, zDel, nFull-1); + if( nByte ==(DWORD)-1 ){ + rc = winLogError(SQLITE_CANTOPEN_BKPT, (DWORD)osErrno, + "readlink", zIn); + }else{ + if( zDel[0]!='/' ){ + int n; + for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--); + if( nByte+n+1>nFull ){ + rc = SQLITE_CANTOPEN_BKPT; + }else{ + memmove(&zDel[n], zDel, nByte+1); + memcpy(zDel, zIn, n); + nByte += n; + } + } + zDel[nByte] = '\0'; + } + } + + zIn = zDel; + } + } + + assert( rc!=SQLITE_OK || zIn!=zFull || zIn[0]=='/' ); + if( rc==SQLITE_OK && zIn!=zFull ){ + rc = mkFullPathname(zIn, zFull, nFull); + } + if( bLink==0 ) break; + zIn = zFull; + }while( rc==SQLITE_OK ); + + sqlite3_free(zDel); + winSimplifyName(zFull); + return rc; + } } - return SQLITE_OK; -#endif +#endif /* __CYGWIN__ */ -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__) +#if defined(_WIN32) /* It's odd to simulate an io-error here, but really this is just ** using the io-error infrastructure to test that SQLite handles this ** function failing. This function could fail if, for example, the @@ -52439,25 +54179,26 @@ static int winFullPathnameNoMutex( sqlite3_data_directory, winGetDirSep(), zRelative); return SQLITE_OK; } +#endif zConverted = winConvertFromUtf8Filename(zRelative); if( zConverted==0 ){ return SQLITE_IOERR_NOMEM_BKPT; } - if( osIsNT() ){ + { LPWSTR zTemp; - nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0); + nByte = osGetFullPathNameW(zConverted, 0, 0, 0); if( nByte==0 ){ sqlite3_free(zConverted); return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), "winFullPathname1", zRelative); } nByte += 3; - zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) ); + zTemp = sqlite3MallocZero( (u64)nByte*sizeof(WCHAR) ); if( zTemp==0 ){ sqlite3_free(zConverted); return SQLITE_IOERR_NOMEM_BKPT; } - nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0); + nByte = osGetFullPathNameW(zConverted, nByte, zTemp, 0); if( nByte==0 ){ sqlite3_free(zConverted); sqlite3_free(zTemp); @@ -52468,41 +54209,32 @@ static int winFullPathnameNoMutex( zOut = winUnicodeToUtf8(zTemp); sqlite3_free(zTemp); } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - char *zTemp; - nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0); - if( nByte==0 ){ - sqlite3_free(zConverted); - return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), - "winFullPathname3", zRelative); - } - nByte += 3; - zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) ); - if( zTemp==0 ){ - sqlite3_free(zConverted); - return SQLITE_IOERR_NOMEM_BKPT; - } - nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0); - if( nByte==0 ){ - sqlite3_free(zConverted); - sqlite3_free(zTemp); - return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), - "winFullPathname4", zRelative); - } - sqlite3_free(zConverted); - zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI()); - sqlite3_free(zTemp); - } -#endif if( zOut ){ +#ifdef __CYGWIN__ + if( memcmp(zOut, "\\\\?\\", 4) ){ + sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut); + }else if( memcmp(zOut+4, "UNC\\", 4) ){ + sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut+4); + }else{ + char *p = zOut+6; + *p = '\\'; + if( osGetcwd ){ + /* On Cygwin, UNC paths use forward slashes */ + while( *p ){ + if( *p=='\\' ) *p = '/'; + ++p; + } + } + sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut+6); + } +#else sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut); +#endif /* __CYGWIN__ */ sqlite3_free(zOut); return SQLITE_OK; }else{ return SQLITE_IOERR_NOMEM_BKPT; } -#endif } static int winFullPathname( sqlite3_vfs *pVfs, /* Pointer to vfs object */ @@ -52525,42 +54257,14 @@ static int winFullPathname( ** within the shared library, and closing the shared library. */ static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){ - HANDLE h; -#if defined(__CYGWIN__) - int nFull = pVfs->mxPathname+1; - char *zFull = sqlite3MallocZero( nFull ); - void *zConverted = 0; - if( zFull==0 ){ - OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); - return 0; - } - if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){ - sqlite3_free(zFull); - OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); - return 0; - } - zConverted = winConvertFromUtf8Filename(zFull); - sqlite3_free(zFull); -#else - void *zConverted = winConvertFromUtf8Filename(zFilename); + HANDLE h = 0; + LPWSTR zConverted = winConvertFromUtf8Filename(zFilename); UNUSED_PARAMETER(pVfs); -#endif if( zConverted==0 ){ OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); return 0; } - if( osIsNT() ){ -#if SQLITE_OS_WINRT - h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0); -#else - h = osLoadLibraryW((LPCWSTR)zConverted); -#endif - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - h = osLoadLibraryA((char*)zConverted); - } -#endif + h = osLoadLibraryW ? osLoadLibraryW(zConverted) : 0; OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h)); sqlite3_free(zConverted); return (void*)h; @@ -52570,16 +54274,16 @@ static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){ winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut); } static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){ - FARPROC proc; + FARPROC proc = 0; UNUSED_PARAMETER(pVfs); - proc = osGetProcAddressA((HANDLE)pH, zSym); + proc = osGetProcAddressA ? osGetProcAddressA((HANDLE)pH, zSym) : 0; OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n", (void*)pH, zSym, (void*)proc)); return (void(*)(void))proc; } static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){ UNUSED_PARAMETER(pVfs); - osFreeLibrary((HANDLE)pHandle); + if( osFreeLibrary!=0 ) osFreeLibrary((HANDLE)pHandle); OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle)); } #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ @@ -52628,41 +54332,37 @@ static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ e.nXor = 0; e.i = 0; { - SYSTEMTIME x; - osGetSystemTime(&x); - xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME)); + FILETIME x; + osGetSystemTimeAsFileTime(&x); + xorMemory(&e, (unsigned char*)&x, sizeof(x)); } { DWORD pid = osGetCurrentProcessId(); - xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD)); + xorMemory(&e, (unsigned char*)&pid, sizeof(pid)); } -#if SQLITE_OS_WINRT { ULONGLONG cnt = osGetTickCount64(); - xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG)); - } -#else - { - DWORD cnt = osGetTickCount(); - xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD)); + xorMemory(&e, (unsigned char*)&cnt, sizeof(cnt)); } -#endif /* SQLITE_OS_WINRT */ { LARGE_INTEGER i; osQueryPerformanceCounter(&i); - xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER)); + xorMemory(&e, (unsigned char*)&i, sizeof(i)); } -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID +#if SQLITE_WIN32_USE_UUID +#ifdef SQLITE_UWP +# error SQLITE_WIN32_USE_UUID is incompatible with SQLITE_UWP +#endif { UUID id; - memset(&id, 0, sizeof(UUID)); + memset(&id, 0, sizeof(id)); osUuidCreate(&id); - xorMemory(&e, (unsigned char*)&id, sizeof(UUID)); + xorMemory(&e, (unsigned char*)&id, sizeof(id)); memset(&id, 0, sizeof(UUID)); osUuidCreateSequential(&id); - xorMemory(&e, (unsigned char*)&id, sizeof(UUID)); + xorMemory(&e, (unsigned char*)&id, sizeof(id)); } -#endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */ +#endif /* SQLITE_WIN32_USE_UUID */ return e.nXor>nBuf ? nBuf : e.nXor; #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */ } @@ -52672,7 +54372,7 @@ static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ ** Sleep for a little while. Return the amount of time slept. */ static int winSleep(sqlite3_vfs *pVfs, int microsec){ - sqlite3_win32_sleep((microsec+999)/1000); + osSleep((microsec+999)/1000); UNUSED_PARAMETER(pVfs); return ((microsec+999)/1000)*1000; } @@ -52710,17 +54410,7 @@ static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){ (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296; -#if SQLITE_OS_WINCE - SYSTEMTIME time; - osGetSystemTime(&time); - /* if SystemTimeToFileTime() fails, it returns zero. */ - if (!osSystemTimeToFileTime(&time,&ft)){ - return SQLITE_ERROR; - } -#else osGetSystemTimeAsFileTime( &ft ); -#endif - *piNow = winFiletimeEpoch + ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000; @@ -52814,7 +54504,6 @@ SQLITE_API int sqlite3_os_init(void){ winGetSystemCall, /* xGetSystemCall */ winNextSystemCall, /* xNextSystemCall */ }; -#if defined(SQLITE_WIN32_HAS_WIDE) static sqlite3_vfs winLongPathVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ @@ -52839,7 +54528,6 @@ SQLITE_API int sqlite3_os_init(void){ winGetSystemCall, /* xGetSystemCall */ winNextSystemCall, /* xNextSystemCall */ }; -#endif static sqlite3_vfs winNolockVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ @@ -52864,7 +54552,6 @@ SQLITE_API int sqlite3_os_init(void){ winGetSystemCall, /* xGetSystemCall */ winNextSystemCall, /* xNextSystemCall */ }; -#if defined(SQLITE_WIN32_HAS_WIDE) static sqlite3_vfs winLongPathNolockVfs = { 3, /* iVersion */ sizeof(winFile), /* szOsFile */ @@ -52889,34 +54576,29 @@ SQLITE_API int sqlite3_os_init(void){ winGetSystemCall, /* xGetSystemCall */ winNextSystemCall, /* xNextSystemCall */ }; -#endif /* Double-check that the aSyscall[] array has been constructed ** correctly. See ticket [bb3a86e890c8e96ab] */ - assert( ArraySize(aSyscall)==80 ); + assert( ArraySize(aSyscall)==60 ); + assert( strcmp(aSyscall[0].zName,"AreFileApisANSI")==0 ); + assert( strcmp(aSyscall[8].zName,"FreeLibrary")==0 ); + assert( strcmp(aSyscall[16].zName,"GetSystemInfo")==0 ); + assert( strcmp(aSyscall[24].zName,"HeapReAlloc")==0 ); + assert( strcmp(aSyscall[32].zName,"MapViewOfFileFromApp")==0 ); + assert( strcmp(aSyscall[40].zName,"UnmapViewOfFile")==0 ); + assert( strcmp(aSyscall[48].zName,"UuidCreate")==0 ); + assert( strcmp(aSyscall[56].zName,"lstat")==0 ); /* get memory map allocation granularity */ memset(&winSysInfo, 0, sizeof(SYSTEM_INFO)); -#if SQLITE_OS_WINRT - osGetNativeSystemInfo(&winSysInfo); -#else osGetSystemInfo(&winSysInfo); -#endif assert( winSysInfo.dwAllocationGranularity>0 ); assert( winSysInfo.dwPageSize>0 ); sqlite3_vfs_register(&winVfs, 1); - -#if defined(SQLITE_WIN32_HAS_WIDE) sqlite3_vfs_register(&winLongPathVfs, 0); -#endif - sqlite3_vfs_register(&winNolockVfs, 0); - -#if defined(SQLITE_WIN32_HAS_WIDE) sqlite3_vfs_register(&winLongPathNolockVfs, 0); -#endif - #ifndef SQLITE_OMIT_WAL winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1); #endif @@ -52925,17 +54607,9 @@ SQLITE_API int sqlite3_os_init(void){ } SQLITE_API int sqlite3_os_end(void){ -#if SQLITE_OS_WINRT - if( sleepObj!=NULL ){ - osCloseHandle(sleepObj); - sleepObj = NULL; - } -#endif - #ifndef SQLITE_OMIT_WAL winBigLock = 0; #endif - return SQLITE_OK; } @@ -53512,13 +55186,13 @@ static int memdbOpen( } if( p==0 ){ MemStore **apNew; - p = sqlite3Malloc( sizeof(*p) + szName + 3 ); + p = sqlite3Malloc( sizeof(*p) + (i64)szName + 3 ); if( p==0 ){ sqlite3_mutex_leave(pVfsMutex); return SQLITE_NOMEM; } apNew = sqlite3Realloc(memdb_g.apMemStore, - sizeof(apNew[0])*(memdb_g.nMemStore+1) ); + sizeof(apNew[0])*(1+(i64)memdb_g.nMemStore) ); if( apNew==0 ){ sqlite3_free(p); sqlite3_mutex_leave(pVfsMutex); @@ -53704,7 +55378,7 @@ SQLITE_API unsigned char *sqlite3_serialize( sqlite3_int64 sz; int szPage = 0; sqlite3_stmt *pStmt = 0; - unsigned char *pOut; + unsigned char *pOut = 0; char *zSql; int rc; @@ -53714,12 +55388,13 @@ SQLITE_API unsigned char *sqlite3_serialize( return 0; } #endif + sqlite3_mutex_enter(db->mutex); if( zSchema==0 ) zSchema = db->aDb[0].zDbSName; p = memdbFromDbSchema(db, zSchema); iDb = sqlite3FindDbName(db, zSchema); if( piSize ) *piSize = -1; - if( iDb<0 ) return 0; + if( iDb<0 ) goto serialize_out; if( p ){ MemStore *pStore = p->pStore; assert( pStore->pMutex==0 ); @@ -53730,19 +55405,17 @@ SQLITE_API unsigned char *sqlite3_serialize( pOut = sqlite3_malloc64( pStore->sz ); if( pOut ) memcpy(pOut, pStore->aData, pStore->sz); } - return pOut; + goto serialize_out; } pBt = db->aDb[iDb].pBt; - if( pBt==0 ) return 0; + if( pBt==0 ) goto serialize_out; szPage = sqlite3BtreeGetPageSize(pBt); zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema); rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM; sqlite3_free(zSql); - if( rc ) return 0; + if( rc ) goto serialize_out; rc = sqlite3_step(pStmt); - if( rc!=SQLITE_ROW ){ - pOut = 0; - }else{ + if( rc==SQLITE_ROW ){ sz = sqlite3_column_int64(pStmt, 0)*szPage; if( sz==0 ){ sqlite3_reset(pStmt); @@ -53776,6 +55449,9 @@ SQLITE_API unsigned char *sqlite3_serialize( } } sqlite3_finalize(pStmt); + + serialize_out: + sqlite3_mutex_leave(db->mutex); return pOut; } @@ -53821,10 +55497,10 @@ SQLITE_API int sqlite3_deserialize( if( rc ) goto end_deserialize; db->init.iDb = (u8)iDb; db->init.reopenMemdb = 1; - rc = sqlite3_step(pStmt); + sqlite3_step(pStmt); db->init.reopenMemdb = 0; - if( rc!=SQLITE_DONE ){ - rc = SQLITE_ERROR; + rc = sqlite3_finalize(pStmt); + if( rc!=SQLITE_OK ){ goto end_deserialize; } p = memdbFromDbSchema(db, zSchema); @@ -53845,7 +55521,6 @@ SQLITE_API int sqlite3_deserialize( } end_deserialize: - sqlite3_finalize(pStmt); if( pData && (mFlags & SQLITE_DESERIALIZE_FREEONCLOSE)!=0 ){ sqlite3_free(pData); } @@ -53951,7 +55626,7 @@ SQLITE_PRIVATE int sqlite3MemdbInit(void){ ** no fewer collisions than the no-op *1. */ #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT) -#define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *)) +#define BITVEC_NPTR ((u32)(BITVEC_USIZE/sizeof(Bitvec *))) /* @@ -53991,6 +55666,7 @@ struct Bitvec { } u; }; + /* ** Create a new bitmap object able to handle bits between 0 and iSize, ** inclusive. Return a pointer to the new object. Return NULL if @@ -54100,7 +55776,9 @@ SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){ }else{ memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); memset(p->u.apSub, 0, sizeof(p->u.apSub)); - p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR; + p->iDivisor = p->iSize/BITVEC_NPTR; + if( (p->iSize%BITVEC_NPTR)!=0 ) p->iDivisor++; + if( p->iDivisor<BITVEC_NBIT ) p->iDivisor = BITVEC_NBIT; rc = sqlite3BitvecSet(p, i); for(j=0; j<BITVEC_NINT; j++){ if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]); @@ -54134,7 +55812,7 @@ SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){ } } if( p->iSize<=BITVEC_NBIT ){ - p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1))); + p->u.aBitmap[i/BITVEC_SZELEM] &= ~(BITVEC_TELEM)(1<<(i&(BITVEC_SZELEM-1))); }else{ unsigned int j; u32 *aiValues = pBuf; @@ -54177,6 +55855,52 @@ SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){ return p->iSize; } +#ifdef SQLITE_DEBUG +/* +** Show the content of a Bitvec option and its children. Indent +** everything by n spaces. Add x to each bitvec value. +** +** From a debugger such as gdb, one can type: +** +** call sqlite3ShowBitvec(p) +** +** For some Bitvec p and see a recursive view of the Bitvec's content. +*/ +static void showBitvec(Bitvec *p, int n, unsigned x){ + int i; + if( p==0 ){ + printf("NULL\n"); + return; + } + printf("Bitvec 0x%p iSize=%u", p, p->iSize); + if( p->iSize<=BITVEC_NBIT ){ + printf(" bitmap\n"); + printf("%*s bits:", n, ""); + for(i=1; i<=BITVEC_NBIT; i++){ + if( sqlite3BitvecTest(p,i) ) printf(" %u", x+(unsigned)i); + } + printf("\n"); + }else if( p->iDivisor==0 ){ + printf(" hash with %u entries\n", p->nSet); + printf("%*s bits:", n, ""); + for(i=0; i<BITVEC_NINT; i++){ + if( p->u.aHash[i] ) printf(" %u", x+(unsigned)p->u.aHash[i]); + } + printf("\n"); + }else{ + printf(" sub-bitvec with iDivisor=%u\n", p->iDivisor); + for(i=0; i<BITVEC_NPTR; i++){ + if( p->u.apSub[i]==0 ) continue; + printf("%*s apSub[%d]=", n, "", i); + showBitvec(p->u.apSub[i], n+4, i*p->iDivisor); + } + } +} +SQLITE_PRIVATE void sqlite3ShowBitvec(Bitvec *p){ + showBitvec(p, 0, 0); +} +#endif + #ifndef SQLITE_UNTESTABLE /* ** Let V[] be an array of unsigned characters sufficient to hold @@ -54185,9 +55909,10 @@ SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){ ** individual bits within V. */ #define SETBIT(V,I) V[I>>3] |= (1<<(I&7)) -#define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7)) +#define CLEARBIT(V,I) V[I>>3] &= ~(BITVEC_TELEM)(1<<(I&7)) #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0 + /* ** This routine runs an extensive test of the Bitvec code. ** @@ -54196,7 +55921,7 @@ SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){ ** by 0, 1, or 3 operands, depending on the opcode. Another ** opcode follows immediately after the last operand. ** -** There are 6 opcodes numbered from 0 through 5. 0 is the +** There are opcodes numbered starting with 0. 0 is the ** "halt" opcode and causes the test to end. ** ** 0 Halt and return the number of errors @@ -54205,18 +55930,25 @@ SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){ ** 3 N Set N randomly chosen bits ** 4 N Clear N randomly chosen bits ** 5 N S X Set N bits from S increment X in array only, not in bitvec +** 6 Invoice sqlite3ShowBitvec() on the Bitvec object so far +** 7 X Show compile-time parameters and the hash of X ** ** The opcodes 1 through 4 perform set and clear operations are performed ** on both a Bitvec object and on a linear array of bits obtained from malloc. ** Opcode 5 works on the linear array only, not on the Bitvec. ** Opcode 5 is used to deliberately induce a fault in order to -** confirm that error detection works. +** confirm that error detection works. Opcodes 6 and greater are +** state output opcodes. Opcodes 6 and greater are no-ops unless +** SQLite has been compiled with SQLITE_DEBUG. ** ** At the conclusion of the test the linear array is compared ** against the Bitvec object. If there are any differences, ** an error is returned. If they are the same, zero is returned. ** ** If a memory allocation error occurs, return -1. +** +** sz is the size of the Bitvec. Or if sz is negative, make the size +** 2*(unsigned)(-sz) and disabled the linear vector check. */ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ Bitvec *pBitvec = 0; @@ -54227,10 +55959,15 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ /* Allocate the Bitvec to be tested and a linear array of ** bits to act as the reference */ - pBitvec = sqlite3BitvecCreate( sz ); - pV = sqlite3MallocZero( (sz+7)/8 + 1 ); + if( sz<=0 ){ + pBitvec = sqlite3BitvecCreate( 2*(unsigned)(-sz) ); + pV = 0; + }else{ + pBitvec = sqlite3BitvecCreate( sz ); + pV = sqlite3MallocZero( (7+(i64)sz)/8 + 1 ); + } pTmpSpace = sqlite3_malloc64(BITVEC_SZ); - if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end; + if( pBitvec==0 || pTmpSpace==0 || (pV==0 && sz>0) ) goto bitvec_end; /* NULL pBitvec tests */ sqlite3BitvecSet(0, 1); @@ -54239,6 +55976,24 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ /* Run the program */ pc = i = 0; while( (op = aOp[pc])!=0 ){ + if( op>=6 ){ +#ifdef SQLITE_DEBUG + if( op==6 ){ + sqlite3ShowBitvec(pBitvec); + }else if( op==7 ){ + printf("BITVEC_SZ = %d (%d by sizeof)\n", + BITVEC_SZ, (int)sizeof(Bitvec)); + printf("BITVEC_USIZE = %d\n", (int)BITVEC_USIZE); + printf("BITVEC_NELEM = %d\n", (int)BITVEC_NELEM); + printf("BITVEC_NBIT = %d\n", (int)BITVEC_NBIT); + printf("BITVEC_NINT = %d\n", (int)BITVEC_NINT); + printf("BITVEC_MXHASH = %d\n", (int)BITVEC_MXHASH); + printf("BITVEC_NPTR = %d\n", (int)BITVEC_NPTR); + } +#endif + pc++; + continue; + } switch( op ){ case 1: case 2: @@ -54260,12 +56015,12 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ pc += nx; i = (i & 0x7fffffff)%sz; if( (op & 1)!=0 ){ - SETBIT(pV, (i+1)); + if( pV ) SETBIT(pV, (i+1)); if( op!=5 ){ if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end; } }else{ - CLEARBIT(pV, (i+1)); + if( pV ) CLEARBIT(pV, (i+1)); sqlite3BitvecClear(pBitvec, i+1, pTmpSpace); } } @@ -54275,14 +56030,18 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){ ** match (rc==0). Change rc to non-zero if a discrepancy ** is found. */ - rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1) - + sqlite3BitvecTest(pBitvec, 0) - + (sqlite3BitvecSize(pBitvec) - sz); - for(i=1; i<=sz; i++){ - if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){ - rc = i; - break; + if( pV ){ + rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1) + + sqlite3BitvecTest(pBitvec, 0) + + (sqlite3BitvecSize(pBitvec) - sz); + for(i=1; i<=sz; i++){ + if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){ + rc = i; + break; + } } + }else{ + rc = 0; } /* Free allocated structure */ @@ -55469,10 +57228,6 @@ static SQLITE_WSD struct PCacheGlobal { sqlite3_mutex *mutex; /* Mutex for accessing the following: */ PgFreeslot *pFree; /* Free page blocks */ int nFreeSlot; /* Number of unused pcache slots */ - /* The following value requires a mutex to change. We skip the mutex on - ** reading because (1) most platforms read a 32-bit integer atomically and - ** (2) even if an incorrect value is read, no great harm is done since this - ** is really just an optimization. */ int bUnderPressure; /* True if low on PAGECACHE memory */ } pcache1_g; @@ -55520,7 +57275,7 @@ SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){ pcache1.nReserve = n>90 ? 10 : (n/10 + 1); pcache1.pStart = pBuf; pcache1.pFree = 0; - pcache1.bUnderPressure = 0; + AtomicStore(&pcache1.bUnderPressure,0); while( n-- ){ p = (PgFreeslot*)pBuf; p->pNext = pcache1.pFree; @@ -55550,22 +57305,24 @@ static int pcache1InitBulk(PCache1 *pCache){ if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){ szBulk = pCache->szAlloc*(i64)pCache->nMax; } - zBulk = pCache->pBulk = sqlite3Malloc( szBulk ); - sqlite3EndBenignMalloc(); - if( zBulk ){ - int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc; - do{ - PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage]; - pX->page.pBuf = zBulk; - pX->page.pExtra = (u8*)pX + ROUND8(sizeof(*pX)); - assert( EIGHT_BYTE_ALIGNMENT( pX->page.pExtra ) ); - pX->isBulkLocal = 1; - pX->isAnchor = 0; - pX->pNext = pCache->pFree; - pX->pLruPrev = 0; /* Initializing this saves a valgrind error */ - pCache->pFree = pX; - zBulk += pCache->szAlloc; - }while( --nBulk ); + if( szBulk>=pCache->szAlloc ){ + zBulk = pCache->pBulk = sqlite3Malloc( szBulk ); + sqlite3EndBenignMalloc(); + if( zBulk ){ + int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc; + do{ + PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage]; + pX->page.pBuf = zBulk; + pX->page.pExtra = (u8*)pX + ROUND8(sizeof(*pX)); + assert( EIGHT_BYTE_ALIGNMENT( pX->page.pExtra ) ); + pX->isBulkLocal = 1; + pX->isAnchor = 0; + pX->pNext = pCache->pFree; + pX->pLruPrev = 0; /* Initializing this saves a valgrind error */ + pCache->pFree = pX; + zBulk += pCache->szAlloc; + }while( --nBulk ); + } } return pCache->pFree!=0; } @@ -55588,7 +57345,7 @@ static void *pcache1Alloc(int nByte){ if( p ){ pcache1.pFree = pcache1.pFree->pNext; pcache1.nFreeSlot--; - pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve; + AtomicStore(&pcache1.bUnderPressure,pcache1.nFreeSlot<pcache1.nReserve); assert( pcache1.nFreeSlot>=0 ); sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte); sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1); @@ -55627,7 +57384,7 @@ static void pcache1Free(void *p){ pSlot->pNext = pcache1.pFree; pcache1.pFree = pSlot; pcache1.nFreeSlot++; - pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve; + AtomicStore(&pcache1.bUnderPressure,pcache1.nFreeSlot<pcache1.nReserve); assert( pcache1.nFreeSlot<=pcache1.nSlot ); sqlite3_mutex_leave(pcache1.mutex); }else{ @@ -55758,7 +57515,7 @@ SQLITE_PRIVATE void sqlite3PageFree(void *p){ */ static int pcache1UnderMemoryPressure(PCache1 *pCache){ if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){ - return pcache1.bUnderPressure; + return AtomicLoad(&pcache1.bUnderPressure); }else{ return sqlite3HeapNearlyFull(); } @@ -55775,15 +57532,16 @@ static int pcache1UnderMemoryPressure(PCache1 *pCache){ */ static void pcache1ResizeHash(PCache1 *p){ PgHdr1 **apNew; - unsigned int nNew; - unsigned int i; + u64 nNew; + u32 i; assert( sqlite3_mutex_held(p->pGroup->mutex) ); - nNew = p->nHash*2; + nNew = 2*(u64)p->nHash; if( nNew<256 ){ nNew = 256; } + assert( (nNew & (nNew-1))==0 ); /* nNew is always a power of two */ pcache1LeaveMutex(p->pGroup); if( p->nHash ){ sqlite3BeginBenignMalloc(); } @@ -55795,7 +57553,7 @@ static void pcache1ResizeHash(PCache1 *p){ PgHdr1 *pPage; PgHdr1 *pNext = p->apHash[i]; while( (pPage = pNext)!=0 ){ - unsigned int h = pPage->iKey % nNew; + unsigned int h = (unsigned int)(pPage->iKey & (nNew-1)); pNext = pPage->pNext; pPage->pNext = apNew[h]; apNew[h] = pPage; @@ -55845,7 +57603,8 @@ static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){ PgHdr1 **pp; assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); - h = pPage->iKey % pCache->nHash; + assert( pCache->nHash>0 && (pCache->nHash & (pCache->nHash-1))==0 ); + h = pPage->iKey & (pCache->nHash-1); for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext); *pp = (*pp)->pNext; @@ -55890,14 +57649,14 @@ static void pcache1TruncateUnsafe( unsigned int h, iStop; assert( sqlite3_mutex_held(pCache->pGroup->mutex) ); assert( pCache->iMaxKey >= iLimit ); - assert( pCache->nHash > 0 ); + assert( pCache->nHash>0 && (pCache->nHash & (pCache->nHash-1))==0 ); if( pCache->iMaxKey - iLimit < pCache->nHash ){ /* If we are just shaving the last few pages off the end of the ** cache, then there is no point in scanning the entire hash table. ** Only scan those hash slots that might contain pages that need to ** be removed. */ - h = iLimit % pCache->nHash; - iStop = pCache->iMaxKey % pCache->nHash; + h = iLimit & (pCache->nHash-1); + iStop = pCache->iMaxKey & (pCache->nHash-1); TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */ }else{ /* This is the general case where many pages are being removed. @@ -55922,7 +57681,7 @@ static void pcache1TruncateUnsafe( } } if( h==iStop ) break; - h = (h+1) % pCache->nHash; + h = (h+1) & (pCache->nHash-1); } assert( nPage<0 || pCache->nPage==(unsigned)nPage ); } @@ -56003,7 +57762,7 @@ static void pcache1Destroy(sqlite3_pcache *p); static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){ PCache1 *pCache; /* The newly created page cache */ PGroup *pGroup; /* The group the new page cache will belong to */ - int sz; /* Bytes of memory required to allocate the new cache */ + i64 sz; /* Bytes of memory required to allocate the new cache */ assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 ); assert( szExtra < 300 ); @@ -56134,6 +57893,7 @@ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2( if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache); assert( pCache->nHash>0 && pCache->apHash ); + assert( (pCache->nHash & (pCache->nHash-1))==0 ); /* Step 4. Try to recycle a page. */ if( pCache->bPurgeable @@ -56162,7 +57922,7 @@ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2( } if( pPage ){ - unsigned int h = iKey % pCache->nHash; + unsigned int h = iKey & (pCache->nHash-1); pCache->nPage++; pPage->iKey = iKey; pPage->pNext = pCache->apHash[h]; @@ -56246,8 +58006,11 @@ static PgHdr1 *pcache1FetchNoMutex( PCache1 *pCache = (PCache1 *)p; PgHdr1 *pPage = 0; - /* Step 1: Search the hash table for an existing entry. */ - pPage = pCache->apHash[iKey % pCache->nHash]; + /* Step 1: Search the hash table for an existing entry. nHash is always + ** a power of two when the cache is in use (see pcache1ResizeHash()), so + ** the modulo reduces to a mask, avoiding a hardware divide. */ + assert( pCache->nHash>0 && (pCache->nHash & (pCache->nHash-1))==0 ); + pPage = pCache->apHash[iKey & (pCache->nHash-1u)]; while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; } /* Step 2: If the page was found in the hash table, then return it. @@ -56366,7 +58129,8 @@ static void pcache1Rekey( pcache1EnterMutex(pCache->pGroup); assert( pcache1FetchNoMutex(p, iOld, 0)==pPage ); /* pPg really is iOld */ - hOld = iOld%pCache->nHash; + assert( pCache->nHash>0 && (pCache->nHash & (pCache->nHash-1))==0 ); + hOld = iOld & (pCache->nHash-1); pp = &pCache->apHash[hOld]; while( (*pp)!=pPage ){ pp = &(*pp)->pNext; @@ -56374,7 +58138,7 @@ static void pcache1Rekey( *pp = pPage->pNext; assert( pcache1FetchNoMutex(p, iNew, 0)==0 ); /* iNew not in cache */ - hNew = iNew%pCache->nHash; + hNew = iNew & (pCache->nHash-1); pPage->iKey = iNew; pPage->pNext = pCache->apHash[hNew]; pCache->apHash[hNew] = pPage; @@ -57207,6 +58971,10 @@ SQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db); SQLITE_PRIVATE int sqlite3WalSystemErrno(Wal*); #endif +#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_WALSTAT) +SQLITE_PRIVATE void sqlite3WalStat(Wal*,sqlite3_str*); +#endif + #endif /* ifndef SQLITE_OMIT_WAL */ #endif /* SQLITE_WAL_H */ @@ -57891,6 +59659,9 @@ struct Pager { Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */ char *zWal; /* File name for write-ahead log */ #endif +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + sqlite3 *dbWal; +#endif }; /* @@ -57980,39 +59751,35 @@ static const unsigned char aJournalMagic[] = { # define USEFETCH(x) 0 #endif -/* -** The argument to this macro is a file descriptor (type sqlite3_file*). -** Return 0 if it is not open, or non-zero (but not 1) if it is. -** -** This is so that expressions can be written as: -** -** if( isOpen(pPager->jfd) ){ ... -** -** instead of -** -** if( pPager->jfd->pMethods ){ ... -*/ -#define isOpen(pFd) ((pFd)->pMethods!=0) - #ifdef SQLITE_DIRECT_OVERFLOW_READ /* ** Return true if page pgno can be read directly from the database file ** by the b-tree layer. This is the case if: ** -** * the database file is open, -** * there are no dirty pages in the cache, and -** * the desired page is not currently in the wal file. +** (1) the database file is open +** (2) the VFS for the database is able to do unaligned sub-page reads +** (3) there are no dirty pages in the cache, and +** (4) the desired page is not currently in the wal file. */ SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){ - if( pPager->fd->pMethods==0 ) return 0; - if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0; + assert( pPager!=0 ); + assert( pPager->fd!=0 ); + if( pPager->fd->pMethods==0 ) return 0; /* Case (1) */ + if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0; /* Failed (3) */ #ifndef SQLITE_OMIT_WAL if( pPager->pWal ){ u32 iRead = 0; (void)sqlite3WalFindFrame(pPager->pWal, pgno, &iRead); - return iRead==0; + if( iRead ) return 0; /* Case (4) */ } +#else + UNUSED_PARAMETER(pgno); #endif + assert( pPager->fd->pMethods->xDeviceCharacteristics!=0 ); + if( (pPager->fd->pMethods->xDeviceCharacteristics(pPager->fd) + & SQLITE_IOCAP_SUBPAGE_READ)==0 ){ + return 0; /* Case (2) */ + } return 1; } #endif @@ -58427,17 +60194,17 @@ static int jrnlBufferSize(Pager *pPager){ */ #ifdef SQLITE_CHECK_PAGES /* -** Return a 32-bit hash of the page data for pPage. +** Return a 64-bit hash of the page data for pPage. */ -static u32 pager_datahash(int nByte, unsigned char *pData){ - u32 hash = 0; +static u64 pager_datahash(int nByte, unsigned char *pData){ + u64 hash = 0; int i; for(i=0; i<nByte; i++){ hash = (hash*1039) + pData[i]; } return hash; } -static u32 pager_pagehash(PgHdr *pPage){ +static u64 pager_pagehash(PgHdr *pPage){ return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData); } static void pager_set_pagehash(PgHdr *pPage){ @@ -58464,39 +60231,78 @@ static void checkPage(PgHdr *pPg){ #endif /* SQLITE_CHECK_PAGES */ /* -** When this is called the journal file for pager pPager must be open. -** This function attempts to read a super-journal file name from the -** end of the file and, if successful, copies it into memory supplied -** by the caller. See comments above writeSuperJournal() for the format -** used to store a super-journal file name at the end of a journal file. +** Free a buffer allocated by the readSuperJournal() function. +*/ +static void freeSuperJournal(char *zSuper){ + if( zSuper ){ + sqlite3_free(&zSuper[-4]); + } +} + +/* +** Check if zSuper is a valid super-journal name. There are two valid +** formats: ** -** zSuper must point to a buffer of at least nSuper bytes allocated by -** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is -** enough space to write the super-journal name). If the super-journal -** name in the journal is longer than nSuper bytes (including a -** nul-terminator), then this is handled as if no super-journal name -** were present in the journal. +** + The 3rd and 4th last bytes of the filename are ".9", and the +** following 2 bytes are hex digits. This is a file created in 8.3 +** filenames mode. ** -** If a super-journal file name is present at the end of the journal -** file, then it is copied into the buffer pointed to by zSuper. A -** nul-terminator byte is appended to the buffer following the -** super-journal file name. +** + The 3rd last byte of the filename is "9" and the filename +** contains the string "-mj" starting at the 12th last byte. +** All bytes following the "-mj" are hex digits. ** -** If it is determined that no super-journal file name is present -** zSuper[0] is set to 0 and SQLITE_OK returned. +** If the filename matches either of these patterns, return non-zero. +** Otherwise, return zero. +*/ +static int pagerIsSuperJrnlName(const char *zSuper){ + const int nSuper = sqlite3Strlen30(zSuper); + int ii; + +#ifdef SQLITE_ENABLE_8_3_NAMES + if( nSuper<4 ) return 0; + if( zSuper[nSuper-3]!='9' ) return 0; + if( sqlite3Isxdigit(zSuper[nSuper-2])==0 ) return 0; + if( sqlite3Isxdigit(zSuper[nSuper-1])==0 ) return 0; + if( zSuper[nSuper-4]=='.' ) return 1; +#endif + if( nSuper<12 ) return 0; + if( memcmp(&zSuper[nSuper-12], "-mj", 3) ) return 0; + if( zSuper[nSuper-3]!='9' ) return 0; + for(ii=nSuper-9; ii<nSuper; ii++){ + if( sqlite3Isxdigit(zSuper[ii])==0 ) return 0; + } + return 1; +} + +/* +** Parameter pJrnl is a file-handle open on a journal file. This function +** attempts to read a super-journal file name from the end of the journal +** file. If successful, it sets output parameter (*pzSuper) to point to a +** buffer containing the super-journal name as a nul-terminated string. +** The caller is responsible for freeing the buffer using freeSuperJournal(). ** -** If an error occurs while reading from the journal file, an SQLite -** error code is returned. +** Refer to comments above writeSuperJournal() for the format used to store +** a super-journal file name at the end of a journal file. +** +** Parameter nSuper is passed the maximum allowable size of the super journal +** name in bytes. If the super-journal name in the journal is longer than +** nSuper bytes (including a nul-terminator), then this is handled as if no +** super-journal name were present in the journal. +** +** If there is no super-journal name at the end of pJrnl, (*pzSuper) is +** set to 0 and SQLITE_OK is returned. Or, if an error occurs while reading +** the super-journal name, an SQLite error code is returned and (*pzSuper) +** is set to 0. */ -static int readSuperJournal(sqlite3_file *pJrnl, char *zSuper, u32 nSuper){ +static int readSuperJournal(sqlite3_file *pJrnl, u64 nSuper, char **pzSuper){ int rc; /* Return code */ u32 len; /* Length in bytes of super-journal name */ i64 szJ; /* Total size in bytes of journal file pJrnl */ u32 cksum; /* MJ checksum value read from journal */ - u32 u; /* Unsigned loop counter */ unsigned char aMagic[8]; /* A buffer to hold the magic header */ - zSuper[0] = '\0'; + char *zOut = 0; + *pzSuper = 0; if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ)) || szJ<16 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len)) @@ -58505,28 +60311,37 @@ static int readSuperJournal(sqlite3_file *pJrnl, char *zSuper, u32 nSuper){ || len==0 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum)) || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8)) - || memcmp(aMagic, aJournalMagic, 8) - || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zSuper, len, szJ-16-len)) ){ return rc; } - /* See if the checksum matches the super-journal name */ - for(u=0; u<len; u++){ - cksum -= zSuper[u]; - } - if( cksum ){ - /* If the checksum doesn't add up, then one or more of the disk sectors - ** containing the super-journal filename is corrupted. This means - ** definitely roll back, so just return SQLITE_OK and report a (nul) - ** super-journal filename. - */ - len = 0; + zOut = (char*)sqlite3MallocZero(4 + len + 2); + if( !zOut ){ + rc = memcmp(aMagic,aJournalMagic,8) ? SQLITE_OK : SQLITE_NOMEM_BKPT; + }else{ + zOut = &zOut[4]; + if( SQLITE_OK==(rc = sqlite3OsRead(pJrnl, zOut, len, szJ-16-len)) ){ + u32 u; /* Unsigned loop counter */ + /* See if the checksum matches the super-journal name */ + for(u=0; u<len; u++){ + cksum -= zOut[u]; + } + } + if( rc!=SQLITE_OK /* Couldn't read the name */ + || !pagerIsSuperJrnlName(zOut) /* Name is not valid */ + || cksum /* checksum is incorrect */ + || memcmp(aMagic, aJournalMagic, 8)!=0 /* Bad magic number */ + ){ + /* If any validity checks fail, that means the super-journal filename + ** is corrupted, so rollback. Return SQLITE_K and a NULL super-journal + ** name */ + freeSuperJournal(zOut); + zOut = 0; + } } - zSuper[len] = '\0'; - zSuper[len+1] = '\0'; - return SQLITE_OK; + *pzSuper = zOut; + return rc; } /* @@ -58902,6 +60717,7 @@ static int writeSuperJournal(Pager *pPager, const char *zSuper){ assert( pPager->setSuper==0 ); assert( !pagerUseWal(pPager) ); + assert( zSuper==0 || pagerIsSuperJrnlName(zSuper) ); if( !zSuper || pPager->journalMode==PAGER_JOURNALMODE_MEMORY @@ -59043,6 +60859,15 @@ static void pager_unlock(Pager *pPager){ if( pagerUseWal(pPager) ){ assert( !isOpen(pPager->jfd) ); + if( pPager->eState==PAGER_ERROR ){ + /* If an IO error occurs in wal.c while attempting to wrap the wal file, + ** then the Wal object may be holding a write-lock but no read-lock. + ** This call ensures that the write-lock is dropped as well. We cannot + ** have sqlite3WalEndReadTransaction() drop the write-lock, as it once + ** did, because this would break "BEGIN EXCLUSIVE" handling for + ** SQLITE_ENABLE_SETLK_TIMEOUT builds. */ + (void)sqlite3WalEndWriteTransaction(pPager->pWal); + } sqlite3WalEndReadTransaction(pPager->pWal); pPager->eState = PAGER_OPEN; }else if( !pPager->exclusiveMode ){ @@ -59176,7 +61001,7 @@ static int pagerFlushOnCommit(Pager *pPager, int bCommit){ ** database transaction. ** ** This routine is never called in PAGER_ERROR state. If it is called -** in PAGER_NONE or PAGER_SHARED state and the lock held is less +** in PAGER_OPEN or PAGER_READER state and the lock held is less ** exclusive than a RESERVED lock, it is a no-op. ** ** Otherwise, any active savepoints are released. @@ -59271,7 +61096,7 @@ static int pager_end_transaction(Pager *pPager, int hasSuper, int bCommit){ } pPager->journalOff = 0; }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST - || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL) + || (pPager->exclusiveMode && pPager->journalMode<PAGER_JOURNALMODE_WAL) ){ rc = zeroJournalHdr(pPager, hasSuper||pPager->tempFile); pPager->journalOff = 0; @@ -59722,14 +61547,25 @@ static int pager_delsuper(Pager *pPager, const char *zSuper){ char *zSuperJournal = 0; /* Contents of super-journal file */ i64 nSuperJournal; /* Size of super-journal file */ char *zJournal; /* Pointer to one journal within MJ file */ - char *zSuperPtr; /* Space to hold super-journal filename */ char *zFree = 0; /* Free this buffer */ - int nSuperPtr; /* Amount of space allocated to zSuperPtr[] */ + int bSeen = 0; /* If super-journal contains pPager->zJournal */ + + /* Check if this looks like a real super-journal name. If it does not, + ** return SQLITE_OK without attempting to delete it. This is to limit + ** the degree to which a crafted journal file can be used to cause + ** SQLite to delete arbitrary files. + ** + ** This test never fails, becaue the super journal name is checked + ** by readSuperJournal(). + */ + if( NEVER(pagerIsSuperJrnlName(zSuper)==0) ){ + return SQLITE_OK; + } /* Allocate space for both the pJournal and pSuper file descriptors. ** If successful, open the super-journal file for reading. */ - pSuper = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2); + pSuper = (sqlite3_file *)sqlite3MallocZero(2 * (i64)pVfs->szOsFile); if( !pSuper ){ rc = SQLITE_NOMEM_BKPT; pJournal = 0; @@ -59747,15 +61583,16 @@ static int pager_delsuper(Pager *pPager, const char *zSuper){ */ rc = sqlite3OsFileSize(pSuper, &nSuperJournal); if( rc!=SQLITE_OK ) goto delsuper_out; - nSuperPtr = pVfs->mxPathname+1; - zFree = sqlite3Malloc(4 + nSuperJournal + nSuperPtr + 2); + assert( nSuperJournal>=0 ); + zFree = sqlite3Malloc(4 + nSuperJournal + 2); if( !zFree ){ rc = SQLITE_NOMEM_BKPT; goto delsuper_out; + }else{ + assert( nSuperJournal<=0x7fffffff ); } zFree[0] = zFree[1] = zFree[2] = zFree[3] = 0; zSuperJournal = &zFree[4]; - zSuperPtr = &zSuperJournal[nSuperJournal+2]; rc = sqlite3OsRead(pSuper, zSuperJournal, (int)nSuperJournal, 0); if( rc!=SQLITE_OK ) goto delsuper_out; zSuperJournal[nSuperJournal] = 0; @@ -59763,43 +61600,56 @@ static int pager_delsuper(Pager *pPager, const char *zSuper){ zJournal = zSuperJournal; while( (zJournal-zSuperJournal)<nSuperJournal ){ - int exists; - rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists); - if( rc!=SQLITE_OK ){ - goto delsuper_out; - } - if( exists ){ - /* One of the journals pointed to by the super-journal exists. - ** Open it and check if it points at the super-journal. If - ** so, return without deleting the super-journal file. - ** NB: zJournal is really a MAIN_JOURNAL. But call it a - ** SUPER_JOURNAL here so that the VFS will not send the zJournal - ** name into sqlite3_database_file_object(). - */ - int c; - int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL); - rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0); + if( strcmp(zJournal, pPager->zJournal)==0 ){ + bSeen = 1; + }else{ + int exists; + rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists); if( rc!=SQLITE_OK ){ goto delsuper_out; } + if( exists ){ + char *zSuperPtr = 0; - rc = readSuperJournal(pJournal, zSuperPtr, nSuperPtr); - sqlite3OsClose(pJournal); - if( rc!=SQLITE_OK ){ - goto delsuper_out; - } + /* One of the journals pointed to by the super-journal exists. + ** Open it and check if it points at the super-journal. If + ** so, return without deleting the super-journal file. + ** NB: zJournal is really a MAIN_JOURNAL. But call it a + ** SUPER_JOURNAL here so that the VFS will not send the zJournal + ** name into sqlite3_database_file_object(). + */ + int c; + int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL); + rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0); + if( rc!=SQLITE_OK ){ + goto delsuper_out; + } - c = zSuperPtr[0]!=0 && strcmp(zSuperPtr, zSuper)==0; - if( c ){ - /* We have a match. Do not delete the super-journal file. */ - goto delsuper_out; + rc = readSuperJournal(pJournal, 1+(u64)pVfs->mxPathname, &zSuperPtr); + sqlite3OsClose(pJournal); + if( rc!=SQLITE_OK ){ + assert( zSuperPtr==0 ); + goto delsuper_out; + } + + c = zSuperPtr!=0 && strcmp(zSuperPtr, zSuper)==0; + freeSuperJournal(zSuperPtr); + if( c ){ + /* We have a match. Do not delete the super-journal file. */ + goto delsuper_out; + } } } zJournal += (sqlite3Strlen30(zJournal)+1); } sqlite3OsClose(pSuper); - rc = sqlite3OsDelete(pVfs, zSuper, 0); + if( bSeen ){ + /* Only delete the super-journal if bSeen is true - indicating that + ** the super-journal contained a pointer to this database's journal + ** file. */ + rc = sqlite3OsDelete(pVfs, zSuper, 0); + } delsuper_out: sqlite3_free(zFree); @@ -60004,19 +61854,11 @@ static int pager_playback(Pager *pPager, int isHot){ ** If a super-journal file name is specified, but the file is not ** present on disk, then the journal is not hot and does not need to be ** played back. - ** - ** TODO: Technically the following is an error because it assumes that - ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that - ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c, - ** mxPathname is 512, which is the same as the minimum allowable value - ** for pageSize. - */ - zSuper = pPager->pTmpSpace; - rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1); - if( rc==SQLITE_OK && zSuper[0] ){ + */ + rc = readSuperJournal(pPager->jfd, 1+(i64)pPager->pVfs->mxPathname, &zSuper); + if( rc==SQLITE_OK && zSuper ){ rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res); } - zSuper = 0; if( rc!=SQLITE_OK || !res ){ goto end_playback; } @@ -60145,30 +61987,20 @@ static int pager_playback(Pager *pPager, int isHot){ */ pPager->changeCountDone = pPager->tempFile; - if( rc==SQLITE_OK ){ - /* Leave 4 bytes of space before the super-journal filename in memory. - ** This is because it may end up being passed to sqlite3OsOpen(), in - ** which case it requires 4 0x00 bytes in memory immediately before - ** the filename. */ - zSuper = &pPager->pTmpSpace[4]; - rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1); - testcase( rc!=SQLITE_OK ); - } if( rc==SQLITE_OK && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) ){ rc = sqlite3PagerSync(pPager, 0); } if( rc==SQLITE_OK ){ - rc = pager_end_transaction(pPager, zSuper[0]!='\0', 0); + rc = pager_end_transaction(pPager, zSuper!=0, 0); testcase( rc!=SQLITE_OK ); } - if( rc==SQLITE_OK && zSuper[0] && res ){ + if( rc==SQLITE_OK && zSuper && res ){ /* If there was a super-journal and this routine will return success, ** see if it is possible to delete the super-journal. */ - assert( zSuper==&pPager->pTmpSpace[4] ); - memset(pPager->pTmpSpace, 0, 4); + assert( memcmp(&zSuper[-4], "\0\0\0\0", 4)==0 ); rc = pager_delsuper(pPager, zSuper); testcase( rc!=SQLITE_OK ); } @@ -60181,6 +62013,7 @@ static int pager_playback(Pager *pPager, int isHot){ ** back a journal created by a process with a different sector size ** value. Reset it to the correct value for this process. */ + freeSuperJournal(zSuper); setSectorSize(pPager); return rc; } @@ -60794,14 +62627,27 @@ SQLITE_PRIVATE void sqlite3PagerSetFlags( unsigned pgFlags /* Various flags */ ){ unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK; - if( pPager->tempFile ){ + if( pPager->tempFile || level==PAGER_SYNCHRONOUS_OFF ){ pPager->noSync = 1; pPager->fullSync = 0; pPager->extraSync = 0; }else{ - pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0; + pPager->noSync = 0; pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0; - pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0; + + /* Set Pager.extraSync if "PRAGMA synchronous=EXTRA" is requested, or + ** if the file-system supports F2FS style atomic writes. If this flag + ** is set, SQLite syncs the directory to disk immediately after deleting + ** a journal file in "PRAGMA journal_mode=DELETE" mode. */ + if( level==PAGER_SYNCHRONOUS_EXTRA +#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE + || (sqlite3OsDeviceCharacteristics(pPager->fd) & SQLITE_IOCAP_BATCH_ATOMIC) +#endif + ){ + pPager->extraSync = 1; + }else{ + pPager->extraSync = 0; + } } if( pPager->noSync ){ pPager->syncFlags = 0; @@ -60921,7 +62767,7 @@ SQLITE_PRIVATE void sqlite3PagerSetBusyHandler( ** ** then the pager object page size is set to *pPageSize. ** -** If the page size is changed, then this function uses sqlite3PagerMalloc() +** If the page size is changed, then this function uses sqlite3PageMalloc() ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. ** In all other cases, SQLITE_OK is returned. @@ -61361,6 +63207,8 @@ SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){ sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a); pPager->pWal = 0; } +#else + UNUSED_PARAMETER(db); #endif pager_reset(pPager); if( MEMDB ){ @@ -61922,6 +63770,7 @@ SQLITE_PRIVATE int sqlite3PagerOpen( const char *zUri = 0; /* URI args to copy */ int nUriByte = 1; /* Number of bytes of URI args at *zUri */ + /* Figure out how much space is required for each journal file-handle ** (there are two of them, the main journal and the sub-journal). */ journalFileSize = ROUND8(sqlite3JournalSize(pVfs)); @@ -61947,8 +63796,8 @@ SQLITE_PRIVATE int sqlite3PagerOpen( */ if( zFilename && zFilename[0] ){ const char *z; - nPathname = pVfs->mxPathname+1; - zPathname = sqlite3DbMallocRaw(0, nPathname*2); + nPathname = pVfs->mxPathname + 1; + zPathname = sqlite3DbMallocRaw(0, 2*(i64)nPathname); if( zPathname==0 ){ return SQLITE_NOMEM_BKPT; } @@ -62035,14 +63884,14 @@ SQLITE_PRIVATE int sqlite3PagerOpen( ROUND8(sizeof(*pPager)) + /* Pager structure */ ROUND8(pcacheSize) + /* PCache object */ ROUND8(pVfs->szOsFile) + /* The main db file */ - journalFileSize * 2 + /* The two journal files */ + (u64)journalFileSize * 2 + /* The two journal files */ SQLITE_PTRSIZE + /* Space to hold a pointer */ 4 + /* Database prefix */ - nPathname + 1 + /* database filename */ - nUriByte + /* query parameters */ - nPathname + 8 + 1 + /* Journal filename */ + (u64)nPathname + 1 + /* database filename */ + (u64)nUriByte + /* query parameters */ + (u64)nPathname + 8 + 1 + /* Journal filename */ #ifndef SQLITE_OMIT_WAL - nPathname + 4 + 1 + /* WAL filename */ + (u64)nPathname + 4 + 1 + /* WAL filename */ #endif 3 /* Terminator */ ); @@ -62109,7 +63958,15 @@ SQLITE_PRIVATE int sqlite3PagerOpen( */ if( zFilename && zFilename[0] ){ int fout = 0; /* VFS flags returned by xOpen() */ + int bImmutable = sqlite3_uri_boolean(pPager->zFilename, "immutable", 0); + if( bImmutable ){ + vfsFlags |= SQLITE_OPEN_READONLY; + vfsFlags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); + } rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout); + if( bImmutable ){ + goto act_like_temp_file; + } assert( !memDb ); pPager->memVfs = memJM = (fout&SQLITE_OPEN_MEMORY)!=0; readOnly = (fout&SQLITE_OPEN_READONLY)!=0; @@ -62149,10 +64006,9 @@ SQLITE_PRIVATE int sqlite3PagerOpen( #endif } pPager->noLock = sqlite3_uri_boolean(pPager->zFilename, "nolock", 0); - if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0 - || sqlite3_uri_boolean(pPager->zFilename, "immutable", 0) ){ - vfsFlags |= SQLITE_OPEN_READONLY; - goto act_like_temp_file; + if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0 ){ + vfsFlags |= SQLITE_OPEN_READONLY; + goto act_like_temp_file; } } }else{ @@ -62172,6 +64028,7 @@ SQLITE_PRIVATE int sqlite3PagerOpen( pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */ pPager->noLock = 1; /* Do no locking */ readOnly = (vfsFlags&SQLITE_OPEN_READONLY); + assert( readOnly==0 || readOnly==1 ); } /* The following call to PagerSetPagesize() serves to set the value of @@ -62265,8 +64122,8 @@ SQLITE_API sqlite3_file *sqlite3_database_file_object(const char *zName){ /* -** This function is called after transitioning from PAGER_UNLOCK to -** PAGER_SHARED state. It tests if there is a hot journal present in +** This function is called while transitioning from PAGER_OPEN to a +** higher state. It tests if there is a hot journal present in ** the file-system for the given pager. A hot journal is one that ** needs to be played back. According to this function, a hot-journal ** file exists if the following criteria are met: @@ -63992,6 +65849,20 @@ SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){ } #endif +#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_WALSTAT) +/* +** Append JSON structure elements describing the current state of +** the write-ahead log to pStr. +*/ +SQLITE_PRIVATE void sqlite3PagerWalStat(Pager *pPager, sqlite3_str *pStr){ +#ifndef SQLITE_OMIT_WAL + if( pPager->pWal ){ + sqlite3WalStat(pPager->pWal, pStr); + } +#endif +} +#endif + /* ** Return the approximate number of bytes of memory currently ** used by the pager and its associated cache. @@ -64693,7 +66564,7 @@ SQLITE_PRIVATE int sqlite3PagerCheckpoint( } if( pPager->pWal ){ rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode, - (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler), + (eMode<=SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler), pPager->pBusyHandlerArg, pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace, pnLog, pnCkpt @@ -64765,6 +66636,11 @@ static int pagerOpenWal(Pager *pPager){ pPager->fd, pPager->zWal, pPager->exclusiveMode, pPager->journalSizeLimit, &pPager->pWal ); +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + if( rc==SQLITE_OK ){ + sqlite3WalDb(pPager->pWal, pPager->dbWal); + } +#endif } pagerFixMaplimit(pPager); @@ -64884,6 +66760,7 @@ SQLITE_PRIVATE int sqlite3PagerWalWriteLock(Pager *pPager, int bLock){ ** blocking locks are required. */ SQLITE_PRIVATE void sqlite3PagerWalDb(Pager *pPager, sqlite3 *db){ + pPager->dbWal = db; if( pagerUseWal(pPager) ){ sqlite3WalDb(pPager->pWal, db); } @@ -65497,6 +67374,11 @@ struct WalCkptInfo { /* ** An open write-ahead log file is represented by an instance of the ** following object. +** +** writeLock: +** This is usually set to 1 whenever the WRITER lock is held. However, +** if it is set to 2, then the WRITER lock is held but must be released +** by walHandleException() if a SEH exception is thrown. */ struct Wal { sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */ @@ -65577,19 +67459,55 @@ typedef u16 ht_slot; ** walIteratorFree() - Free an iterator. ** ** This functionality is used by the checkpoint code (see walCheckpoint()). +** +** There are two possible algorithms: +** +** WALITER-1 Load all pages mentioned in the WAL file and sort them, +** then hand them back out in sorted order as requested by +** walIteratorNext(). nPagemap==0 for this algorithm. +** +** WALITER-2 Create a map of all database file pages and record the +** last WAL file frame that updates that page. Then walk +** through the map in acsending order and return all +** non-zero entries. nPagemap is positive for this algorithm. +** +** Either algorithm should work for any database and WAL file, however +** algorithm WALITER-1 is faster and uses less memory when the database is +** larger than the WAL file and algorithm WALITER-2 is faster and uses +** less memory when the WAL file is larger than the database, modulo a +** constant of proportionality. The walIteratorInit() routine selects +** the best algorithm for each situation. WALITER-2 was added for +** SQLite 3.54.0. Prior to that, WALITER-1 was used always. +** +** For algorithm WALITER-2, nPagemap stores the number of pages in the +** database file, nSegment==1, and aSegment[0].aPgno[] is the page map array +** that is nPagemap+1 entries in length. The value of aSegment[0].aPgno[PGNO] +** is the frame number of the last (newest) entry for page PGNO in the WAL +** file, or 0 if PGNO is not in the WAL file. (Aside: There is no page +** number 0 in a well-formed database, so the memory allocation is arranged +** such that aSegment[0].aPgno[0] and aSegment[0].iZero are aliases for the +** same four bits of memory. This saves us from having to use -1 and +1 +** offsets to translate between 1-based SQLite page numbers and 0-based +** C-language index numbers. tag-20260903-1) */ struct WalIterator { u32 iPrior; /* Last result returned from the iterator */ int nSegment; /* Number of entries in aSegment[] */ + u32 nPagemap; /* Non-zero in "page-map" mode */ struct WalSegment { int iNext; /* Next slot in aIndex[] not yet returned */ ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */ u32 *aPgno; /* Array of page numbers. */ int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */ int iZero; /* Frame number associated with aPgno[0] */ - } aSegment[1]; /* One for every 32KB page in the wal-index */ + } aSegment[FLEXARRAY]; /* One for every 32KB page in the wal-index */ }; +/* Size (in bytes) of a WalIterator object suitable for N or fewer segments */ +#define SZ_WALITERATOR(N) \ + (offsetof(WalIterator,aSegment)+(N)*sizeof(struct WalSegment)) + + /* ** Define the parameters of the hash tables in the wal-index file. There ** is a hash-table following every HASHTABLE_NPAGE page numbers in the @@ -65748,7 +67666,7 @@ static SQLITE_NOINLINE int walIndexPageRealloc( /* Enlarge the pWal->apWiData[] array if required */ if( pWal->nWiData<=iPage ){ - sqlite3_int64 nByte = sizeof(u32*)*(iPage+1); + sqlite3_int64 nByte = sizeof(u32*)*(1+(i64)iPage); volatile u32 **apNew; apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte); if( !apNew ){ @@ -65857,10 +67775,8 @@ static void walChecksumBytes( s1 = s2 = 0; } - assert( nByte>=8 ); - assert( (nByte&0x00000007)==0 ); - assert( nByte<=65536 ); - assert( nByte%4==0 ); + /* nByte is a multiple of 8 between 8 and 65536 */ + assert( nByte>=8 && (nByte&7)==0 && nByte<=65536 ); if( !nativeCksum ){ do { @@ -66011,6 +67927,12 @@ static int walDecodeFrame( return 0; } + /* Need a valid page size + */ + if( !pWal->szPage ){ + return 0; + } + /* A frame is only valid if a checksum of the WAL header, ** all prior frames, the first 16 bytes of this frame-header, ** and the frame-data matches the checksum in the last 8 @@ -66114,7 +68036,7 @@ static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){ /* ** Compute a hash on a page number. The resulting hash value must land -** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances +** between 0 and (HASHTABLE_NSLOT-1). The walNextHash() function advances ** the hash to the next value in the event of a collision. */ static int walHash(u32 iPage){ @@ -66322,7 +68244,7 @@ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){ for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){ if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT; } - sLoc.aPgno[idx-1] = iPage; + sLoc.aPgno[(idx-1)&(HASHTABLE_NPAGE-1)] = iPage; AtomicStore(&sLoc.aHash[iKey], (ht_slot)idx); #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT @@ -66748,24 +68670,38 @@ static int walIteratorNext( u32 *piPage, /* OUT: The page number of the next page */ u32 *piFrame /* OUT: Wal frame index of next page */ ){ - u32 iMin; /* Result pgno must be greater than iMin */ u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */ - int i; /* For looping through segments */ - iMin = p->iPrior; - assert( iMin<0xffffffff ); - for(i=p->nSegment-1; i>=0; i--){ - struct WalSegment *pSegment = &p->aSegment[i]; - while( pSegment->iNext<pSegment->nEntry ){ - u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]]; - if( iPg>iMin ){ - if( iPg<iRet ){ - iRet = iPg; - *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext]; - } + if( p->nPagemap ){ + /* Algorithm WALITER-2 */ + while( p->iPrior<p->nPagemap ){ + p->iPrior++; + if( p->aSegment[0].aPgno[p->iPrior] ){ + iRet = p->iPrior; + *piFrame = p->aSegment[0].aPgno[p->iPrior]; break; } - pSegment->iNext++; + } + }else{ + /* Algorithm WALITER-1 */ + u32 iMin; /* Result pgno must be greater than iMin */ + int i; /* For looping through segments */ + + iMin = p->iPrior; + assert( iMin<0xffffffff ); + for(i=p->nSegment-1; i>=0; i--){ + struct WalSegment *pSegment = &p->aSegment[i]; + while( pSegment->iNext<pSegment->nEntry ){ + u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]]; + if( iPg>iMin ){ + if( iPg<iRet ){ + iRet = iPg; + *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext]; + } + break; + } + pSegment->iNext++; + } } } @@ -66934,36 +68870,59 @@ static void walIteratorFree(WalIterator *p){ ** WalIterator object when it has finished with it. */ static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){ + int iFirstPage; /* First 32KB *-shm page to visit */ + int iLastPage; /* Last 32KB *-shm page to visit */ + u32 iZero; /* Frame before first frame to visit */ WalIterator *p; /* Return value */ int nSegment; /* Number of segments to merge */ u32 iLast; /* Last frame in log */ sqlite3_int64 nByte; /* Number of bytes to allocate */ + sqlite3_int64 nExtra; /* Number of bytes to allocate */ int i; /* Iterator variable */ - ht_slot *aTmp; /* Temp space used by merge-sort */ + ht_slot *aTmp = 0; /* Temp space used by merge-sort */ int rc = SQLITE_OK; /* Return Code */ + int eAlg; /* Which algorithm to use. 1 or 2 */ /* This routine only runs while holding the checkpoint lock. And - ** it only runs if there is actually content in the log (mxFrame>0). - */ + ** it only runs if there is actually content in the log (mxFrame>0). */ assert( pWal->ckptLock && pWal->hdr.mxFrame>0 ); + iLast = pWal->hdr.mxFrame; + iFirstPage = walFramePage(nBackfill+1); + iLastPage = walFramePage(iLast); + iZero = iFirstPage ? (HASHTABLE_NPAGE_ONE+(iFirstPage-1)*HASHTABLE_NPAGE) : 0; + + if( (iLast-iZero)*sizeof(ht_slot)>pWal->hdr.nPage*sizeof(u32) ){ + /* Algorithm WALITER-2 */ + nSegment = 1; + eAlg = 2; + nByte = SZ_WALITERATOR(nSegment) + pWal->hdr.nPage * sizeof(u32); + nExtra = 0; + }else{ + /* Algorithm WALITER-1 */ + nSegment = iLastPage - iFirstPage + 1; + eAlg = 1; + nByte = SZ_WALITERATOR(nSegment) + (iLast-iZero)*sizeof(ht_slot); + nExtra = sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast); + } /* Allocate space for the WalIterator object. */ - nSegment = walFramePage(iLast) + 1; - nByte = sizeof(WalIterator) - + (nSegment-1)*sizeof(struct WalSegment) - + iLast*sizeof(ht_slot); - p = (WalIterator *)sqlite3_malloc64(nByte - + sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast) - ); + p = (WalIterator *)sqlite3_malloc64(nByte + nExtra); if( !p ){ return SQLITE_NOMEM_BKPT; } memset(p, 0, nByte); p->nSegment = nSegment; - aTmp = (ht_slot*)&(((u8*)p)[nByte]); + if( eAlg==2 ){ + p->nPagemap = pWal->hdr.nPage; + p->aSegment[0].aPgno = ((u32*)&p->aSegment[1]) - 1; + assert( (u8*)&(p->aSegment[0].aPgno[0]) == (u8*)&(p->aSegment[0].iZero) ); + /* ^-- verifies tag-20260903-1 */ + }else{ + aTmp = (ht_slot*)&(((u8*)p)[nByte]); + } SEH_FREE_ON_ERROR(0, p); - for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){ + for(i=iFirstPage; rc==SQLITE_OK && i<=iLastPage; i++){ WalHashLoc sLoc; rc = walHashGet(pWal, i, &sLoc); @@ -66972,22 +68931,34 @@ static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){ int nEntry; /* Number of entries in this segment */ ht_slot *aIndex; /* Sorted index for this segment */ - if( (i+1)==nSegment ){ + if( i==iLastPage ){ nEntry = (int)(iLast - sLoc.iZero); }else{ nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno); } - aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero]; - sLoc.iZero++; - for(j=0; j<nEntry; j++){ - aIndex[j] = (ht_slot)j; + if( eAlg==2 ){ + u32 *aPagemap = p->aSegment[0].aPgno; + for(j=0; j<nEntry; j++){ + u32 pgno = sLoc.aPgno[ j ]; + if( pgno<=p->nPagemap ){ + aPagemap[pgno] = sLoc.iZero + j + 1; + } + } + }else{ + assert( i!=iFirstPage || iZero==sLoc.iZero ); + aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero - iZero]; + sLoc.iZero++; + + for(j=0; j<nEntry; j++){ + aIndex[j] = (ht_slot)j; + } + walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry); + p->aSegment[i-iFirstPage].iZero = sLoc.iZero; + p->aSegment[i-iFirstPage].nEntry = nEntry; + p->aSegment[i-iFirstPage].aIndex = aIndex; + p->aSegment[i-iFirstPage].aPgno = (u32 *)sLoc.aPgno; } - walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry); - p->aSegment[i].iZero = sLoc.iZero; - p->aSegment[i].nEntry = nEntry; - p->aSegment[i].aIndex = aIndex; - p->aSegment[i].aPgno = (u32 *)sLoc.aPgno; } } if( rc!=SQLITE_OK ){ @@ -67022,7 +68993,7 @@ static int walEnableBlockingMs(Wal *pWal, int nMs){ static int walEnableBlocking(Wal *pWal){ int res = 0; if( pWal->db ){ - int tmout = pWal->db->busyTimeout; + int tmout = pWal->db->setlkTimeout; if( tmout ){ res = walEnableBlockingMs(pWal, tmout); } @@ -67243,68 +69214,82 @@ static int walCheckpoint( && (rc = walBusyLock(pWal,xBusy,pBusyArg,WAL_READ_LOCK(0),1))==SQLITE_OK ){ u32 nBackfill = pInfo->nBackfill; - pInfo->nBackfillAttempted = mxSafeFrame; SEH_INJECT_FAULT; - - /* Sync the WAL to disk */ - rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags)); - - /* If the database may grow as a result of this checkpoint, hint - ** about the eventual size of the db file to the VFS layer. - */ - if( rc==SQLITE_OK ){ - i64 nReq = ((i64)mxPage * szPage); - i64 nSize; /* Current size of database file */ - sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0); - rc = sqlite3OsFileSize(pWal->pDbFd, &nSize); - if( rc==SQLITE_OK && nSize<nReq ){ - if( (nSize+65536+(i64)pWal->hdr.mxFrame*szPage)<nReq ){ - /* If the size of the final database is larger than the current - ** database plus the amount of data in the wal file, plus the - ** maximum size of the pending-byte page (65536 bytes), then - ** must be corruption somewhere. */ - rc = SQLITE_CORRUPT_BKPT; - }else{ - sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT,&nReq); + WalIndexHdr *pLive = (WalIndexHdr*)walIndexHdr(pWal); + + /* Now that read-lock slot 0 is locked, check that the wal has not been + ** wrapped since the header was read for this checkpoint. If it was, then + ** there was no work to do anyway. In this case the + ** (pInfo->nBackfill<pWal->hdr.mxFrame) test above only passed because + ** pInfo->nBackfill had already been set to 0 by the writer that wrapped + ** the wal file. It would also be dangerous to proceed, as there may be + ** fewer than pWal->hdr.mxFrame valid frames in the wal file. */ + int bChg = memcmp(pLive->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt)); + if( 0==bChg ){ + pInfo->nBackfillAttempted = mxSafeFrame; SEH_INJECT_FAULT; + + /* Sync the WAL to disk */ + rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags)); + + /* If the database may grow as a result of this checkpoint, hint + ** about the eventual size of the db file to the VFS layer. + */ + if( rc==SQLITE_OK ){ + i64 nReq = ((i64)mxPage * szPage); + i64 nSize; /* Current size of database file */ + sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0); + rc = sqlite3OsFileSize(pWal->pDbFd, &nSize); + if( rc==SQLITE_OK && nSize<nReq ){ + if( (nSize+65536+(i64)pWal->hdr.mxFrame*szPage)<nReq ){ + /* If the size of the final database is larger than the current + ** database plus the amount of data in the wal file, plus the + ** maximum size of the pending-byte page (65536 bytes), then + ** must be corruption somewhere. */ + rc = SQLITE_CORRUPT_BKPT; + }else{ + sqlite3OsFileControlHint( + pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq); + } } - } - } - - /* Iterate through the contents of the WAL, copying data to the db file */ - while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){ - i64 iOffset; - assert( walFramePgno(pWal, iFrame)==iDbpage ); - SEH_INJECT_FAULT; - if( AtomicLoad(&db->u1.isInterrupted) ){ - rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT; - break; } - if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){ - continue; - } - iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE; - /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */ - rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset); - if( rc!=SQLITE_OK ) break; - iOffset = (iDbpage-1)*(i64)szPage; - testcase( IS_BIG_INT(iOffset) ); - rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset); - if( rc!=SQLITE_OK ) break; - } - sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0); - /* If work was actually accomplished... */ - if( rc==SQLITE_OK ){ - if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){ - i64 szDb = pWal->hdr.nPage*(i64)szPage; - testcase( IS_BIG_INT(szDb) ); - rc = sqlite3OsTruncate(pWal->pDbFd, szDb); - if( rc==SQLITE_OK ){ - rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags)); + /* Iterate through the contents of the WAL, copying data to the + ** db file */ + while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){ + i64 iOffset; + assert( walFramePgno(pWal, iFrame)==iDbpage ); + SEH_INJECT_FAULT; + if( AtomicLoad(&db->u1.isInterrupted) ){ + rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT; + break; } + if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){ + continue; + } + iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE; + /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */ + rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset); + if( rc!=SQLITE_OK ) break; + iOffset = (iDbpage-1)*(i64)szPage; + testcase( IS_BIG_INT(iOffset) ); + rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset); + if( rc!=SQLITE_OK ) break; } + sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0); + + /* If work was actually accomplished... */ if( rc==SQLITE_OK ){ - AtomicStore(&pInfo->nBackfill, mxSafeFrame); SEH_INJECT_FAULT; + if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){ + i64 szDb = pWal->hdr.nPage*(i64)szPage; + testcase( IS_BIG_INT(szDb) ); + rc = sqlite3OsTruncate(pWal->pDbFd, szDb); + if( rc==SQLITE_OK ){ + rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags)); + } + } + if( rc==SQLITE_OK ){ + AtomicStore(&pInfo->nBackfill, mxSafeFrame); SEH_INJECT_FAULT; + } } } @@ -67408,7 +69393,9 @@ static int walHandleException(Wal *pWal){ static const int S = 1; static const int E = (1<<SQLITE_SHM_NLOCK); int ii; - u32 mUnlock = pWal->lockMask & ~( + u32 mUnlock; + if( pWal->writeLock==2 ) pWal->writeLock = 0; + mUnlock = pWal->lockMask & ~( (pWal->readLock<0 ? 0 : (S << WAL_READ_LOCK(pWal->readLock))) | (pWal->writeLock ? (E << WAL_WRITE_LOCK) : 0) | (pWal->ckptLock ? (E << WAL_CKPT_LOCK) : 0) @@ -67680,7 +69667,12 @@ static int walIndexReadHdr(Wal *pWal, int *pChanged){ if( bWriteLock || SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){ - pWal->writeLock = 1; + /* If the write-lock was just obtained, set writeLock to 2 instead of + ** the usual 1. This causes walIndexPage() to behave as if the + ** write-lock were held (so that it allocates new pages as required), + ** and walHandleException() to unlock the write-lock if a SEH exception + ** is thrown. */ + if( !bWriteLock ) pWal->writeLock = 2; if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){ badHdr = walIndexTryHdr(pWal, pChanged); if( badHdr ){ @@ -67845,7 +69837,7 @@ static int walBeginShmUnreliable(Wal *pWal, int *pChanged){ /* Allocate a buffer to read frames into */ assert( (pWal->szPage & (pWal->szPage-1))==0 ); - assert( pWal->szPage>=512 && pWal->szPage<=65536 ); + assert( (pWal->szPage>=512 && pWal->szPage<=65536) || pWal->szPage==0 ); szFrame = pWal->szPage + WAL_FRAME_HDRSIZE; aFrame = (u8 *)sqlite3_malloc64(szFrame); if( aFrame==0 ){ @@ -67981,11 +69973,7 @@ static int walBeginShmUnreliable(Wal *pWal, int *pChanged){ */ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int *pCnt){ volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */ - u32 mxReadMark; /* Largest aReadMark[] value */ - int mxI; /* Index of largest aReadMark[] value */ - int i; /* Loop counter */ int rc = SQLITE_OK; /* Return code */ - u32 mxFrame; /* Wal frame to lock to */ #ifdef SQLITE_ENABLE_SETLK_TIMEOUT int nBlockTmout = 0; #endif @@ -68048,7 +70036,6 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int *pCnt){ rc = walIndexReadHdr(pWal, pChanged); } #ifdef SQLITE_ENABLE_SETLK_TIMEOUT - walDisableBlocking(pWal); if( rc==SQLITE_BUSY_TIMEOUT ){ rc = SQLITE_BUSY; *pCnt |= WAL_RETRY_BLOCKED_MASK; @@ -68063,6 +70050,7 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int *pCnt){ ** WAL_RETRY this routine will be called again and will probably be ** right on the second iteration. */ + (void)walEnableBlocking(pWal); if( pWal->apWiData[0]==0 ){ /* This branch is taken when the xShmMap() method returns SQLITE_BUSY. ** We assume this is a transient condition, so return WAL_RETRY. The @@ -68079,6 +70067,7 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int *pCnt){ rc = SQLITE_BUSY_RECOVERY; } } + walDisableBlocking(pWal); if( rc!=SQLITE_OK ){ return rc; } @@ -68091,141 +70080,147 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int *pCnt){ assert( pWal->apWiData[0]!=0 ); pInfo = walCkptInfo(pWal); SEH_INJECT_FAULT; - if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame + { + u32 mxReadMark; /* Largest aReadMark[] value */ + int mxI; /* Index of largest aReadMark[] value */ + int i; /* Loop counter */ + u32 mxFrame; /* Wal frame to lock to */ + if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame #ifdef SQLITE_ENABLE_SNAPSHOT - && ((pWal->bGetSnapshot==0 && pWal->pSnapshot==0) || pWal->hdr.mxFrame==0) + && ((pWal->bGetSnapshot==0 && pWal->pSnapshot==0) || pWal->hdr.mxFrame==0) #endif - ){ - /* The WAL has been completely backfilled (or it is empty). - ** and can be safely ignored. - */ - rc = walLockShared(pWal, WAL_READ_LOCK(0)); - walShmBarrier(pWal); - if( rc==SQLITE_OK ){ - if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){ - /* It is not safe to allow the reader to continue here if frames - ** may have been appended to the log before READ_LOCK(0) was obtained. - ** When holding READ_LOCK(0), the reader ignores the entire log file, - ** which implies that the database file contains a trustworthy - ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from - ** happening, this is usually correct. - ** - ** However, if frames have been appended to the log (or if the log - ** is wrapped and written for that matter) before the READ_LOCK(0) - ** is obtained, that is not necessarily true. A checkpointer may - ** have started to backfill the appended frames but crashed before - ** it finished. Leaving a corrupt image in the database file. - */ - walUnlockShared(pWal, WAL_READ_LOCK(0)); - return WAL_RETRY; + ){ + /* The WAL has been completely backfilled (or it is empty). + ** and can be safely ignored. + */ + rc = walLockShared(pWal, WAL_READ_LOCK(0)); + walShmBarrier(pWal); + if( rc==SQLITE_OK ){ + if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr,sizeof(WalIndexHdr)) ){ + /* It is not safe to allow the reader to continue here if frames + ** may have been appended to the log before READ_LOCK(0) was obtained. + ** When holding READ_LOCK(0), the reader ignores the entire log file, + ** which implies that the database file contains a trustworthy + ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from + ** happening, this is usually correct. + ** + ** However, if frames have been appended to the log (or if the log + ** is wrapped and written for that matter) before the READ_LOCK(0) + ** is obtained, that is not necessarily true. A checkpointer may + ** have started to backfill the appended frames but crashed before + ** it finished. Leaving a corrupt image in the database file. + */ + walUnlockShared(pWal, WAL_READ_LOCK(0)); + return WAL_RETRY; + } + pWal->readLock = 0; + return SQLITE_OK; + }else if( rc!=SQLITE_BUSY ){ + return rc; } - pWal->readLock = 0; - return SQLITE_OK; - }else if( rc!=SQLITE_BUSY ){ - return rc; } - } - /* If we get this far, it means that the reader will want to use - ** the WAL to get at content from recent commits. The job now is - ** to select one of the aReadMark[] entries that is closest to - ** but not exceeding pWal->hdr.mxFrame and lock that entry. - */ - mxReadMark = 0; - mxI = 0; - mxFrame = pWal->hdr.mxFrame; + /* If we get this far, it means that the reader will want to use + ** the WAL to get at content from recent commits. The job now is + ** to select one of the aReadMark[] entries that is closest to + ** but not exceeding pWal->hdr.mxFrame and lock that entry. + */ + mxReadMark = 0; + mxI = 0; + mxFrame = pWal->hdr.mxFrame; #ifdef SQLITE_ENABLE_SNAPSHOT - if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){ - mxFrame = pWal->pSnapshot->mxFrame; - } -#endif - for(i=1; i<WAL_NREADER; i++){ - u32 thisMark = AtomicLoad(pInfo->aReadMark+i); SEH_INJECT_FAULT; - if( mxReadMark<=thisMark && thisMark<=mxFrame ){ - assert( thisMark!=READMARK_NOT_USED ); - mxReadMark = thisMark; - mxI = i; + if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){ + mxFrame = pWal->pSnapshot->mxFrame; } - } - if( (pWal->readOnly & WAL_SHM_RDONLY)==0 - && (mxReadMark<mxFrame || mxI==0) - ){ +#endif for(i=1; i<WAL_NREADER; i++){ - rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1); - if( rc==SQLITE_OK ){ - AtomicStore(pInfo->aReadMark+i,mxFrame); - mxReadMark = mxFrame; + u32 thisMark = AtomicLoad(pInfo->aReadMark+i); SEH_INJECT_FAULT; + if( mxReadMark<=thisMark && thisMark<=mxFrame ){ + assert( thisMark!=READMARK_NOT_USED ); + mxReadMark = thisMark; mxI = i; - walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); - break; - }else if( rc!=SQLITE_BUSY ){ - return rc; } } - } - if( mxI==0 ){ - assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 ); - return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT; - } + if( (pWal->readOnly & WAL_SHM_RDONLY)==0 + && (mxReadMark<mxFrame || mxI==0) + ){ + for(i=1; i<WAL_NREADER; i++){ + rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1); + if( rc==SQLITE_OK ){ + AtomicStore(pInfo->aReadMark+i,mxFrame); + mxReadMark = mxFrame; + mxI = i; + walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); + break; + }else if( rc!=SQLITE_BUSY ){ + return rc; + } + } + } + if( mxI==0 ){ + assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 ); + return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT; + } - (void)walEnableBlockingMs(pWal, nBlockTmout); - rc = walLockShared(pWal, WAL_READ_LOCK(mxI)); - walDisableBlocking(pWal); - if( rc ){ + (void)walEnableBlockingMs(pWal, nBlockTmout); + rc = walLockShared(pWal, WAL_READ_LOCK(mxI)); + walDisableBlocking(pWal); + if( rc ){ #ifdef SQLITE_ENABLE_SETLK_TIMEOUT - if( rc==SQLITE_BUSY_TIMEOUT ){ - *pCnt |= WAL_RETRY_BLOCKED_MASK; - } + if( rc==SQLITE_BUSY_TIMEOUT ){ + *pCnt |= WAL_RETRY_BLOCKED_MASK; + } #else - assert( rc!=SQLITE_BUSY_TIMEOUT ); + assert( rc!=SQLITE_BUSY_TIMEOUT ); #endif - assert( (rc&0xFF)!=SQLITE_BUSY||rc==SQLITE_BUSY||rc==SQLITE_BUSY_TIMEOUT ); - return (rc&0xFF)==SQLITE_BUSY ? WAL_RETRY : rc; - } - /* Now that the read-lock has been obtained, check that neither the - ** value in the aReadMark[] array or the contents of the wal-index - ** header have changed. - ** - ** It is necessary to check that the wal-index header did not change - ** between the time it was read and when the shared-lock was obtained - ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility - ** that the log file may have been wrapped by a writer, or that frames - ** that occur later in the log than pWal->hdr.mxFrame may have been - ** copied into the database by a checkpointer. If either of these things - ** happened, then reading the database with the current value of - ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry - ** instead. - ** - ** Before checking that the live wal-index header has not changed - ** since it was read, set Wal.minFrame to the first frame in the wal - ** file that has not yet been checkpointed. This client will not need - ** to read any frames earlier than minFrame from the wal file - they - ** can be safely read directly from the database file. - ** - ** Because a ShmBarrier() call is made between taking the copy of - ** nBackfill and checking that the wal-header in shared-memory still - ** matches the one cached in pWal->hdr, it is guaranteed that the - ** checkpointer that set nBackfill was not working with a wal-index - ** header newer than that cached in pWal->hdr. If it were, that could - ** cause a problem. The checkpointer could omit to checkpoint - ** a version of page X that lies before pWal->minFrame (call that version - ** A) on the basis that there is a newer version (version B) of the same - ** page later in the wal file. But if version B happens to like past - ** frame pWal->hdr.mxFrame - then the client would incorrectly assume - ** that it can read version A from the database file. However, since - ** we can guarantee that the checkpointer that set nBackfill could not - ** see any pages past pWal->hdr.mxFrame, this problem does not come up. - */ - pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1; SEH_INJECT_FAULT; - walShmBarrier(pWal); - if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark - || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) - ){ - walUnlockShared(pWal, WAL_READ_LOCK(mxI)); - return WAL_RETRY; - }else{ - assert( mxReadMark<=pWal->hdr.mxFrame ); - pWal->readLock = (i16)mxI; + assert((rc&0xFF)!=SQLITE_BUSY||rc==SQLITE_BUSY||rc==SQLITE_BUSY_TIMEOUT); + return (rc&0xFF)==SQLITE_BUSY ? WAL_RETRY : rc; + } + /* Now that the read-lock has been obtained, check that neither the + ** value in the aReadMark[] array or the contents of the wal-index + ** header have changed. + ** + ** It is necessary to check that the wal-index header did not change + ** between the time it was read and when the shared-lock was obtained + ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility + ** that the log file may have been wrapped by a writer, or that frames + ** that occur later in the log than pWal->hdr.mxFrame may have been + ** copied into the database by a checkpointer. If either of these things + ** happened, then reading the database with the current value of + ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry + ** instead. + ** + ** Before checking that the live wal-index header has not changed + ** since it was read, set Wal.minFrame to the first frame in the wal + ** file that has not yet been checkpointed. This client will not need + ** to read any frames earlier than minFrame from the wal file - they + ** can be safely read directly from the database file. + ** + ** Because a ShmBarrier() call is made between taking the copy of + ** nBackfill and checking that the wal-header in shared-memory still + ** matches the one cached in pWal->hdr, it is guaranteed that the + ** checkpointer that set nBackfill was not working with a wal-index + ** header newer than that cached in pWal->hdr. If it were, that could + ** cause a problem. The checkpointer could omit to checkpoint + ** a version of page X that lies before pWal->minFrame (call that version + ** A) on the basis that there is a newer version (version B) of the same + ** page later in the wal file. But if version B happens to like past + ** frame pWal->hdr.mxFrame - then the client would incorrectly assume + ** that it can read version A from the database file. However, since + ** we can guarantee that the checkpointer that set nBackfill could not + ** see any pages past pWal->hdr.mxFrame, this problem does not come up. + */ + pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1; SEH_INJECT_FAULT; + walShmBarrier(pWal); + if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark + || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) + ){ + walUnlockShared(pWal, WAL_READ_LOCK(mxI)); + return WAL_RETRY; + }else{ + assert( mxReadMark<=pWal->hdr.mxFrame ); + pWal->readLock = (i16)mxI; + } } return rc; } @@ -68463,8 +70458,11 @@ SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){ ** read-lock. */ SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){ - sqlite3WalEndWriteTransaction(pWal); +#ifndef SQLITE_ENABLE_SETLK_TIMEOUT + assert( pWal->writeLock==0 || pWal->readLock<0 ); +#endif if( pWal->readLock>=0 ){ + (void)sqlite3WalEndWriteTransaction(pWal); walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); pWal->readLock = -1; } @@ -68544,7 +70542,10 @@ static int walFindFrame( SEH_INJECT_FAULT; while( (iH = AtomicLoad(&sLoc.aHash[iKey]))!=0 ){ u32 iFrame = iH + sLoc.iZero; - if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH-1]==pgno ){ + if( iFrame<=iLast + && iFrame>=pWal->minFrame + && sLoc.aPgno[(iH-1)&(HASHTABLE_NPAGE-1)]==pgno + ){ assert( iFrame>iRead || CORRUPT_DB ); iRead = iFrame; } @@ -68618,11 +70619,15 @@ SQLITE_PRIVATE int sqlite3WalReadFrame( i64 iOffset; sz = pWal->hdr.szPage; sz = (sz&0xfe00) + ((sz&0x0001)<<16); + if( nOut>sz ){ + memset(pOut+sz, 0, nOut-sz); + nOut = sz; + } testcase( sz<=32768 ); testcase( sz>=65536 ); iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE; /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */ - return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset); + return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset); } /* @@ -68657,7 +70662,7 @@ SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){ ** read-transaction was even opened, making this call a no-op. ** Return early. */ if( pWal->writeLock ){ - assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) ); + assert( !memcmp(&pWal->hdr,(void*)pWal->apWiData[0],sizeof(WalIndexHdr)) ); return SQLITE_OK; } #endif @@ -68757,6 +70762,7 @@ SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *p if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal); } SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; ) + pWal->iReCksum = 0; } return rc; } @@ -68804,6 +70810,9 @@ SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){ walCleanupHash(pWal); } SEH_EXCEPT( rc = SQLITE_IOERR_IN_PAGE; ) + if( pWal->iReCksum>pWal->hdr.mxFrame ){ + pWal->iReCksum = 0; + } } return rc; @@ -69269,7 +71278,8 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint( /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked ** in the SQLITE_CHECKPOINT_PASSIVE mode. */ - assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 ); + assert( SQLITE_CHECKPOINT_NOOP<SQLITE_CHECKPOINT_PASSIVE ); + assert( eMode>SQLITE_CHECKPOINT_PASSIVE || xBusy==0 ); if( pWal->readOnly ) return SQLITE_READONLY; WALTRACE(("WAL%p: checkpoint begins\n", pWal)); @@ -69286,31 +71296,35 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint( ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured, ** it will not be invoked in this case. */ - rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1); - testcase( rc==SQLITE_BUSY ); - testcase( rc!=SQLITE_OK && xBusy2!=0 ); - if( rc==SQLITE_OK ){ - pWal->ckptLock = 1; + if( eMode!=SQLITE_CHECKPOINT_NOOP ){ + rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1); + testcase( rc==SQLITE_BUSY ); + testcase( rc!=SQLITE_OK && xBusy2!=0 ); + if( rc==SQLITE_OK ){ + pWal->ckptLock = 1; - /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and - ** TRUNCATE modes also obtain the exclusive "writer" lock on the database - ** file. - ** - ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained - ** immediately, and a busy-handler is configured, it is invoked and the - ** writer lock retried until either the busy-handler returns 0 or the - ** lock is successfully obtained. - */ - if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){ - rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1); - if( rc==SQLITE_OK ){ - pWal->writeLock = 1; - }else if( rc==SQLITE_BUSY ){ - eMode2 = SQLITE_CHECKPOINT_PASSIVE; - xBusy2 = 0; - rc = SQLITE_OK; + /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART + ** and TRUNCATE modes also obtain the exclusive "writer" lock on the + ** database file. + ** + ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained + ** immediately, and a busy-handler is configured, it is invoked and the + ** writer lock retried until either the busy-handler returns 0 or the + ** lock is successfully obtained. + */ + if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){ + rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1); + if( rc==SQLITE_OK ){ + pWal->writeLock = 1; + }else if( rc==SQLITE_BUSY ){ + eMode2 = SQLITE_CHECKPOINT_PASSIVE; + xBusy2 = 0; + rc = SQLITE_OK; + } } } + }else{ + rc = SQLITE_OK; } @@ -69324,7 +71338,7 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint( ** immediately and do a partial checkpoint if it cannot obtain it. */ walDisableBlocking(pWal); rc = walIndexReadHdr(pWal, &isChanged); - if( eMode2!=SQLITE_CHECKPOINT_PASSIVE ) (void)walEnableBlocking(pWal); + if( eMode2>SQLITE_CHECKPOINT_PASSIVE ) (void)walEnableBlocking(pWal); if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){ sqlite3OsUnfetch(pWal->pDbFd, 0, 0); } @@ -69332,9 +71346,10 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint( /* Copy data from the log to the database file. */ if( rc==SQLITE_OK ){ + sqlite3FaultSim(660); if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){ rc = SQLITE_CORRUPT_BKPT; - }else{ + }else if( eMode2!=SQLITE_CHECKPOINT_NOOP ){ rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags,zBuf); } @@ -69362,7 +71377,7 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint( sqlite3WalDb(pWal, 0); /* Release the locks. */ - sqlite3WalEndWriteTransaction(pWal); + (void)sqlite3WalEndWriteTransaction(pWal); if( pWal->ckptLock ){ walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1); pWal->ckptLock = 0; @@ -69585,6 +71600,64 @@ SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){ return pWal->pWalFd; } +#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_WALSTAT) +/* +** Helper function to sqlite3WalStat(). +** +** Append JSON-5 structure elements onto describing the current state +** of pWal onto the end of pStr. This function is for debugging and +** analysis only and is not included in production builds. +*/ +static void walIndexHdrStat(volatile WalIndexHdr *pHdr, sqlite3_str *pStr){ + sqlite3_str_appendf(pStr, "iVersion:%u",pHdr->iVersion); + sqlite3_str_appendf(pStr, ",iChange:%u",pHdr->iChange); + sqlite3_str_appendf(pStr, ",isInit:%u",pHdr->isInit); + sqlite3_str_appendf(pStr, ",bigEndCksum:%u",pHdr->bigEndCksum); + sqlite3_str_appendf(pStr, ",szPage:%u",pHdr->szPage); + sqlite3_str_appendf(pStr, ",mxFrame:%u",pHdr->mxFrame); + sqlite3_str_appendf(pStr, ",nPage:%u",pHdr->nPage); +#if 0 /* Not often needed. Declutter. */ + sqlite3_str_appendf(pStr, ",aFrameCksum:[0x%08x,0x%08x]", + pHdr->aFrameCksum[0], pHdr->aFrameCksum[1]); + sqlite3_str_appendf(pStr, ",aSalt:[0x%08x,0x%08x]", + pHdr->aSalt[0], pHdr->aSalt[1]); + sqlite3_str_appendf(pStr, ",aCksum:[0x%08x,0x%08x]", + pHdr->aCksum[0], pHdr->aCksum[1]); +#endif +} +#endif /* SQLITE_DEBUG || SQLITE_ENABLE_WALSTAT */ + + +#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_WALSTAT) +/* +** Append JSON-5 structure elements onto describing the current state +** of pWal onto the end of pStr. This function is for debugging and +** analysis only and is not included in production builds. +*/ +SQLITE_PRIVATE void sqlite3WalStat(Wal *pWal, sqlite3_str *pStr){ + SEH_TRY { + int i; + volatile WalCkptInfo *pInfo = walCkptInfo(pWal); + volatile WalIndexHdr *pHdr = walIndexHdr(pWal); + sqlite3_str_appendf(pStr, "hdr0:{"); + walIndexHdrStat(pHdr,pStr); + sqlite3_str_appendf(pStr, "},ckpt:{"); + sqlite3_str_appendf(pStr, "nBackfill:%u",pInfo->nBackfill); + sqlite3_str_appendf(pStr, ",aReadMark:[%u", pInfo->aReadMark[0]); + for(i=1; i<WAL_NREADER; i++){ + sqlite3_str_appendf(pStr, ",%u", pInfo->aReadMark[i]); + } + sqlite3_str_appendf(pStr, "],nBackfillAttempted:%u}", + pInfo->nBackfillAttempted); + + sqlite3_str_appendf(pStr, ",nWiData:%d", pWal->nWiData); + sqlite3_str_appendf(pStr, ",readLock:%d", pWal->readLock); + sqlite3_str_appendf(pStr, ",minFrame:%u", pWal->minFrame); + } + SEH_EXCEPT( ; ) +} +#endif /* SQLITE_DEBUG || SQLITE_ENABLE_WALSTAT */ + #endif /* #ifndef SQLITE_OMIT_WAL */ /************** End of wal.c *************************************************/ @@ -70106,6 +72179,12 @@ struct CellInfo { */ #define BTCURSOR_MAX_DEPTH 20 +/* +** Maximum amount of storage local to a database page, regardless of +** page size. +*/ +#define BT_MAX_LOCAL 65501 /* 65536 - 35 */ + /* ** A cursor is a pointer to a particular entry within a particular ** b-tree within a database file. @@ -70142,6 +72221,9 @@ struct BtCursor { Btree *pBtree; /* The Btree to which this cursor belongs */ Pgno *aOverflow; /* Cache of overflow page locations */ void *pKey; /* Saved key that was cursor last known position */ +#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG) + BtCursor *pCursorHintTableCursor; +#endif /* All fields above are zeroed when the cursor is allocated. See ** sqlite3BtreeCursorZero(). Fields that follow must be manually ** initialized. */ @@ -70310,6 +72392,7 @@ struct IntegrityCk { int nErr; /* Number of messages written to zErrMsg so far */ int rc; /* SQLITE_OK, SQLITE_NOMEM, or SQLITE_INTERRUPT */ u32 nStep; /* Number of steps into the integrity_check process */ + u8 nAbove; /* Current btree recursion depth */ const char *zPfx; /* Error message prefix */ Pgno v0; /* Value for first %u substitution in zPfx (root page) */ Pgno v1; /* Value for second %u substitution in zPfx (current pg) */ @@ -70318,6 +72401,9 @@ struct IntegrityCk { u32 *heap; /* Min-heap used for analyzing cell coverage */ sqlite3 *db; /* Database connection running the check */ i64 nRow; /* Number of rows visited in current tree */ +#ifdef SQLITE_DEBUG + u32 mxHeap; /* Maximum number of entries in the Min-heap */ +#endif }; /* @@ -70514,7 +72600,7 @@ SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){ */ static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){ int i; - int skipOk = 1; + u8 skipOk = 1; Btree *p; assert( sqlite3_mutex_held(db->mutex) ); for(i=0; i<db->nDb; i++){ @@ -70656,6 +72742,16 @@ SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){ */ /* #include "btreeInt.h" */ +/* +** Suppress false-positive compiler warnings from GCC. Warnings are +** re-enabled at the bottom of this source file. +*/ +#if defined(__GNUC__) && __GNUC__>=11 +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wstringop-overread" +# pragma GCC diagnostic ignored "-Wstringop-overflow" +#endif + /* ** The header string that appears at the beginning of every ** SQLite database. @@ -71370,7 +73466,7 @@ static int saveCursorKey(BtCursor *pCur){ ** below. */ void *pKey; pCur->nKey = sqlite3BtreePayloadSize(pCur); - pKey = sqlite3Malloc( pCur->nKey + 9 + 8 ); + pKey = sqlite3Malloc( ((i64)pCur->nKey) + 9 + 8 ); if( pKey ){ rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey); if( rc==SQLITE_OK ){ @@ -71513,7 +73609,7 @@ static int btreeMoveto( assert( nKey==(i64)(int)nKey ); pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo); if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT; - sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey); + sqlite3VdbeRecordUnpack((int)nKey, pKey, pIdxKey); if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){ rc = SQLITE_CORRUPT_BKPT; }else{ @@ -71636,31 +73732,48 @@ SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow) SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){ /* Used only by system that substitute their own storage engine */ #ifdef SQLITE_DEBUG - if( ALWAYS(eHintType==BTREE_HINT_RANGE) ){ - va_list ap; + va_list ap; + va_start(ap, eHintType); + if( eHintType==BTREE_HINT_RANGE ){ Expr *pExpr; Walker w; memset(&w, 0, sizeof(w)); w.xExprCallback = sqlite3CursorRangeHintExprCheck; - va_start(ap, eHintType); pExpr = va_arg(ap, Expr*); w.u.aMem = va_arg(ap, Mem*); - va_end(ap); assert( pExpr!=0 ); assert( w.u.aMem!=0 ); sqlite3WalkExpr(&w, pExpr); + }else if( ALWAYS(eHintType==BTREE_HINT_TABLECURSOR) ){ + BtCursor *pCsr = va_arg(ap, BtCursor*); + assert( pCur->pCursorHintTableCursor==0 + || pCur->pCursorHintTableCursor==pCsr + ); + assert( pCsr->pKeyInfo==0 || CORRUPT_DB ); + pCur->pCursorHintTableCursor = pCsr; } + va_end(ap); #endif /* SQLITE_DEBUG */ } #endif /* SQLITE_ENABLE_CURSOR_HINTS */ +#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG) +/* +** Return the pointer configured via the BTREE_HINT_TABLECURSOR hint on +** cursor pCsr. This is used from OP_DeferredSeek to assert() that the +** index cursor has been correctly configured with the table cursor. +*/ +SQLITE_PRIVATE BtCursor *sqlite3BtreeCursorHintTblCsr(BtCursor *pCsr){ + return pCsr->pCursorHintTableCursor; +} +#endif /* ** Provide flag hints to the cursor. */ SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){ assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 ); - pCur->hints = x; + pCur->hints = (u8)x; } @@ -71854,14 +73967,15 @@ static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow( static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){ int maxLocal; /* Maximum amount of payload held locally */ maxLocal = pPage->maxLocal; + assert( nPayload>=0 ); if( nPayload<=maxLocal ){ - return nPayload; + return (int)nPayload; }else{ int minLocal; /* Minimum amount of payload held locally */ int surplus; /* Overflow payload available for local storage */ minLocal = pPage->minLocal; - surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4); - return ( surplus <= maxLocal ) ? surplus : minLocal; + surplus = (int)(minLocal +(nPayload - minLocal)%(pPage->pBt->usableSize-4)); + return (surplus <= maxLocal) ? surplus : minLocal; } } @@ -71890,7 +74004,7 @@ static void btreeParseCellPtrNoPayload( #ifndef SQLITE_DEBUG UNUSED_PARAMETER(pPage); #endif - pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey); + pInfo->nSize = 4 + sqlite3GetVarint(&pCell[4], (u64*)&pInfo->nKey); pInfo->nPayload = 0; pInfo->nLocal = 0; pInfo->pPayload = 0; @@ -71902,7 +74016,7 @@ static void btreeParseCellPtr( CellInfo *pInfo /* Fill in this structure */ ){ u8 *pIter; /* For scanning through pCell */ - u32 nPayload; /* Number of bytes of cell payload */ + u64 nPayload; /* Number of bytes of cell payload */ u64 iKey; /* Extracted Key value */ assert( sqlite3_mutex_held(pPage->pBt->mutex) ); @@ -71924,12 +74038,13 @@ static void btreeParseCellPtr( do{ nPayload = (nPayload<<7) | (*++pIter & 0x7f); }while( (*pIter)>=0x80 && pIter<pEnd ); + nPayload &= 0xffffffff; } pIter++; /* The next block of code is equivalent to: ** - ** pIter += getVarint(pIter, (u64*)&pInfo->nKey); + ** pIter += sqlite3GetVarint(pIter, (u64*)&pInfo->nKey); ** ** The code is inlined and the loop is unrolled for performance. ** This routine is a high-runner. @@ -71967,15 +74082,16 @@ static void btreeParseCellPtr( pIter++; pInfo->nKey = *(i64*)&iKey; - pInfo->nPayload = nPayload; + pInfo->nPayload = (u32)nPayload; pInfo->pPayload = pIter; testcase( nPayload==pPage->maxLocal ); testcase( nPayload==(u32)pPage->maxLocal+1 ); + assert( pPage->maxLocal <= BT_MAX_LOCAL ); if( nPayload<=pPage->maxLocal ){ /* This is the (easy) common case where the entire payload fits ** on the local page. No overflow is required. */ - pInfo->nSize = nPayload + (u16)(pIter - pCell); + pInfo->nSize = (u16)nPayload + (u16)(pIter - pCell); if( pInfo->nSize<4 ) pInfo->nSize = 4; pInfo->nLocal = (u16)nPayload; }else{ @@ -72008,11 +74124,13 @@ static void btreeParseCellPtrIndex( pInfo->pPayload = pIter; testcase( nPayload==pPage->maxLocal ); testcase( nPayload==(u32)pPage->maxLocal+1 ); + assert( nPayload>=0 ); + assert( pPage->maxLocal <= BT_MAX_LOCAL ); if( nPayload<=pPage->maxLocal ){ /* This is the (easy) common case where the entire payload fits ** on the local page. No overflow is required. */ - pInfo->nSize = nPayload + (u16)(pIter - pCell); + pInfo->nSize = (u16)nPayload + (u16)(pIter - pCell); if( pInfo->nSize<4 ) pInfo->nSize = 4; pInfo->nLocal = (u16)nPayload; }else{ @@ -72551,24 +74669,24 @@ static SQLITE_INLINE int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ ** at the end of the page. So do additional corruption checks inside this ** routine and return SQLITE_CORRUPT if any problems are found. */ -static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ - u16 iPtr; /* Address of ptr to next freeblock */ - u16 iFreeBlk; /* Address of the next freeblock */ +static int freeSpace(MemPage *pPage, int iStart, int iSize){ + int iPtr; /* Address of ptr to next freeblock */ + int iFreeBlk; /* Address of the next freeblock */ u8 hdr; /* Page header size. 0 or 100 */ - u8 nFrag = 0; /* Reduction in fragmentation */ - u16 iOrigSize = iSize; /* Original value of iSize */ - u16 x; /* Offset to cell content area */ - u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */ + int nFrag = 0; /* Reduction in fragmentation */ + int iOrigSize = iSize; /* Original value of iSize */ + int x; /* Offset to cell content area */ + int iEnd = iStart + iSize; /* First byte past the iStart buffer */ unsigned char *data = pPage->aData; /* Page content */ u8 *pTmp; /* Temporary ptr into data[] */ assert( pPage->pBt!=0 ); assert( sqlite3PagerIswriteable(pPage->pDbPage) ); assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize ); - assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize ); + assert( CORRUPT_DB || iEnd <= (int)pPage->pBt->usableSize ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); assert( iSize>=4 ); /* Minimum cell size is 4 */ - assert( CORRUPT_DB || iStart<=pPage->pBt->usableSize-4 ); + assert( CORRUPT_DB || iStart<=(int)pPage->pBt->usableSize-4 ); /* The list of freeblocks must be in ascending order. Find the ** spot on the list where iStart should be inserted. @@ -72585,7 +74703,7 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ } iPtr = iFreeBlk; } - if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */ + if( iFreeBlk>(int)pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */ return SQLITE_CORRUPT_PAGE(pPage); } assert( iFreeBlk>iPtr || iFreeBlk==0 || CORRUPT_DB ); @@ -72600,7 +74718,7 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ nFrag = iFreeBlk - iEnd; if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage); iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]); - if( iEnd > pPage->pBt->usableSize ){ + if( iEnd > (int)pPage->pBt->usableSize ){ return SQLITE_CORRUPT_PAGE(pPage); } iSize = iEnd - iStart; @@ -72621,7 +74739,7 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ } } if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage); - data[hdr+7] -= nFrag; + data[hdr+7] -= (u8)nFrag; } pTmp = &data[hdr+5]; x = get2byte(pTmp); @@ -72642,7 +74760,8 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ /* Insert the new freeblock into the freelist */ put2byte(&data[iPtr], iStart); put2byte(&data[iStart], iFreeBlk); - put2byte(&data[iStart+2], iSize); + assert( iSize>=0 && iSize<=0xffff ); + put2byte(&data[iStart+2], (u16)iSize); } pPage->nFree += iOrigSize; return SQLITE_OK; @@ -72773,8 +74892,15 @@ static int btreeComputeFreeSpace(MemPage *pPage){ } next = get2byte(&data[pc]); size = get2byte(&data[pc+2]); + if( size<4 && sqlite3FaultSim(422)==SQLITE_OK ){ + /* Minimum freeblock size is 4. Enable fault-sim 422 to disable this + ** check to reach interesting error states. However, disabling this + ** check can cause assertion faults due to min-heap overflow. All + ** fault-sims are for testing use only, but this one especially so. */ + return SQLITE_CORRUPT_PAGE(pPage); + } nFree = nFree + size; - if( next<=pc+size+3 ) break; + if( next<pc+size+4 ) break; pc = next; } if( next>0 ){ @@ -72868,7 +74994,7 @@ static int btreeInitPage(MemPage *pPage){ assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); pPage->maskPage = (u16)(pBt->pageSize - 1); pPage->nOverflow = 0; - pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize; + pPage->cellOffset = (u16)(pPage->hdrOffset + 8 + pPage->childPtrSize); pPage->aCellIdx = data + pPage->childPtrSize + 8; pPage->aDataEnd = pPage->aData + pBt->pageSize; pPage->aDataOfst = pPage->aData + pPage->childPtrSize; @@ -72902,8 +75028,8 @@ static int btreeInitPage(MemPage *pPage){ static void zeroPage(MemPage *pPage, int flags){ unsigned char *data = pPage->aData; BtShared *pBt = pPage->pBt; - u8 hdr = pPage->hdrOffset; - u16 first; + int hdr = pPage->hdrOffset; + int first; assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno || CORRUPT_DB ); assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); @@ -72920,7 +75046,7 @@ static void zeroPage(MemPage *pPage, int flags){ put2byte(&data[hdr+5], pBt->usableSize); pPage->nFree = (u16)(pBt->usableSize - first); decodeFlags(pPage, flags); - pPage->cellOffset = first; + pPage->cellOffset = (u16)first; pPage->aDataEnd = &data[pBt->pageSize]; pPage->aCellIdx = &data[first]; pPage->aDataOfst = &data[pPage->childPtrSize]; @@ -73491,6 +75617,7 @@ static int removeFromSharingList(BtShared *pBt){ sqlite3_mutex_leave(pMainMtx); return removed; #else + UNUSED_PARAMETER( pBt ); return 1; #endif } @@ -73706,8 +75833,12 @@ SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, BtShared *pBt = p->pBt; assert( nReserve>=0 && nReserve<=255 ); sqlite3BtreeEnter(p); - pBt->nReserveWanted = nReserve; + pBt->nReserveWanted = (u8)nReserve; x = pBt->pageSize - pBt->usableSize; + if( x==nReserve && (pageSize==0 || (u32)pageSize==pBt->pageSize) ){ + sqlite3BtreeLeave(p); + return SQLITE_OK; + } if( nReserve<x ) nReserve = x; if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){ sqlite3BtreeLeave(p); @@ -73812,7 +75943,7 @@ SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) ); if( newFlag>=0 ){ p->pBt->btsFlags &= ~BTS_FAST_SECURE; - p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag; + p->pBt->btsFlags |= (u16)(BTS_SECURE_DELETE*newFlag); } b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE; sqlite3BtreeLeave(p); @@ -74303,6 +76434,30 @@ static SQLITE_NOINLINE int btreeBeginTrans( } #endif +#ifdef SQLITE_EXPERIMENTAL_PRAGMA_20251114 + /* If both a read and write transaction will be opened by this call, + ** then issue a file-control as if the following pragma command had + ** been evaluated: + ** + ** PRAGMA experimental_pragma_20251114 = 1|2 + ** + ** where the RHS is "1" if wrflag is 1 (RESERVED lock), or "2" if wrflag + ** is 2 (EXCLUSIVE lock). Ignore any result or error returned by the VFS. + ** + ** WARNING: This code will likely remain part of SQLite only temporarily - + ** it exists to allow users to experiment with certain types of blocking + ** locks in custom VFS implementations. It MAY BE REMOVED AT ANY TIME. */ + if( pBt->pPage1==0 && wrflag ){ + sqlite3_file *fd = sqlite3PagerFile(pPager); + char *aFcntl[3] = {0,0,0}; + aFcntl[1] = "experimental_pragma_20251114"; + assert( wrflag==1 || wrflag==2 ); + aFcntl[2] = (wrflag==1 ? "1" : "2"); + sqlite3OsFileControlHint(fd, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); + sqlite3_free(aFcntl[0]); + } +#endif + /* Call lockBtree() until either pBt->pPage1 is populated or ** lockBtree() returns something other than SQLITE_OK. lockBtree() ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after @@ -74332,6 +76487,13 @@ static SQLITE_NOINLINE int btreeBeginTrans( (void)sqlite3PagerWalWriteLock(pPager, 0); unlockBtreeIfUnused(pBt); } +#if defined(SQLITE_ENABLE_SETLK_TIMEOUT) + if( rc==SQLITE_BUSY_TIMEOUT ){ + /* If a blocking lock timed out, break out of the loop here so that + ** the busy-handler is not invoked. */ + break; + } +#endif }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && btreeInvokeBusyHandler(pBt) ); sqlite3PagerWalDb(pPager, 0); @@ -75743,7 +77905,7 @@ static int accessPayload( getCellInfo(pCur); aPayload = pCur->info.pPayload; - assert( offset+amt <= pCur->info.nPayload ); + assert( (u64)offset+(u64)amt <= (u64)pCur->info.nPayload ); assert( aPayload > pPage->aData ); if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){ @@ -75784,7 +77946,9 @@ static int accessPayload( ** means "not yet known" (the cache is lazily populated). */ if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){ - int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; + i64 nOvfl = pCur->info.nPayload; + testcase( nOvfl - pCur->info.nLocal + ovflSize - 1 > 0xffffffffU ); + nOvfl = (nOvfl - pCur->info.nLocal + ovflSize-1)/ovflSize; if( pCur->aOverflow==0 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow) ){ @@ -75889,6 +78053,14 @@ static int accessPayload( (eOp==0 ? PAGER_GET_READONLY : 0) ); if( rc==SQLITE_OK ){ + if( eOp!=0 + && (sqlite3PagerPageRefcount(pDbPage)!=1 + || NEVER(((MemPage*)sqlite3PagerGetExtra(pDbPage))->isInit)) + && sqlite3FaultSim(411)==SQLITE_OK + ){ + sqlite3PagerUnref(pDbPage); + return SQLITE_CORRUPT_PAGE(pPage); + } aPayload = sqlite3PagerGetData(pDbPage); nextPage = get4byte(aPayload); rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); @@ -76290,6 +78462,30 @@ SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ return rc; } +/* Set *pRes to 1 (true) if the BTree pointed to by cursor pCur contains zero +** rows of content. Set *pRes to 0 (false) if the table contains content. +** Return SQLITE_OK on success or some error code (ex: SQLITE_NOMEM) if +** something goes wrong. +*/ +SQLITE_PRIVATE int sqlite3BtreeIsEmpty(BtCursor *pCur, int *pRes){ + int rc; + + assert( cursorOwnsBtShared(pCur) ); + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + if( NEVER(pCur->eState==CURSOR_VALID) ){ + *pRes = 0; + return SQLITE_OK; + } + rc = moveToRoot(pCur); + if( rc==SQLITE_EMPTY ){ + *pRes = 1; + rc = SQLITE_OK; + }else{ + *pRes = 0; + } + return rc; +} + #ifdef SQLITE_DEBUG /* The cursors is CURSOR_VALID and has BTCF_AtLast set. Verify that ** this flags are true for a consistent database. @@ -76459,7 +78655,7 @@ SQLITE_PRIVATE int sqlite3BtreeTableMoveto( } } } - getVarint(pCell, (u64*)&nCellKey); + nCellKey = sqlite3VarintValue(pCell); if( nCellKey<intKey ){ lwr = idx+1; if( lwr>upr ){ c = -1; break; } @@ -76509,28 +78705,27 @@ SQLITE_PRIVATE int sqlite3BtreeTableMoveto( } /* -** Compare the "idx"-th cell on the page the cursor pCur is currently -** pointing to to pIdxKey using xRecordCompare. Return negative or +** Compare the "idx"-th cell on the page pPage against the key +** pointing to by pIdxKey using xRecordCompare. Return negative or ** zero if the cell is less than or equal pIdxKey. Return positive ** if unknown. ** -** Return value negative: Cell at pCur[idx] less than pIdxKey +** Return value negative: Cell at pPage[idx] less than pIdxKey ** -** Return value is zero: Cell at pCur[idx] equals pIdxKey +** Return value is zero: Cell at pPage[idx] equals pIdxKey ** ** Return value positive: Nothing is known about the relationship -** of the cell at pCur[idx] and pIdxKey. +** of the cell at pPage[idx] and pIdxKey. ** ** This routine is part of an optimization. It is always safe to return ** a positive value as that will cause the optimization to be skipped. */ static int indexCellCompare( - BtCursor *pCur, + MemPage *pPage, int idx, UnpackedRecord *pIdxKey, RecordCompare xRecordCompare ){ - MemPage *pPage = pCur->pPage; int c; int nCell; /* Size of the pCell cell in bytes */ u8 *pCell = findCellPastPtr(pPage, idx); @@ -76540,14 +78735,14 @@ static int indexCellCompare( /* This branch runs if the record-size field of the cell is a ** single byte varint and the record fits entirely on the main ** b-tree page. */ - testcase( pCell+nCell+1==pPage->aDataEnd ); + if( pCell + nCell >= pPage->aDataEnd ) return 99; c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey); }else if( !(pCell[1] & 0x80) && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal ){ /* The record-size field is a 2 byte varint and the record ** fits entirely on the main b-tree page. */ - testcase( pCell+nCell+2==pPage->aDataEnd ); + if( pCell + nCell >= pPage->aDataEnd ) return 99; c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey); }else{ /* If the record extends into overflow pages, do not attempt @@ -76639,14 +78834,14 @@ SQLITE_PRIVATE int sqlite3BtreeIndexMoveto( ){ int c; if( pCur->ix==pCur->pPage->nCell-1 - && (c = indexCellCompare(pCur, pCur->ix, pIdxKey, xRecordCompare))<=0 + && (c = indexCellCompare(pCur->pPage,pCur->ix,pIdxKey,xRecordCompare))<=0 && pIdxKey->errCode==SQLITE_OK ){ *pRes = c; return SQLITE_OK; /* Cursor already pointing at the correct spot */ } if( pCur->iPage>0 - && indexCellCompare(pCur, 0, pIdxKey, xRecordCompare)<=0 + && indexCellCompare(pCur->pPage, 0, pIdxKey, xRecordCompare)<=0 && pIdxKey->errCode==SQLITE_OK ){ pCur->curFlags &= ~(BTCF_ValidOvfl|BTCF_AtLast); @@ -76709,14 +78904,17 @@ SQLITE_PRIVATE int sqlite3BtreeIndexMoveto( /* This branch runs if the record-size field of the cell is a ** single byte varint and the record fits entirely on the main ** b-tree page. */ - testcase( pCell+nCell+1==pPage->aDataEnd ); + if( pCell + nCell >= pPage->aDataEnd ){ + rc = SQLITE_CORRUPT_PAGE(pPage); + goto moveto_index_finish; + } c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey); }else if( !(pCell[1] & 0x80) && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal + && pCell + nCell < pPage->aDataEnd ){ /* The record-size field is a 2 byte varint and the record ** fits entirely on the main b-tree page. */ - testcase( pCell+nCell+2==pPage->aDataEnd ); c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey); }else{ /* The record flows over onto one or more overflow pages. In @@ -76741,7 +78939,7 @@ SQLITE_PRIVATE int sqlite3BtreeIndexMoveto( rc = SQLITE_CORRUPT_PAGE(pPage); goto moveto_index_finish; } - pCellKey = sqlite3Malloc( nCell+nOverrun ); + pCellKey = sqlite3Malloc( (u64)nCell+(u64)nOverrun ); if( pCellKey==0 ){ rc = SQLITE_NOMEM_BKPT; goto moveto_index_finish; @@ -76863,7 +79061,7 @@ SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){ n = pCur->pPage->nCell; for(i=0; i<pCur->iPage; i++){ - n *= pCur->apPage[i]->nCell; + n *= pCur->apPage[i]->nCell+1; } return n; } @@ -77664,7 +79862,7 @@ static int fillInCell( nSrc = pX->nData; assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */ nHeader += putVarint32(&pCell[nHeader], nPayload); - nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey); + nHeader += sqlite3PutVarint(&pCell[nHeader], *(u64*)&pX->nKey); }else{ assert( pX->nKey<=0x7fffffff && pX->pKey!=0 ); nSrc = nPayload = (int)pX->nKey; @@ -78260,7 +80458,8 @@ static int rebuildPage( } /* The pPg->nFree field is now set incorrectly. The caller will fix it. */ - pPg->nCell = nCell; + assert( nCell < 10922 ); + pPg->nCell = (u16)nCell; pPg->nOverflow = 0; put2byte(&aData[hdr+1], 0); @@ -78507,9 +80706,13 @@ static int editPage( if( pageInsertArray( pPg, pBegin, &pData, pCellptr, iNew+nCell, nNew-nCell, pCArray - ) ) goto editpage_fail; + ) + ){ + goto editpage_fail; + } - pPg->nCell = nNew; + assert( nNew < 10922 ); + pPg->nCell = (u16)nNew; pPg->nOverflow = 0; put2byte(&aData[hdr+3], pPg->nCell); @@ -78818,7 +81021,7 @@ static int balance_nonroot( int pageFlags; /* Value of pPage->aData[0] */ int iSpace1 = 0; /* First unused byte of aSpace1[] */ int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */ - int szScratch; /* Size of scratch memory requested */ + u64 szScratch; /* Size of scratch memory requested */ MemPage *apOld[NB]; /* pPage and up to two siblings */ MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */ u8 *pRight; /* Location in parent of right-sibling pointer */ @@ -79315,7 +81518,12 @@ static int balance_nonroot( ** of the right-most new sibling page is set to the value that was ** originally in the same field of the right-most old sibling page. */ if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){ - MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1]; + MemPage *pOld; + if( nNew>nOld ){ + pOld = apNew[nOld-1]; + }else{ + pOld = apOld[nOld-1]; + } memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4); } @@ -79403,7 +81611,7 @@ static int balance_nonroot( j--; pNew->xParseCell(pNew, b.apCell[j], &info); pCell = pTemp; - sz = 4 + putVarint(&pCell[4], info.nKey); + sz = 4 + sqlite3PutVarint(&pCell[4], info.nKey); pTemp = 0; }else{ pCell -= 4; @@ -80103,7 +82311,7 @@ SQLITE_PRIVATE int sqlite3BtreeInsert( if( pCur->info.nKey==pX->nKey ){ BtreePayload x2; x2.pData = pX->pKey; - x2.nData = pX->nKey; + x2.nData = (int)pX->nKey; assert( pX->nKey<=0x7fffffff ); x2.nZero = 0; return btreeOverwriteCell(pCur, &x2); } @@ -80284,11 +82492,11 @@ SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 getCellInfo(pSrc); if( pSrc->info.nPayload<0x80 ){ - *(aOut++) = pSrc->info.nPayload; + *(aOut++) = (u8)pSrc->info.nPayload; }else{ aOut += sqlite3PutVarint(aOut, pSrc->info.nPayload); } - if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey); + if( pDest->pKeyInfo==0 ) aOut += sqlite3PutVarint(aOut, iKey); nIn = pSrc->info.nLocal; aIn = pSrc->info.pPayload; if( aIn+nIn>pSrc->pPage->aDataEnd ){ @@ -80297,7 +82505,7 @@ SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 nRem = pSrc->info.nPayload; if( nIn==nRem && nIn<pDest->pPage->maxLocal ){ memcpy(aOut, aIn, nIn); - pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace); + pBt->nPreformatSize = nIn + (int)(aOut - pBt->pTmpSpace); return SQLITE_OK; }else{ int rc = SQLITE_OK; @@ -80309,7 +82517,7 @@ SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 u32 nOut; /* Size of output buffer aOut[] */ nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload); - pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace); + pBt->nPreformatSize = (int)nOut + (int)(aOut - pBt->pTmpSpace); if( nOut<pSrc->info.nPayload ){ pPgnoOut = &aOut[nOut]; pBt->nPreformatSize += 4; @@ -80348,7 +82556,7 @@ SQLITE_PRIVATE int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 }while( rc==SQLITE_OK && nOut>0 ); if( rc==SQLITE_OK && nRem>0 && ALWAYS(pPgnoOut) ){ - Pgno pgnoNew; + Pgno pgnoNew = 0; /* Prevent harmless static-analyzer warning */ MemPage *pNew = 0; rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); put4byte(pPgnoOut, pgnoNew); @@ -80527,7 +82735,7 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){ assert( pTmp!=0 ); rc = sqlite3PagerWrite(pLeaf->pDbPage); if( rc==SQLITE_OK ){ - rc = insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n); + rc = insertCell(pPage, iCellIdx, pCell-4, nCell+4-(pCell[0]==2), pTmp, n); } dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc); if( rc ) return rc; @@ -80758,11 +82966,20 @@ SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){ /* ** Erase the given database page and all its children. Return ** the page to the freelist. +** +** The freePageFlag parameter serves a double role: +** +** * Bit 0 (freePageFlag&1) means that the page should be freed +** after it is cleared. +** +** * Bits 1-31 (freePageFlag>>1) is the depth of recursion. Use this +** to prevent a corrupt database file from recursing too deeply and +** overflowing the CPU stack. */ static int clearDatabasePage( BtShared *pBt, /* The BTree that contains the table */ Pgno pgno, /* Page number to clear */ - int freePageFlag, /* Deallocate page if true */ + int freePageFlag, /* bit 0: Deallocate page. Bits 1-31: depth */ i64 *pnChange /* Add number of Cells freed to this counter */ ){ MemPage *pPage; @@ -80776,6 +82993,9 @@ static int clearDatabasePage( if( pgno>btreePagecount(pBt) ){ return SQLITE_CORRUPT_PGNO(pgno); } + if( (freePageFlag>>1) > BTCURSOR_MAX_DEPTH ){ + return SQLITE_CORRUPT_PGNO(pgno); + } rc = getAndInitPage(pBt, pgno, &pPage, 0); if( rc ) return rc; if( (pBt->openFlags & BTREE_SINGLE)==0 @@ -80788,14 +83008,16 @@ static int clearDatabasePage( for(i=0; i<pPage->nCell; i++){ pCell = findCell(pPage, i); if( !pPage->leaf ){ - rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange); + rc = clearDatabasePage(pBt, get4byte(pCell), + (freePageFlag+2)|1, pnChange); if( rc ) goto cleardatabasepage_out; } BTREE_CLEAR_CELL(rc, pPage, pCell, info); if( rc ) goto cleardatabasepage_out; } if( !pPage->leaf ){ - rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange); + rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), + (freePageFlag+2)|1, pnChange); if( rc ) goto cleardatabasepage_out; if( pPage->intKey ) pnChange = 0; } @@ -80803,7 +83025,7 @@ static int clearDatabasePage( testcase( !pPage->intKey ); *pnChange += pPage->nCell; } - if( freePageFlag ){ + if( (freePageFlag&1)!=0 ){ freePage(pPage, &rc); }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF); @@ -80933,6 +83155,9 @@ static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){ } pMove = 0; rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0); + if( rc==SQLITE_OK ){ + rc = sqlite3PagerWrite(pMove->pDbPage); + } freePage(pMove, &rc); releasePage(pMove); if( rc!=SQLITE_OK ){ @@ -81438,19 +83663,24 @@ static int checkTreePage( /* Check that the page exists */ checkProgress(pCheck); - if( pCheck->mxErr==0 ) goto end_of_check; + if( pCheck->mxErr==0 ) return 0; pBt = pCheck->pBt; usableSize = pBt->usableSize; if( iPage==0 ) return 0; if( checkRef(pCheck, iPage) ) return 0; pCheck->zPfx = "Tree %u page %u: "; pCheck->v1 = iPage; + pCheck->nAbove++; if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){ checkAppendMsg(pCheck, "unable to get the page. error code=%d", rc); if( rc==SQLITE_IOERR_NOMEM ) pCheck->rc = SQLITE_NOMEM; goto end_of_check; } + if( pCheck->nAbove > BTCURSOR_MAX_DEPTH ){ + checkAppendMsg(pCheck,"btree depth exceeds %d",BTCURSOR_MAX_DEPTH); + goto end_of_check; + } /* Clear MemPage.isInit to make sure the corruption detection code in ** btreeInitPage() is executed. */ @@ -81530,6 +83760,11 @@ static int checkTreePage( doCoverageCheck = 0; continue; } + if( info.nPayload && info.pPayload[0]<2 ){ + checkAppendMsg(pCheck, "Bad cell header size"); + doCoverageCheck = 0; + continue; + } /* Check for integer primary key out of range */ if( pPage->intKey ){ @@ -81571,6 +83806,7 @@ static int checkTreePage( } }else{ /* Populate the coverage-checking heap for leaf pages */ + assert( heap!=0 && heap[0] < pCheck->mxHeap ); btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1)); } } @@ -81590,6 +83826,7 @@ static int checkTreePage( u32 size; pc = get2byteAligned(&data[cellStart+i*2]); size = pPage->xCellSize(pPage, &data[pc]); + assert( heap!=0 && heap[0] < pCheck->mxHeap ); btreeHeapInsert(heap, (pc<<16)|(pc+size-1)); } } @@ -81606,6 +83843,7 @@ static int checkTreePage( assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */ size = get2byte(&data[i+2]); assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */ + assert( heap!=0 && heap[0] < pCheck->mxHeap ); btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1)); /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a ** big-endian integer which is the offset in the b-tree page of the next @@ -81662,6 +83900,7 @@ static int checkTreePage( pCheck->zPfx = saved_zPfx; pCheck->v1 = saved_v1; pCheck->v2 = saved_v2; + pCheck->nAbove--; return depth+1; } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ @@ -81739,7 +83978,10 @@ SQLITE_PRIVATE int sqlite3BtreeIntegrityCheck( checkOom(&sCheck); goto integrity_ck_cleanup; } - sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize ); + sCheck.heap = (u32*)sqlite3Malloc( pBt->pageSize*2 ); +#ifdef SQLITE_DEBUG + sCheck.mxHeap = pBt->pageSize/2 - 1; +#endif if( sCheck.heap==0 ){ checkOom(&sCheck); goto integrity_ck_cleanup; @@ -81791,7 +84033,9 @@ SQLITE_PRIVATE int sqlite3BtreeIntegrityCheck( } #endif sCheck.v0 = aRoot[i]; + assert( sCheck.nAbove==0 ); checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64); + assert( sCheck.nAbove==0 ); } sqlite3MemSetArrayInt64(aCnt, i, sCheck.nRow); } @@ -81824,7 +84068,7 @@ SQLITE_PRIVATE int sqlite3BtreeIntegrityCheck( /* Clean up and report errors. */ integrity_ck_cleanup: - sqlite3PageFree(sCheck.heap); + sqlite3_free(sCheck.heap); sqlite3_free(sCheck.aPgRef); *pnErr = sCheck.nErr; if( sCheck.nErr==0 ){ @@ -81930,6 +84174,7 @@ SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){ */ SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){ BtShared *pBt = p->pBt; + assert( nBytes==0 || nBytes==sizeof(Schema) ); sqlite3BtreeEnter(p); if( !pBt->pSchema && nBytes ){ pBt->pSchema = sqlite3DbMallocZero(0, nBytes); @@ -81946,6 +84191,7 @@ SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void */ SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){ int rc; + UNUSED_PARAMETER(p); /* only used in DEBUG builds */ assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK); @@ -82131,6 +84377,13 @@ SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){ } #endif +/* Re-enable GCC compiler warnings that were suppressed at the top +** of this source file to prevent annoying false-positives. +*/ +#if defined(__GNUC__) && __GNUC__>=11 +# pragma GCC diagnostic pop +#endif + /************** End of btree.c ***********************************************/ /************** Begin file backup.c ******************************************/ /* @@ -82155,6 +84408,7 @@ SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){ */ struct sqlite3_backup { sqlite3* pDestDb; /* Destination database handle */ + char *zDestDb; Btree *pDest; /* Destination b-tree file */ u32 iDestSchema; /* Original schema cookie in destination */ int bDestLocked; /* True once a write-transaction is open on pDest */ @@ -82215,8 +84469,10 @@ struct sqlite3_backup { ** error message to pErrorDb. */ static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){ - int i = sqlite3FindDbName(pDb, zDb); + int i; + assert( pDb!=0 ); + i = sqlite3FindDbName(pDb, zDb); if( i==1 ){ Parse sParse; int rc = 0; @@ -82244,10 +84500,8 @@ static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){ ** Attempt to set the page size of the destination to match the page size ** of the source. */ -static int setDestPgsz(sqlite3_backup *p){ - int rc; - rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),0,0); - return rc; +static int setDestPgsz(Btree *pDest, Btree *pSrc){ + return sqlite3BtreeSetPageSize(pDest, sqlite3BtreeGetPageSize(pSrc), 0, 0); } /* @@ -82304,27 +84558,37 @@ SQLITE_API sqlite3_backup *sqlite3_backup_init( ); p = 0; }else { + int nDest = sqlite3Strlen30(zDestDb); + /* Allocate space for a new sqlite3_backup object... ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a ** call to sqlite3_backup_init() and is destroyed by a call to ** sqlite3_backup_finish(). */ - p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup)); + p = (sqlite3_backup*)sqlite3MallocZero(sizeof(sqlite3_backup)+nDest+1); if( !p ){ sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT); + }else{ + p->zDestDb = (char*)&p[1]; + memcpy(p->zDestDb, zDestDb, nDest); } } /* If the allocation succeeded, populate the new object. */ if( p ){ + /* Do not store the pointer to the destination b-tree at this point. + ** This is because there is nothing preventing it from being detached + ** or otherwise freed before the first call to sqlite3_backup_step() + ** on this object. The source b-tree does not have this problem, as + ** incrementing Btree.nBackup (see below) effectively locks the object. */ + Btree *pDest = findBtree(pDestDb, pDestDb, zDestDb); p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb); - p->pDest = findBtree(pDestDb, pDestDb, zDestDb); p->pDestDb = pDestDb; p->pSrcDb = pSrcDb; p->iNext = 1; p->isAttached = 0; - if( 0==p->pSrc || 0==p->pDest - || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK + if( 0==p->pSrc || 0==pDest + || checkReadTransaction(pDestDb, pDest)!=SQLITE_OK ){ /* One (or both) of the named databases did not exist or an OOM ** error was hit. Or there is a transaction open on the destination @@ -82448,7 +84712,7 @@ static void attachBackupObject(sqlite3_backup *p){ */ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ int rc; - int destMode; /* Destination journal mode */ + int destMode = 0; /* Destination journal mode */ int pgszSrc = 0; /* Source page size */ int pgszDest = 0; /* Destination page size */ @@ -82464,7 +84728,8 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ rc = p->rc; if( !isFatalError(rc) ){ Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */ - Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */ + Btree * pDest = 0; /* Dest btree */ + Pager * pDestPager = 0; /* Dest pager */ int ii; /* Iterator variable */ int nSrcPage = -1; /* Size of source db in pages */ int bCloseTrans = 0; /* True if src db requires unlocking */ @@ -82478,6 +84743,7 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ rc = SQLITE_OK; } + /* If there is no open read-transaction on the source database, open ** one now. If a transaction is opened here, then it will be closed ** before this function exits. @@ -82487,34 +84753,48 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){ bCloseTrans = 1; } + /* Locate the destination btree and pager. */ + if( (pDest = p->pDest)==0 ){ + pDest = findBtree(p->pDestDb, p->pDestDb, p->zDestDb); + } + if( pDest==0 ){ + rc = SQLITE_ERROR; + }else{ + pDestPager = sqlite3BtreePager(pDest); + } + /* If the destination database has not yet been locked (i.e. if this ** is the first call to backup_step() for the current backup operation), ** try to set its page size to the same as the source database. This ** is especially important on ZipVFS systems, as in that case it is ** not possible to create a database file that uses one page size by ** writing to it with another. */ - if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){ + if( p->bDestLocked==0 && rc==SQLITE_OK + && setDestPgsz(pDest, p->pSrc)==SQLITE_NOMEM + ){ rc = SQLITE_NOMEM; } /* Lock the destination database, if it is not locked already. */ if( SQLITE_OK==rc && p->bDestLocked==0 - && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2, + && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(pDest, 2, (int*)&p->iDestSchema)) ){ p->bDestLocked = 1; + p->pDest = pDest; } /* Do not allow backup if the destination database is in WAL mode ** and the page sizes are different between source and destination */ - pgszSrc = sqlite3BtreeGetPageSize(p->pSrc); - pgszDest = sqlite3BtreeGetPageSize(p->pDest); - destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest)); - if( SQLITE_OK==rc - && (destMode==PAGER_JOURNALMODE_WAL || sqlite3PagerIsMemdb(pDestPager)) - && pgszSrc!=pgszDest - ){ - rc = SQLITE_READONLY; + if( rc==SQLITE_OK ){ + pgszSrc = sqlite3BtreeGetPageSize(p->pSrc); + pgszDest = sqlite3BtreeGetPageSize(p->pDest); + destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest)); + if( (destMode==PAGER_JOURNALMODE_WAL || sqlite3PagerIsMemdb(pDestPager)) + && pgszSrc!=pgszDest + ){ + rc = SQLITE_READONLY; + } } /* Now that there is a read-lock on the source database, query the @@ -82732,7 +85012,9 @@ SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){ } /* If a transaction is still open on the Btree, roll it back. */ - sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0); + if( p->pDest ){ + sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0); + } /* Set the error code of the destination database handle. */ rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc; @@ -83012,21 +85294,27 @@ static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){ StrAccum acc; assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) ); assert( sz>22 ); - if( p->flags & MEM_Int ){ -#if GCC_VERSION>=7000000 - /* Work-around for GCC bug - ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96270 */ + if( p->flags & (MEM_Int|MEM_IntReal) ){ +#if GCC_VERSION>=7000000 && GCC_VERSION<15000000 && defined(__i386__) + /* Work-around for GCC bug or bugs: + ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96270 + ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114659 + ** The problem appears to be fixed in GCC 15 */ i64 x; - assert( (p->flags&MEM_Int)*2==sizeof(x) ); - memcpy(&x, (char*)&p->u, (p->flags&MEM_Int)*2); + assert( (sqlite3Config.bSmallMalloc!=0xee)*8==sizeof(x) ); + memcpy(&x, (char*)&p->u.i, (sqlite3Config.bSmallMalloc!=0xee)*8); p->n = sqlite3Int64ToText(x, zBuf); #else p->n = sqlite3Int64ToText(p->u.i, zBuf); #endif + if( p->flags & MEM_IntReal ){ + memcpy(zBuf+p->n,".0", 3); + p->n += 2; + } }else{ sqlite3StrAccumInit(&acc, 0, zBuf, sz, 0); - sqlite3_str_appendf(&acc, "%!.15g", - (p->flags & MEM_IntReal)!=0 ? (double)p->u.i : p->u.r); + sqlite3_str_appendf(&acc, "%!.*g", + (p->db ? p->db->nFpDigit : 17), p->u.r); assert( acc.zText==zBuf && acc.mxAlloc<=0 ); zBuf[acc.nChar] = 0; /* Fast version of sqlite3StrAccumFinish(&acc) */ p->n = acc.nChar; @@ -83046,7 +85334,7 @@ static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){ ** corresponding string value, then it is important that the string be ** derived from the numeric value, not the other way around, to ensure ** that the index and table are consistent. See ticket -** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for +** https://sqlite.org/src/info/343634942dd54ab (2018-01-31) for ** an example. ** ** This routine looks at pMem to verify that if it has both a numeric @@ -83075,6 +85363,9 @@ SQLITE_PRIVATE int sqlite3VdbeMemValidStrRep(Mem *p){ assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 ); } if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1; + if( p->db==0 ){ + return 1; /* db->nFpDigit required to validate p->z[] */ + } memcpy(&tmp, p, sizeof(tmp)); vdbeMemRenderNum(sizeof(zBuf), zBuf, &tmp); z = p->z; @@ -83225,32 +85516,36 @@ SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){ ** ** This is an optimization. Correct operation continues even if ** this routine is a no-op. +** +** Return true if the strig is zero-terminated after this routine is +** called and false if it is not. */ -SQLITE_PRIVATE void sqlite3VdbeMemZeroTerminateIfAble(Mem *pMem){ +SQLITE_PRIVATE int sqlite3VdbeMemZeroTerminateIfAble(Mem *pMem){ if( (pMem->flags & (MEM_Str|MEM_Term|MEM_Ephem|MEM_Static))!=MEM_Str ){ /* pMem must be a string, and it cannot be an ephemeral or static string */ - return; + return 0; } - if( pMem->enc!=SQLITE_UTF8 ) return; - if( NEVER(pMem->z==0) ) return; + if( pMem->enc!=SQLITE_UTF8 ) return 0; + assert( pMem->z!=0 ); if( pMem->flags & MEM_Dyn ){ if( pMem->xDel==sqlite3_free && sqlite3_msize(pMem->z) >= (u64)(pMem->n+1) ){ pMem->z[pMem->n] = 0; pMem->flags |= MEM_Term; - return; + return 1; } if( pMem->xDel==sqlite3RCStrUnref ){ /* Blindly assume that all RCStr objects are zero-terminated */ pMem->flags |= MEM_Term; - return; + return 1; } }else if( pMem->szMalloc >= pMem->n+1 ){ pMem->z[pMem->n] = 0; pMem->flags |= MEM_Term; - return; + return 1; } + return 0; } /* @@ -83548,18 +85843,117 @@ SQLITE_PRIVATE i64 sqlite3VdbeIntValue(const Mem *pMem){ } } +/* +** This routine implements the uncommon and slower path for +** sqlite3MemRealValueRC() that has to deal with input strings +** that are not UTF8 or that are not zero-terminated. It is +** broken out into a separate no-inline routine so that the +** main sqlite3MemRealValueRC() routine can avoid unnecessary +** stack pushes. +** +** A text->float translation of pMem->z is written into *pValue. +** +** Result code invariants: +** +** rc==0 => ERROR: Input string not well-formed, or OOM +** rc<0 => Some prefix of the input is well-formed +** rc>0 => All of the input is well-formed +** (rc&2)==0 => The number is expressed as an integer, with no +** decimal point or eNNN suffix. +*/ +static SQLITE_NOINLINE int sqlite3MemRealValueRCSlowPath( + Mem *pMem, + double *pValue +){ + int rc = SQLITE_OK; + *pValue = 0.0; + if( pMem->enc==SQLITE_UTF8 ){ + char *zCopy = sqlite3DbStrNDup(pMem->db, pMem->z, pMem->n); + if( zCopy ){ + rc = sqlite3AtoF(zCopy, pValue); + sqlite3DbFree(pMem->db, zCopy); + } + return rc; + }else{ + int n, i, j; + char *zCopy; + const char *z; + + n = pMem->n & ~1; + zCopy = sqlite3DbMallocRaw(pMem->db, n/2 + 2); + if( zCopy ){ + z = pMem->z; + if( pMem->enc==SQLITE_UTF16LE ){ + for(i=j=0; i<n-1; i+=2, j++){ + zCopy[j] = z[i]; + if( z[i+1]!=0 ) break; + } + }else{ + for(i=j=0; i<n-1; i+=2, j++){ + if( z[i]!=0 ) break; + zCopy[j] = z[i+1]; + } + } + assert( j<=n/2 ); + zCopy[j] = 0; + rc = sqlite3AtoF(zCopy, pValue); + if( i<n ) rc = -100; + sqlite3DbFree(pMem->db, zCopy); + } + return rc; + } +} + +/* +** Invoke sqlite3AtoF() on the text value of pMem. Write the +** translation of the text input into *pValue. +** +** The caller must ensure that pMem->db!=0 and that pMem is in +** mode MEM_Str or MEM_Blob. +** +** Result code invariants: +** +** rc==0 => ERROR: Input string not well-formed, or OOM +** rc<0 => Some prefix of the input is well-formed +** rc>0 => All of the input is well-formed +** (rc&2)==0 => The number is expressed as an integer, with no +** decimal point or eNNN suffix. +*/ +SQLITE_PRIVATE int sqlite3MemRealValueRC(Mem *pMem, double *pValue){ + testcase( pMem->db==0 ); + assert( pMem->flags & (MEM_Str|MEM_Blob) ); + if( pMem->z==0 ){ + *pValue = 0.0; + return 0; + }else if( pMem->enc==SQLITE_UTF8 + && ((pMem->flags & MEM_Term)!=0 || sqlite3VdbeMemZeroTerminateIfAble(pMem)) + ){ + return sqlite3AtoF(pMem->z, pValue); + }else if( pMem->n==0 ){ + *pValue = 0.0; + return 0; + }else{ + return sqlite3MemRealValueRCSlowPath(pMem, pValue); + } +} + +/* +** This routine acts as a bridge from sqlite3VdbeRealValue() to +** sqlite3VdbeRealValueRC, allowing sqlite3VdbeRealValue() to avoid +** stuffing values onto the stack. +*/ +static SQLITE_NOINLINE double sqlite3MemRealValueNoRC(Mem *pMem){ + double r; + (void)sqlite3MemRealValueRC(pMem, &r); + return r; +} + /* ** Return the best representation of pMem that we can get into a ** double. If pMem is already a double or an integer, return its ** value. If it is a string or blob, try to convert it to a double. ** If it is a NULL, return 0.0. */ -static SQLITE_NOINLINE double memRealValue(Mem *pMem){ - /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ - double val = (double)0; - sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc); - return val; -} SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){ assert( pMem!=0 ); assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); @@ -83570,7 +85964,7 @@ SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){ testcase( pMem->flags & MEM_IntReal ); return (double)pMem->u.i; }else if( pMem->flags & (MEM_Str|MEM_Blob) ){ - return memRealValue(pMem); + return sqlite3MemRealValueNoRC(pMem); }else{ /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ return (double)0; @@ -83694,8 +86088,8 @@ SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){ sqlite3_int64 ix; assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 ); assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc); - if( ((rc==0 || rc==1) && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1) + rc = sqlite3MemRealValueRC(pMem, &pMem->u.r); + if( ((rc&2)==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<2) || sqlite3RealSameAsInt(pMem->u.r, (ix = sqlite3RealToI64(pMem->u.r))) ){ pMem->u.i = ix; @@ -83951,27 +86345,30 @@ SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){ SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){ int i; Mem *pX; - for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){ - if( pX->pScopyFrom==pMem ){ - u16 mFlags; - if( pVdbe->db->flags & SQLITE_VdbeTrace ){ - sqlite3DebugPrintf("Invalidate R[%d] due to change in R[%d]\n", - (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem)); - } - /* If pX is marked as a shallow copy of pMem, then try to verify that - ** no significant changes have been made to pX since the OP_SCopy. - ** A significant change would indicated a missed call to this - ** function for pX. Minor changes, such as adding or removing a - ** dual type, are allowed, as long as the underlying value is the - ** same. */ - mFlags = pMem->flags & pX->flags & pX->mScopyFlags; - assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i ); - - /* pMem is the register that is changing. But also mark pX as - ** undefined so that we can quickly detect the shallow-copy error */ - pX->flags = MEM_Undefined; - pX->pScopyFrom = 0; - } + if( pMem->bScopy ){ + for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){ + if( pX->pScopyFrom==pMem ){ + u16 mFlags; + if( pVdbe->db->flags & SQLITE_VdbeTrace ){ + sqlite3DebugPrintf("Invalidate R[%d] due to change in R[%d]\n", + (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem)); + } + /* If pX is marked as a shallow copy of pMem, then try to verify that + ** no significant changes have been made to pX since the OP_SCopy. + ** A significant change would indicated a missed call to this + ** function for pX. Minor changes, such as adding or removing a + ** dual type, are allowed, as long as the underlying value is the + ** same. */ + mFlags = pMem->flags & pX->flags & pX->mScopyFlags; + assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i ); + + /* pMem is the register that is changing. But also mark pX as + ** undefined so that we can quickly detect the shallow-copy error */ + pX->flags = MEM_Undefined; + pX->pScopyFrom = 0; + } + } + pMem->bScopy = 0; } pMem->pScopyFrom = 0; } @@ -84128,6 +86525,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr( if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){ return SQLITE_NOMEM_BKPT; } + assert( pMem->z!=0 ); memcpy(pMem->z, z, nAlloc); }else{ sqlite3VdbeMemRelease(pMem); @@ -84155,6 +86553,84 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr( return SQLITE_OK; } +/* Like sqlite3VdbeMemSetStr() except: +** +** enc is always SQLITE_UTF8 +** pMem->db is always non-NULL +*/ +SQLITE_PRIVATE int sqlite3VdbeMemSetText( + Mem *pMem, /* Memory cell to set to string value */ + const char *z, /* String pointer */ + i64 n, /* Bytes in string, or negative */ + void (*xDel)(void*) /* Destructor function */ +){ + i64 nByte = n; /* New value for pMem->n */ + u16 flags; + + assert( pMem!=0 ); + assert( pMem->db!=0 ); + assert( sqlite3_mutex_held(pMem->db->mutex) ); + assert( !sqlite3VdbeMemIsRowSet(pMem) ); + + /* If z is a NULL pointer, set pMem to contain an SQL NULL. */ + if( !z ){ + sqlite3VdbeMemSetNull(pMem); + return SQLITE_OK; + } + + if( nByte<0 ){ + nByte = strlen(z); + flags = MEM_Str|MEM_Term; + }else{ + flags = MEM_Str; + } + if( nByte>(i64)pMem->db->aLimit[SQLITE_LIMIT_LENGTH] ){ + if( xDel && xDel!=SQLITE_TRANSIENT ){ + if( xDel==SQLITE_DYNAMIC ){ + sqlite3DbFree(pMem->db, (void*)z); + }else{ + xDel((void*)z); + } + } + sqlite3VdbeMemSetNull(pMem); + return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG); + } + + /* The following block sets the new values of Mem.z and Mem.xDel. It + ** also sets a flag in local variable "flags" to indicate the memory + ** management (one of MEM_Dyn or MEM_Static). + */ + if( xDel==SQLITE_TRANSIENT ){ + i64 nAlloc = nByte + 1; + testcase( nAlloc==31 ); + testcase( nAlloc==32 ); + if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){ + return SQLITE_NOMEM_BKPT; + } + assert( pMem->z!=0 ); + memcpy(pMem->z, z, nByte); + pMem->z[nByte] = 0; + }else{ + sqlite3VdbeMemRelease(pMem); + pMem->z = (char *)z; + if( xDel==SQLITE_DYNAMIC ){ + pMem->zMalloc = pMem->z; + pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc); + pMem->xDel = 0; + }else if( xDel==SQLITE_STATIC ){ + pMem->xDel = xDel; + flags |= MEM_Static; + }else{ + pMem->xDel = xDel; + flags |= MEM_Dyn; + } + } + pMem->flags = flags; + pMem->n = (int)(nByte & 0x7fffffff); + pMem->enc = SQLITE_UTF8; + return SQLITE_OK; +} + /* ** Move data out of a btree key or data field and into a Mem structure. ** The data is payload from the entry that pCur is currently pointing @@ -84178,7 +86654,12 @@ SQLITE_PRIVATE int sqlite3VdbeMemFromBtree( ){ int rc; pMem->flags = MEM_Null; - if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){ + testcase( amt==SQLITE_MAX_ALLOCATION_SIZE-1 ); + testcase( amt==SQLITE_MAX_ALLOCATION_SIZE ); + if( amt>=SQLITE_MAX_ALLOCATION_SIZE ){ + return SQLITE_NOMEM_BKPT; + } + if( (u64)amt + (u64)offset > (u64)sqlite3BtreeMaxRecordSize(pCur) ){ return SQLITE_CORRUPT_BKPT; } if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){ @@ -84342,7 +86823,7 @@ static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){ if( pRec==0 ){ Index *pIdx = p->pIdx; /* Index being probed */ - int nByte; /* Bytes of space to allocate */ + i64 nByte; /* Bytes of space to allocate */ int i; /* Counter variable */ int nCol = pIdx->nColumn; /* Number of index columns including rowid */ @@ -84408,7 +86889,7 @@ static int valueFromFunction( ){ sqlite3_context ctx; /* Context object for function invocation */ sqlite3_value **apVal = 0; /* Function arguments */ - int nVal = 0; /* Size of apVal[] array */ + int nVal = 0; /* Number of function arguments */ FuncDef *pFunc = 0; /* Function definition */ sqlite3_value *pVal = 0; /* New value */ int rc = SQLITE_OK; /* Return code */ @@ -84578,7 +87059,7 @@ static int valueFromExpr( if( affinity==SQLITE_AFF_BLOB ){ if( op==TK_FLOAT ){ assert( pVal && pVal->z && pVal->flags==(MEM_Str|MEM_Term) ); - sqlite3AtoF(pVal->z, &pVal->u.r, pVal->n, SQLITE_UTF8); + sqlite3AtoF(pVal->z, &pVal->u.r); pVal->flags = MEM_Real; }else if( op==TK_INTEGER ){ /* This case is required by -9223372036854775808 and other strings @@ -84688,7 +87169,30 @@ SQLITE_PRIVATE int sqlite3ValueFromExpr( u8 affinity, /* Affinity to use */ sqlite3_value **ppVal /* Write the new value here */ ){ - return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0; + int rc = SQLITE_OK; + sqlite3_value *pVal = 0; + if( pExpr ){ + rc = valueFromExpr(db, pExpr, enc, affinity, &pVal, 0); + if( rc==SQLITE_OK && pVal + && affinity==SQLITE_AFF_REAL + && (pVal->flags & MEM_Int) + && (pVal->u.i<-140737488355328LL || pVal->u.i>140737488355327LL) + ){ + /* If the integer value is too large to fit in a 6-byte integer and + ** the affinity is REAL, convert it to a real value now. In most + ** cases an OP_RealAffinity opcode will be used to convert the + ** value to an actual real, but this opcode is omitted if the values + ** are being read directly from a table in order to create an index + ** key. It is important to get a "real" real value for the larger + ** magnitude integer values so that comparisons work correctly - + ** SQLite by default will convert real values to integers before + ** doing the comparison, which is different from converting to real + ** first. */ + sqlite3VdbeMemRealify(pVal); + } + } + *ppVal = pVal; + return rc; } #ifdef SQLITE_ENABLE_STAT4 @@ -84733,7 +87237,7 @@ static int stat4ValueFromExpr( }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){ Vdbe *v; int iBindVar = pExpr->iColumn; - sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar); + sqlite3VdbeReprepareOnBind(pParse->pVdbe, iBindVar, 0); if( (v = pParse->pReprepare)!=0 ){ pVal = valueNew(db, pAlloc); if( pVal ){ @@ -84846,6 +87350,11 @@ SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr( ** ** If *ppVal is initially NULL then the caller is responsible for ** ensuring that the value written into *ppVal is eventually freed. +** +** If the buffer does not contain a well-formed record, this routine may +** read several bytes past the end of the buffer. Callers must therefore +** ensure that any buffer which may contain a corrupt record is padded +** with at least 8 bytes of addressable memory. */ SQLITE_PRIVATE int sqlite3Stat4Column( sqlite3 *db, /* Database handle */ @@ -85033,6 +87542,7 @@ SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlag p->prepFlags = prepFlags; if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){ p->expmask = 0; + p->smimask = 0; } assert( p->zSql==0 ); p->zSql = sqlite3DbStrNDup(p->db, z, n); @@ -85106,7 +87616,8 @@ SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){ pA->zNormSql = pB->zNormSql; pB->zNormSql = zTmp; #endif - pB->expmask = pA->expmask; + pB->expmask |= pA->expmask; + pB->smimask |= pA->smimask; pB->prepFlags = pA->prepFlags; memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter)); pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++; @@ -85325,6 +87836,20 @@ SQLITE_PRIVATE int sqlite3VdbeAddOp4Int( return i; } +/* Generate an opcode that loads a 64-bit integer into register iDest +*/ +SQLITE_PRIVATE int sqlite3VdbeAddInt64(Vdbe *p, int iDest, i64 iVal){ + return sqlite3VdbeAddOp3(p, OP_Int64, LOWER32(iVal), iDest, UPPER32(iVal)); +} + +/* Generate an opcode that loads a 64-floating point value into register iDest. +*/ +SQLITE_PRIVATE int sqlite3VdbeAddDouble(Vdbe *p, int iDest, double rVal){ + i64 iVal; + memcpy(&iVal,&rVal,8); + return sqlite3VdbeAddOp3(p, OP_Real, LOWER32(iVal), iDest, UPPER32(iVal)); +} + /* Generate code for an unconditional jump to instruction iDest */ SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){ @@ -85406,12 +87931,10 @@ SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall( int eCallCtx /* Calling context */ ){ Vdbe *v = pParse->pVdbe; - int nByte; int addr; sqlite3_context *pCtx; assert( v ); - nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*); - pCtx = sqlite3DbMallocRawNN(pParse->db, nByte); + pCtx = sqlite3DbMallocRawNN(pParse->db, SZ_CONTEXT(nArg)); if( pCtx==0 ){ assert( pParse->db->mallocFailed ); freeEphemeralFunction(pParse->db, (FuncDef*)pFunc); @@ -85430,24 +87953,6 @@ SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall( return addr; } -/* -** Add an opcode that includes the p4 value with a P4_INT64 or -** P4_REAL type. -*/ -SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8( - Vdbe *p, /* Add the opcode to this VM */ - int op, /* The new opcode */ - int p1, /* The P1 operand */ - int p2, /* The P2 operand */ - int p3, /* The P3 operand */ - const u8 *zP4, /* The P4 operand */ - int p4type /* P4 operand type */ -){ - char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8); - if( p4copy ) memcpy(p4copy, zP4, 8); - return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type); -} - #ifndef SQLITE_OMIT_EXPLAIN /* ** Return the address of the current EXPLAIN QUERY PLAN baseline. @@ -85519,11 +88024,21 @@ SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse *pParse){ ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees ** as having been used. ** -** The zWhere string must have been obtained from sqlite3_malloc(). +** zWhere is a WHERE clause that defines which entries of the schema +** to reparse. If zWhere==0, that means all entries. p5 is a mask +** of INITFLAG_* values for the parse. +** +** In the current usage, the following are always true: +** +** ALTER TABLE: zWhere==0, p5!=0 +** Otherwise: zWhere!=0, p5==0 +** +** The zWhere string must have been obtained from sqlite3DbMalloc(). ** This routine will take ownership of the allocated memory. */ SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere, u16 p5){ int j; + assert( p5==0 || zWhere==0 ); sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC); sqlite3VdbeChangeP5(p, p5); for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j); @@ -85580,7 +88095,7 @@ SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse *pParse){ ** a prior call to sqlite3VdbeMakeLabel(). */ static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){ - int nNewSize = 10 - p->nLabel; + int nNewSize = 25 - p->nLabel; p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, nNewSize*sizeof(p->aLabel[0])); if( p->aLabel==0 ){ @@ -85687,7 +88202,7 @@ static Op *opIterNext(VdbeOpIter *p){ } if( pRet->p4type==P4_SUBPROGRAM ){ - int nByte = (p->nSub+1)*sizeof(SubProgram*); + i64 nByte = (1+(u64)p->nSub)*sizeof(SubProgram*); int j; for(j=0; j<p->nSub; j++){ if( p->apSub[j]==pRet->p4.pProgram ) break; @@ -85751,6 +88266,7 @@ SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){ || opcode==OP_Function || opcode==OP_PureFunc || ((opcode==OP_Halt || opcode==OP_HaltIfNull) && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort)) + || (opcode==OP_MustBeInt && pOp->p2==0) ){ hasAbort = 1; break; @@ -85817,8 +88333,8 @@ SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){ ** (1) For each jump instruction with a negative P2 value (a label) ** resolve the P2 value to an actual address. ** -** (2) Compute the maximum number of arguments used by any SQL function -** and store that value in *pMaxFuncArgs. +** (2) Compute the maximum number of arguments used by the xUpdate/xFilter +** methods of any virtual table and store that value in *pMaxVtabArgs. ** ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately ** indicate what the prepared statement actually does. @@ -85831,8 +88347,8 @@ SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){ ** script numbers the opcodes correctly. Changes to this routine must be ** coordinated with changes to mkopcodeh.tcl. */ -static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){ - int nMaxArgs = *pMaxFuncArgs; +static void resolveP2Values(Vdbe *p, int *pMaxVtabArgs){ + int nMaxVtabArgs = *pMaxVtabArgs; Op *pOp; Parse *pParse = p->pParse; int *aLabel = pParse->aLabel; @@ -85877,15 +88393,19 @@ static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){ } #ifndef SQLITE_OMIT_VIRTUALTABLE case OP_VUpdate: { - if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2; + if( pOp->p2>nMaxVtabArgs ) nMaxVtabArgs = pOp->p2; break; } case OP_VFilter: { int n; + /* The instruction immediately prior to VFilter will be an + ** OP_Integer that sets the "argc" value for the VFilter. See + ** the code where OP_VFilter is generated at tag-20250207a. */ assert( (pOp - p->aOp) >= 3 ); assert( pOp[-1].opcode==OP_Integer ); + assert( pOp[-1].p2==pOp->p3+1 ); n = pOp[-1].p1; - if( n>nMaxArgs ) nMaxArgs = n; + if( n>nMaxVtabArgs ) nMaxVtabArgs = n; /* Fall through into the default case */ /* no break */ deliberate_fall_through } @@ -85926,7 +88446,7 @@ static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){ pParse->aLabel = 0; } pParse->nLabel = 0; - *pMaxFuncArgs = nMaxArgs; + *pMaxVtabArgs = nMaxVtabArgs; assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) ); } @@ -86155,7 +88675,7 @@ SQLITE_PRIVATE void sqlite3VdbeScanStatus( const char *zName /* Name of table or index being scanned */ ){ if( IS_STMT_SCANSTATUS(p->db) ){ - sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus); + i64 nByte = (1+(i64)p->nScan) * sizeof(ScanStatus); ScanStatus *aNew; aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte); if( aNew ){ @@ -86265,6 +88785,9 @@ SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){ */ SQLITE_PRIVATE void sqlite3VdbeTypeofColumn(Vdbe *p, int iDest){ VdbeOp *pOp = sqlite3VdbeGetLastOp(p); +#ifdef SQLITE_DEBUG + while( pOp->opcode==OP_ReleaseReg ) pOp--; +#endif if( pOp->p3==iDest && pOp->opcode==OP_Column ){ pOp->p5 |= OPFLAG_TYPEOFARG; } @@ -86337,8 +88860,6 @@ static void freeP4(sqlite3 *db, int p4type, void *p4){ freeP4FuncCtx(db, (sqlite3_context*)p4); break; } - case P4_REAL: - case P4_INT64: case P4_DYNAMIC: case P4_INTARRAY: { if( p4 ) sqlite3DbNNFreeNN(db, p4); @@ -86692,6 +89213,9 @@ static int translateP(char c, const Op *pOp){ ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x +** "PINT13" -> int(P1|P3<<32) +** "PDBL13" -> real(P1|P3<<32) +** "PHEX23" -> hex(P2|P3<<32) */ SQLITE_PRIVATE char *sqlite3VdbeDisplayComment( sqlite3 *db, /* Optional - Oom error reporting only */ @@ -86727,6 +89251,20 @@ SQLITE_PRIVATE char *sqlite3VdbeDisplayComment( seenCom = 1; break; } + }else if( strncmp(&zSynopsis[ii],"INT13",5)==0 ){ + sqlite3_str_appendf(&x,"%lld",INT32_TO_64(pOp->p1,pOp->p3)); + ii += 4; +#ifdef SQLITE_ENABLE_COLUMN_USED_MASK + }else if( strncmp(&zSynopsis[ii],"HEX23",5)==0 ){ + sqlite3_str_appendf(&x,"0x%llx",INT32_TO_64(pOp->p2,pOp->p3)); + ii += 4; +#endif + }else if( strncmp(&zSynopsis[ii],"DBL13",5)==0 ){ + i64 iVal = INT32_TO_64(pOp->p1,pOp->p3); + double r; + memcpy(&r, &iVal, 8); + sqlite3_str_appendf(&x,"%.17g",r); + ii += 4; }else{ int v1 = translateP(c, pOp); int v2; @@ -86856,7 +89394,6 @@ static void displayP4Expr(StrAccum *p, Expr *pExpr){ #if VDBE_DISPLAY_P4 /* ** Compute a string that describes the P4 parameter for an opcode. -** Use zTemp for any required temporary buffer space. */ SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){ char *zP4 = 0; @@ -86905,18 +89442,10 @@ SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){ sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg); break; } - case P4_INT64: { - sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64); - break; - } case P4_INT32: { sqlite3_str_appendf(&x, "%d", pOp->p4.i); break; } - case P4_REAL: { - sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal); - break; - } case P4_MEM: { Mem *pMem = pOp->p4.pMem; if( pMem->flags & MEM_Str ){ @@ -86959,6 +89488,10 @@ SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){ zP4 = pOp->p4.pTab->zName; break; } + case P4_INDEX: { + zP4 = pOp->p4.pIdx->zName; + break; + } case P4_SUBRTNSIG: { SubrtnSig *pSig = pOp->p4.pSubrtnSig; sqlite3_str_appendf(&x, "subrtnsig:%d,%s", pSig->selId, pSig->zAff); @@ -87105,6 +89638,7 @@ SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){ ** will be initialized before use. */ static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){ + assert( db!=0 ); if( N>0 ){ do{ p->flags = flags; @@ -87112,6 +89646,7 @@ static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){ p->szMalloc = 0; #ifdef SQLITE_DEBUG p->pScopyFrom = 0; + p->bScopy = 0; #endif p++; }while( (--N)>0 ); @@ -87130,6 +89665,7 @@ static void releaseMemArray(Mem *p, int N){ if( p && N ){ Mem *pEnd = &p[N]; sqlite3 *db = p->db; + assert( db!=0 ); if( db->pnBytesFreed ){ do{ if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc); @@ -87601,7 +90137,7 @@ SQLITE_PRIVATE void sqlite3VdbeMakeReady( int nVar; /* Number of parameters */ int nMem; /* Number of VM memory registers */ int nCursor; /* Number of cursors required */ - int nArg; /* Number of arguments in subprograms */ + int nArg; /* Max number args to xFilter or xUpdate */ int n; /* Loop counter */ struct ReusableSpace x; /* Reusable bulk memory */ @@ -87610,6 +90146,7 @@ SQLITE_PRIVATE void sqlite3VdbeMakeReady( assert( pParse!=0 ); assert( p->eVdbeState==VDBE_INIT_STATE ); assert( pParse==p->pParse ); + assert( pParse->db==p->db ); p->pVList = pParse->pVList; pParse->pVList = 0; db = p->db; @@ -87634,7 +90171,7 @@ SQLITE_PRIVATE void sqlite3VdbeMakeReady( n = ROUND8P(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */ x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */ assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) ); - x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */ + x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes unused memory */ assert( x.nFree>=0 ); assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) ); @@ -87672,6 +90209,9 @@ SQLITE_PRIVATE void sqlite3VdbeMakeReady( p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*)); } } +#ifdef SQLITE_DEBUG + p->napArg = nArg; +#endif if( db->mallocFailed ){ p->nVar = 0; @@ -87850,7 +90390,7 @@ SQLITE_PRIVATE int sqlite3VdbeSetColName( } assert( p->aColName!=0 ); pColName = &(p->aColName[idx+var*p->nResAlloc]); - rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel); + rc = sqlite3VdbeMemSetText(pColName, zName, -1, xDel); assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 ); return rc; } @@ -87943,10 +90483,12 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){ - for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ - Btree *pBt = db->aDb[i].pBt; - if( pBt ){ - rc = sqlite3BtreeCommitPhaseOne(pBt, 0); + if( needXcommit ){ + for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( sqlite3BtreeTxnState(pBt)>=SQLITE_TXN_WRITE ){ + rc = sqlite3BtreeCommitPhaseOne(pBt, 0); + } } } @@ -87957,7 +90499,9 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){ */ for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ Btree *pBt = db->aDb[i].pBt; - if( pBt ){ + int txn = sqlite3BtreeTxnState(pBt); + if( txn!=SQLITE_TXN_NONE ){ + assert( needXcommit || txn==SQLITE_TXN_READ ); rc = sqlite3BtreeCommitPhaseTwo(pBt, 0); } } @@ -88212,28 +90756,31 @@ SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){ /* -** This function is called when a transaction opened by the database +** These functions are called when a transaction opened by the database ** handle associated with the VM passed as an argument is about to be -** committed. If there are outstanding deferred foreign key constraint -** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK. +** committed. If there are outstanding foreign key constraint violations +** return an error code. Otherwise, SQLITE_OK. ** ** If there are outstanding FK violations and this function returns -** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY -** and write an error message to it. Then return SQLITE_ERROR. +** non-zero, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY +** and write an error message to it. */ #ifndef SQLITE_OMIT_FOREIGN_KEY -SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){ +static SQLITE_NOINLINE int vdbeFkError(Vdbe *p){ + p->rc = SQLITE_CONSTRAINT_FOREIGNKEY; + p->errorAction = OE_Abort; + sqlite3VdbeError(p, "FOREIGN KEY constraint failed"); + if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ) return SQLITE_ERROR; + return SQLITE_CONSTRAINT_FOREIGNKEY; +} +SQLITE_PRIVATE int sqlite3VdbeCheckFkImmediate(Vdbe *p){ + if( p->nFkConstraint==0 ) return SQLITE_OK; + return vdbeFkError(p); +} +SQLITE_PRIVATE int sqlite3VdbeCheckFkDeferred(Vdbe *p){ sqlite3 *db = p->db; - if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) - || (!deferred && p->nFkConstraint>0) - ){ - p->rc = SQLITE_CONSTRAINT_FOREIGNKEY; - p->errorAction = OE_Abort; - sqlite3VdbeError(p, "FOREIGN KEY constraint failed"); - if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ) return SQLITE_ERROR; - return SQLITE_CONSTRAINT_FOREIGNKEY; - } - return SQLITE_OK; + if( (db->nDeferredCons+db->nDeferredImmCons)==0 ) return SQLITE_OK; + return vdbeFkError(p); } #endif @@ -88327,7 +90874,7 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ /* Check for immediate foreign key violations. */ if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){ - (void)sqlite3VdbeCheckFk(p, 0); + (void)sqlite3VdbeCheckFkImmediate(p); } /* If the auto-commit flag is set and this is the only active writer @@ -88341,7 +90888,7 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){ && db->nVdbeWrite==(p->readOnly==0) ){ if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){ - rc = sqlite3VdbeCheckFk(p, 1); + rc = sqlite3VdbeCheckFkDeferred(p); if( rc!=SQLITE_OK ){ if( NEVER(p->readOnly) ){ sqlite3VdbeLeave(p); @@ -88987,67 +91534,16 @@ SQLITE_PRIVATE u64 sqlite3FloatSwap(u64 in){ } #endif /* SQLITE_MIXED_ENDIAN_64BIT_FLOAT */ - -/* Input "x" is a sequence of unsigned characters that represent a -** big-endian integer. Return the equivalent native integer -*/ -#define ONE_BYTE_INT(x) ((i8)(x)[0]) -#define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1]) -#define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2]) -#define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3]) -#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3]) - /* -** Deserialize the data blob pointed to by buf as serial type serial_type -** and store the result in pMem. -** -** This function is implemented as two separate routines for performance. -** The few cases that require local variables are broken out into a separate -** routine so that in most cases the overhead of moving the stack pointer -** is avoided. +** Deserialize the REAL number pointed to by buf and store it in pMem. */ -static void serialGet( - const unsigned char *buf, /* Buffer to deserialize from */ - u32 serial_type, /* Serial type to deserialize */ - Mem *pMem /* Memory cell to write value into */ -){ - u64 x = FOUR_BYTE_UINT(buf); - u32 y = FOUR_BYTE_UINT(buf+4); - x = (x<<32) + y; - if( serial_type==6 ){ - /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit - ** twos-complement integer. */ - pMem->u.i = *(i64*)&x; - pMem->flags = MEM_Int; - testcase( pMem->u.i<0 ); - }else{ - /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit - ** floating point number. */ -#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT) - /* Verify that integers and floating point values use the same - ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is - ** defined that 64-bit floating point values really are mixed - ** endian. - */ - static const u64 t1 = ((u64)0x3ff00000)<<32; - static const double r1 = 1.0; - u64 t2 = t1; - swapMixedEndianFloat(t2); - assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 ); -#endif - assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 ); - swapMixedEndianFloat(x); - memcpy(&pMem->u.r, &x, sizeof(x)); - pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real; - } -} -static int serialGet7( +static int sqlite3VdbeSerialGet7( const unsigned char *buf, /* Buffer to deserialize from */ Mem *pMem /* Memory cell to write value into */ ){ - u64 x = FOUR_BYTE_UINT(buf); - u32 y = FOUR_BYTE_UINT(buf+4); - x = (x<<32) + y; + /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit + ** floating point number. */ + u64 x = sqlite3Get8byte(buf); assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 ); swapMixedEndianFloat(x); memcpy(&pMem->u.r, &x, sizeof(x)); @@ -89058,6 +91554,13 @@ static int serialGet7( pMem->flags = MEM_Real; return 0; } + +/* +** Deserialize the data blob pointed to by buf as serial type serial_type +** and store the result in pMem. +** +** Similar code is found in the implementation of the OP_Column opcode. +*/ SQLITE_PRIVATE void sqlite3VdbeSerialGet( const unsigned char *buf, /* Buffer to deserialize from */ u32 serial_type, /* Serial type to deserialize */ @@ -89116,16 +91619,21 @@ SQLITE_PRIVATE void sqlite3VdbeSerialGet( case 5: { /* 6-byte signed integer */ /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit ** twos-complement integer. */ - pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf); + pMem->u.i = SIX_BYTE_INT(buf); + pMem->flags = MEM_Int; + testcase( pMem->u.i<0 ); + return; + } + case 6: { /* 8-byte signed integer */ + /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit + ** twos-complement integer. */ + pMem->u.i = (i64)sqlite3Get8byte(buf); pMem->flags = MEM_Int; testcase( pMem->u.i<0 ); return; } - case 6: /* 8-byte signed integer */ case 7: { /* IEEE floating point */ - /* These use local variables, so do them in a separate routine - ** to avoid having to move the frame pointer in the common case */ - serialGet(buf,serial_type,pMem); + sqlite3VdbeSerialGet7(buf, pMem); return; } case 8: /* Integer 0 */ @@ -89151,29 +91659,22 @@ SQLITE_PRIVATE void sqlite3VdbeSerialGet( return; } /* -** This routine is used to allocate sufficient space for an UnpackedRecord -** structure large enough to be used with sqlite3VdbeRecordUnpack() if -** the first argument is a pointer to KeyInfo structure pKeyInfo. -** -** The space is either allocated using sqlite3DbMallocRaw() or from within -** the unaligned buffer passed via the second and third arguments (presumably -** stack space). If the former, then *ppFree is set to a pointer that should -** be eventually freed by the caller using sqlite3DbFree(). Or, if the -** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL -** before returning. +** Allocate sufficient space for an UnpackedRecord structure large enough +** to hold a decoded index record for pKeyInfo. ** -** If an OOM error occurs, NULL is returned. +** The space is allocated using sqlite3DbMallocRaw(). If an OOM error +** occurs, NULL is returned. */ SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord( KeyInfo *pKeyInfo /* Description of the record */ ){ UnpackedRecord *p; /* Unpacked record to return */ - int nByte; /* Number of bytes required for *p */ + u64 nByte; /* Number of bytes required for *p */ + assert( sizeof(UnpackedRecord) + sizeof(Mem)*65536 < 0x7fffffff ); nByte = ROUND8P(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1); p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte); if( !p ) return 0; p->aMem = (Mem*)&((char*)p)[ROUND8P(sizeof(UnpackedRecord))]; - assert( pKeyInfo->aSortFlags!=0 ); p->pKeyInfo = pKeyInfo; p->nField = pKeyInfo->nKeyField + 1; return p; @@ -89185,7 +91686,6 @@ SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord( ** contents of the decoded record. */ SQLITE_PRIVATE void sqlite3VdbeRecordUnpack( - KeyInfo *pKeyInfo, /* Information about the record format */ int nKey, /* Size of the binary record */ const void *pKey, /* The binary record */ UnpackedRecord *p /* Populate this structure before returning. */ @@ -89196,6 +91696,7 @@ SQLITE_PRIVATE void sqlite3VdbeRecordUnpack( u16 u; /* Unsigned loop counter */ u32 szHdr; Mem *pMem = p->aMem; + KeyInfo *pKeyInfo = p->pKeyInfo; p->default_rc = 0; assert( EIGHT_BYTE_ALIGNMENT(pMem) ); @@ -89213,16 +91714,18 @@ SQLITE_PRIVATE void sqlite3VdbeRecordUnpack( pMem->z = 0; sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem); d += sqlite3VdbeSerialTypeLen(serial_type); - pMem++; if( (++u)>=p->nField ) break; + pMem++; } if( d>(u32)nKey && u ){ assert( CORRUPT_DB ); /* In a corrupt record entry, the last pMem might have been set up using ** uninitialized memory. Overwrite its value with NULL, to prevent ** warnings from MSAN. */ - sqlite3VdbeMemSetNull(pMem-1); + sqlite3VdbeMemSetNull(pMem-(u<p->nField)); } + testcase( u == pKeyInfo->nKeyField + 1 ); + testcase( u < pKeyInfo->nKeyField + 1 ); assert( u<=pKeyInfo->nKeyField + 1 ); p->nField = u; } @@ -89390,6 +91893,32 @@ static void vdbeAssertFieldCountWithinLimits( ** or positive value if *pMem1 is less than, equal to or greater than ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);". */ +static SQLITE_NOINLINE int vdbeCompareMemStringWithEncodingChange( + const Mem *pMem1, + const Mem *pMem2, + const CollSeq *pColl, + u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */ +){ + int rc; + const void *v1, *v2; + Mem c1; + Mem c2; + sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null); + sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null); + sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem); + sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem); + v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc); + v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc); + if( (v1==0 || v2==0) ){ + if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT; + rc = 0; + }else{ + rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2); + } + sqlite3VdbeMemReleaseMalloc(&c1); + sqlite3VdbeMemReleaseMalloc(&c2); + return rc; +} static int vdbeCompareMemString( const Mem *pMem1, const Mem *pMem2, @@ -89401,25 +91930,7 @@ static int vdbeCompareMemString( ** comparison function directly */ return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z); }else{ - int rc; - const void *v1, *v2; - Mem c1; - Mem c2; - sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null); - sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null); - sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem); - sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem); - v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc); - v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc); - if( (v1==0 || v2==0) ){ - if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT; - rc = 0; - }else{ - rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2); - } - sqlite3VdbeMemReleaseMalloc(&c1); - sqlite3VdbeMemReleaseMalloc(&c2); - return rc; + return vdbeCompareMemStringWithEncodingChange(pMem1,pMem2,pColl,prcErr); } } @@ -89728,7 +92239,7 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( }else if( serial_type==0 ){ rc = -1; }else if( serial_type==7 ){ - serialGet7(&aKey1[d1], &mem1); + sqlite3VdbeSerialGet7(&aKey1[d1], &mem1); rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r); }else{ i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]); @@ -89754,7 +92265,7 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( rc = -1; }else{ if( serial_type==7 ){ - if( serialGet7(&aKey1[d1], &mem1) ){ + if( sqlite3VdbeSerialGet7(&aKey1[d1], &mem1) ){ rc = -1; /* mem1 is a NaN */ }else if( mem1.u.r<pRhs->u.r ){ rc = -1; @@ -89836,7 +92347,7 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip( serial_type = aKey1[idx1]; if( serial_type==0 || serial_type==10 - || (serial_type==7 && serialGet7(&aKey1[d1], &mem1)!=0) + || (serial_type==7 && sqlite3VdbeSerialGet7(&aKey1[d1], &mem1)!=0) ){ assert( rc==0 ); }else{ @@ -89910,65 +92421,42 @@ static int vdbeRecordCompareInt( const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F]; int serial_type = ((const u8*)pKey1)[1]; int res; - u32 y; - u64 x; i64 v; i64 lhs; vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo); assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB ); - switch( serial_type ){ - case 1: { /* 1-byte signed integer */ - lhs = ONE_BYTE_INT(aKey); - testcase( lhs<0 ); - break; - } - case 2: { /* 2-byte signed integer */ - lhs = TWO_BYTE_INT(aKey); - testcase( lhs<0 ); - break; - } - case 3: { /* 3-byte signed integer */ - lhs = THREE_BYTE_INT(aKey); - testcase( lhs<0 ); - break; - } - case 4: { /* 4-byte signed integer */ - y = FOUR_BYTE_UINT(aKey); - lhs = (i64)*(int*)&y; - testcase( lhs<0 ); - break; - } - case 5: { /* 6-byte signed integer */ - lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey); - testcase( lhs<0 ); - break; - } - case 6: { /* 8-byte signed integer */ - x = FOUR_BYTE_UINT(aKey); - x = (x<<32) | FOUR_BYTE_UINT(aKey+4); - lhs = *(i64*)&x; - testcase( lhs<0 ); - break; - } - case 8: - lhs = 0; - break; - case 9: - lhs = 1; - break; - - /* This case could be removed without changing the results of running - ** this code. Including it causes gcc to generate a faster switch - ** statement (since the range of switch targets now starts at zero and - ** is contiguous) but does not cause any duplicate code to be generated - ** (as gcc is clever enough to combine the two like cases). Other - ** compilers might be similar. */ - case 0: case 7: - return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2); - default: - return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2); + /* Serial types 1 through 6 are big-endian integers of 1, 2, 3, 4, + ** 6, or 8 bytes. Rather than handle each width in its own switch + ** case, read 8 bytes and use an arithmetic right shift to drop the + ** unwanted low-order bytes and sign-extend the value. This helps + ** because the switch tends to mispredict when a key column contains + ** integers of varying sizes. The first entry of aShift[] is a + ** placeholder so that the table can be indexed by serial_type + ** directly. Reading 8 bytes is always safe, because a buffer passed + ** to this routine has at least 74 bytes of padding after it, as + ** explained in sqlite3VdbeFindCompare() below. + */ + if( (u32)(serial_type-1)<=5 ){ + static const u8 aShift[] = { 0, 56, 48, 40, 32, 16, 0 }; + lhs = ((i64)sqlite3Get8byte(aKey)) >> aShift[serial_type]; + /* ^^--- This shift operator + ** needs to be an arithmetic right-shift, which means that + ** if the left-hand operand (LHS) is negative, it will be sign-extended + ** so that the final results is also negative. All modern C + ** compilers work this way as long as the LHS is a signed integer + ** (which is why the unsigned result from sqlite3Get8byte() is cast + ** into i64), but it is not defined by the C standards, or so Claude + ** tells me. That the correct result is obtained is verified by the + ** following assert() and testcase() macros: + */ + assert( 0<=(i64)sqlite3Get8byte(aKey) || lhs<0 ); + testcase( lhs<0 ); + }else if( serial_type==8 || serial_type==9 ){ + lhs = serial_type - 8; + }else{ + return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2); } assert( pPKey2->u.i == pPKey2->aMem[0].u.i ); @@ -90082,6 +92570,7 @@ SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){ ** The easiest way to enforce this limit is to consider only records with ** 13 fields or less. If the first field is an integer, the maximum legal ** header size is (12*5 + 1 + 1) bytes. */ + assert( p->pKeyInfo->aSortFlags!=0 ); if( p->pKeyInfo->nAllField<=13 ){ int flags = p->aMem[0].flags; if( p->pKeyInfo->aSortFlags[0] ){ @@ -90102,7 +92591,7 @@ SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){ testcase( flags & MEM_Null ); testcase( flags & MEM_Blob ); if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0 - && p->pKeyInfo->aColl[0]==0 + && sqlite3IsBinary(p->pKeyInfo->aColl[0]) ){ assert( flags & MEM_Str ); p->u.z = p->aMem[0].z; @@ -90318,19 +92807,250 @@ SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff /* ** Configure SQL variable iVar so that binding a new value to it signals ** to sqlite3_reoptimize() that re-preparing the statement may result -** in a better query plan. +** in a better query plan. If parameter bSmallint is true, then the +** statement is only re-prepared if the new value is integer value 0 or 1. +** +** The v->expmask bit is always set. expmask means that a reprepare is +** possible. The v->smimask bit is only set if we want to restrict +** reprepare when the value changes from (0,1) to something else, or from +** something else to (0,1). */ -SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){ +SQLITE_PRIVATE void sqlite3VdbeReprepareOnBind(Vdbe *v, int iVar, int bSmallint){ + u32 m; assert( iVar>0 ); assert( (v->db->flags & SQLITE_EnableQPSG)==0 || (v->db->mDbFlags & DBFLAG_InternalFunc)!=0 ); - if( iVar>=32 ){ - v->expmask |= 0x80000000; + + m = (iVar>=32) ? 0x80000000 : ((u32)1 << (iVar-1)); + if( bSmallint ){ + if( (v->expmask & m)==0 ) v->smimask |= m; }else{ - v->expmask |= ((u32)1 << (iVar-1)); + v->smimask &= ~m; } + v->expmask |= m; + + /* smimask is always a subset of expmask */ + assert( (v->smimask & v->expmask) == v->smimask ); } +/* +** Helper function for vdbeIsMatchingIndexKey(). Return true if column +** iCol should be ignored when comparing a record with a record from +** an index on disk. The field should be ignored if: +** +** * the corresponding bit in mask is set, and +** * either: +** - bIntegrity is false, or +** - the two Mem values are both real values that differ by +** BTREE_ULPDISTORTION or fewer ULPs. +*/ +static int vdbeSkipField( + Bitmask mask, /* Mask of indexed expression fields */ + int iCol, /* Column of index being considered */ + Mem *pMem1, /* Expected index value */ + Mem *pMem2, /* Actual indexed value */ + int bIntegrity /* True if running PRAGMA integrity_check */ +){ +#define BTREE_ULPDISTORTION 2 + if( iCol>=BMS || (mask & MASKBIT(iCol))==0 ) return 0; + if( bIntegrity==0 ) return 1; + if( (pMem1->flags & MEM_Real) && (pMem2->flags & MEM_Real) ){ + u64 m1, m2; + memcpy(&m1,&pMem1->u.r,8); + memcpy(&m2,&pMem2->u.r,8); + if( (m1<m2 ? m2-m1 : m1-m2) <= BTREE_ULPDISTORTION ){ + return 1; + } + } + return 0; +} + +/* +** This function compares the unpacked record with the current key that +** cursor pCur points to. If bInt is false, all fields for which the +** corresponding bit in parameter "mask" is set are ignored. Or, if +** bInt is true, then a difference of BTREE_ULPDISTORTION or fewer ULPs +** in real values is overlooked for fields with the corresponding bit +** set in mask. +** +** Return the usual less than zero, zero, or greater than zero if the +** remaining fields of the cursor cursor key are less than, equal to or +** greater than those in (*p). +*/ +static int vdbeIsMatchingIndexKey( + BtCursor *pCur, /* Cursor open on index */ + int bInt, /* True for integrity_check-style search */ + Bitmask mask, /* Mask of columns to skip */ + UnpackedRecord *p, /* Index key being deleted */ + int *piRes /* 0 for a match, non-zero for not a match */ +){ + u8 *aRec = 0; + u32 nRec = 0; + Mem m; + int rc = SQLITE_OK; + + memset(&m, 0, sizeof(m)); + m.enc = p->pKeyInfo->enc; + m.db = p->pKeyInfo->db; + nRec = sqlite3BtreePayloadSize(pCur); + if( nRec>0x7fffffff ){ + return SQLITE_CORRUPT_BKPT; + } + + /* Allocate 5 extra bytes at the end of the buffer. This allows the + ** getVarint32() call below to read slightly past the end of the buffer + ** if the record is corrupt. */ + aRec = sqlite3MallocZero(nRec+5); + if( aRec==0 ){ + rc = SQLITE_NOMEM_BKPT; + }else{ + rc = sqlite3BtreePayload(pCur, 0, nRec, aRec); + } + + if( rc==SQLITE_OK ){ + u32 szHdr = 0; /* Size of record header in bytes */ + u32 idxHdr = 0; /* Current index in header */ + + idxHdr = getVarint32(aRec, szHdr); + if( szHdr>98307 ){ + rc = SQLITE_CORRUPT; + }else{ + int res = 0; /* Result of this function call */ + u32 idxRec = szHdr; /* Index of next field in record body */ + int ii = 0; /* Iterator variable */ + + int nCol = p->pKeyInfo->nAllField; + for(ii=0; ii<nCol && rc==SQLITE_OK; ii++){ + u32 iSerial = 0; + int nSerial = 0; + + if( idxHdr>=szHdr ){ + rc = SQLITE_CORRUPT_BKPT; + break; + } + idxHdr += getVarint32(&aRec[idxHdr], iSerial); + nSerial = sqlite3VdbeSerialTypeLen(iSerial); + if( (idxRec+nSerial)>nRec ){ + rc = SQLITE_CORRUPT_BKPT; + }else{ + sqlite3VdbeSerialGet(&aRec[idxRec], iSerial, &m); + if( vdbeSkipField(mask, ii, &p->aMem[ii], &m, bInt)==0 ){ + res = sqlite3MemCompare(&m, &p->aMem[ii], p->pKeyInfo->aColl[ii]); + if( res!=0 ) break; + } + } + idxRec += sqlite3VdbeSerialTypeLen(iSerial); + } + + *piRes = res; + } + } + + sqlite3_free(aRec); + return rc; +} + +/* +** This is called when the record in (*p) should be found in the index +** opened by cursor pCur, but was not. This may happen as part of a DELETE +** operation or an integrity check. +** +** One reason that an exact match was not found may be the EIIB bug - that +** a text-to-float conversion may have caused a real value in record (*p) +** to be slightly different from its counterpart on disk. This function +** attempts to find the right index record. If it does find the right +** record, it leaves *pCur pointing to it and sets (*pRes) to 0 before +** returning. Otherwise, (*pRes) is set to non-zero and an SQLite error +** code returned. +** +** The algorithm used to find the correct record is: +** +** * Scan up to BTREE_FDK_RANGE entries either side of the current entry. +** If parameter bIntegrity is false, then all fields that are indexed +** expressions or virtual table columns are omitted from the comparison. +** If bIntegrity is true, then small differences in real values in +** such fields are overlooked, but they are not omitted from the comparison +** altogether. +** +** * If the above fails to find an entry and bIntegrity is false, search +** the entire index. +*/ +SQLITE_PRIVATE int sqlite3VdbeFindIndexKey( + BtCursor *pCur, + Index *pIdx, + UnpackedRecord *p, + int *pRes, + int bIntegrity +){ +#define BTREE_FDK_RANGE 10 + int nStep = 0; + int res = 1; + int rc = SQLITE_OK; + int ii = 0; + + /* Calculate a mask based on the first 64 columns of the index. The mask + ** bit is set if the corresponding index field is either an expression + ** or a virtual column of the table. */ + Bitmask mask = 0; + for(ii=0; ii<MIN(pIdx->nColumn, BMS); ii++){ + int iCol = pIdx->aiColumn[ii]; + if( (iCol==XN_EXPR) + || (iCol>=0 && (pIdx->pTable->aCol[iCol].colFlags & COLFLAG_VIRTUAL)) + ){ + mask |= MASKBIT(ii); + } + } + + /* If the mask is 0 at this point, then the index contains no expressions + ** or virtual columns. So do not search for a match - return so that the + ** caller may declare the db corrupt immediately. Or, if mask is non-zero, + ** proceed. */ + if( mask!=0 ){ + + /* Move the cursor back BTREE_FDK_RANGE entries. If this hits an EOF, + ** position the cursor at the first entry in the index and set nStep + ** to -1 so that the first loop below scans the entire index. Otherwise, + ** set nStep to BTREE_FDK_RANGE*2 so that the first loop below scans + ** just that many entries. */ + for(ii=0; sqlite3BtreeEof(pCur)==0 && ii<BTREE_FDK_RANGE; ii++){ + rc = sqlite3BtreePrevious(pCur, 0); + } + if( rc==SQLITE_DONE ){ + rc = sqlite3BtreeFirst(pCur, &res); + nStep = -1; + }else{ + nStep = BTREE_FDK_RANGE*2; + } + + /* This loop runs at most twice to search for a key with matching PK + ** fields in the index. The second iteration always searches the entire + ** index. The first iteration searches nStep entries starting with the + ** current cursor entry if (nStep>=0), or the entire index if (nStep<0). */ + while( sqlite3BtreeCursorIsValidNN(pCur) ){ + for(ii=0; rc==SQLITE_OK && (ii<nStep || nStep<0); ii++){ + rc = vdbeIsMatchingIndexKey(pCur, bIntegrity, mask, p, &res); + if( res==0 || rc!=SQLITE_OK ) break; + rc = sqlite3BtreeNext(pCur, 0); + } + if( rc==SQLITE_DONE ){ + rc = SQLITE_OK; + assert( res!=0 ); + } + if( nStep<0 || rc!=SQLITE_OK || res==0 || bIntegrity ) break; + + /* The first, non-exhaustive, search failed to find an entry with + ** matching PK fields. So restart for an exhaustive search of the + ** entire index. */ + nStep = -1; + rc = sqlite3BtreeFirst(pCur, &res); + } + } + + *pRes = res; + return rc; +} + +#ifndef SQLITE_OMIT_DATETIME_FUNCS /* ** Cause a function to throw an error if it was call from OP_PureFunc ** rather than OP_Function. @@ -90364,6 +93084,7 @@ SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){ } return 1; } +#endif /* SQLITE_OMIT_DATETIME_FUNCS */ #if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG) /* @@ -90440,7 +93161,6 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( i64 iKey2; PreUpdate preupdate; const char *zTbl = pTab->zName; - static const u8 fakeSortOrder = 0; #ifdef SQLITE_DEBUG int nRealCol; if( pTab->tabFlags & TF_WithoutRowid ){ @@ -90475,10 +93195,11 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( preupdate.pCsr = pCsr; preupdate.op = op; preupdate.iNewReg = iReg; - preupdate.keyinfo.db = db; - preupdate.keyinfo.enc = ENC(db); - preupdate.keyinfo.nKeyField = pTab->nCol; - preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder; + preupdate.pKeyinfo = (KeyInfo*)&preupdate.uKey; + preupdate.pKeyinfo->db = db; + preupdate.pKeyinfo->enc = ENC(db); + preupdate.pKeyinfo->nKeyField = pTab->nCol; + preupdate.pKeyinfo->aSortFlags = 0; /* Indicate .aColl, .nAllField uninit */ preupdate.iKey1 = iKey1; preupdate.iKey2 = iKey2; preupdate.pTab = pTab; @@ -90488,8 +93209,9 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2); db->pPreUpdate = 0; sqlite3DbFree(db, preupdate.aRecord); - vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked); - vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked); + vdbeFreeUnpacked(db, preupdate.pKeyinfo->nKeyField+1,preupdate.pUnpacked); + vdbeFreeUnpacked(db, preupdate.pKeyinfo->nKeyField+1,preupdate.pNewUnpacked); + sqlite3VdbeMemRelease(&preupdate.oldipk); if( preupdate.aNew ){ int i; for(i=0; i<pCsr->nField; i++){ @@ -90507,6 +93229,17 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ +#ifdef SQLITE_ENABLE_PERCENTILE +/* +** Return the name of an SQL function associated with the sqlite3_context. +*/ +SQLITE_PRIVATE const char *sqlite3VdbeFuncName(const sqlite3_context *pCtx){ + assert( pCtx!=0 ); + assert( pCtx->pFunc!=0 ); + return pCtx->pFunc->zName; +} +#endif /* SQLITE_ENABLE_PERCENTILE */ + /************** End of vdbeaux.c *********************************************/ /************** Begin file vdbeapi.c *****************************************/ /* @@ -90538,8 +93271,14 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook( ** added or changed. */ SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){ - Vdbe *p = (Vdbe*)pStmt; - return p==0 || p->expired; + int iRet = 1; + if( pStmt ){ + Vdbe *p = (Vdbe*)pStmt; + sqlite3_mutex_enter(p->db->mutex); + iRet = p->expired; + sqlite3_mutex_leave(p->db->mutex); + } + return iRet; } #endif @@ -90574,7 +93313,6 @@ static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){ sqlite3_int64 iNow; sqlite3_int64 iElapse; assert( p->startTime>0 ); - assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 ); assert( db->init.busy==0 ); assert( p->zSql!=0 ); sqlite3OsCurrentTimeInt64(db->pVfs, &iNow); @@ -90886,15 +93624,18 @@ SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){ /**************************** sqlite3_result_ ******************************* -** The following routines are used by user-defined functions to specify -** the function result. +** The following routines are used by application-defined SQL functions to +** specify the function return value. There are many variations on +** sqlite3_result_xxxx() for different types of return values. ** -** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the -** result as a string or blob. Appropriate errors are set if the string/blob -** is too big or if an OOM occurs. +** The setStrOrError() function is a helper function that invokes +** sqlite3VdbeMemSetStr() to store the result as a string or blob. +** Appropriate errors are set if the string/blob is too big or if +** an OOM occurs. ** -** The invokeValueDestructor(P,X) routine invokes destructor function X() -** on value P if P is not going to be used and need to be destroyed. +** The invokeValueDestructor(P,X) helper function invokes the destructor +** function X() on value P if P is not going to be used and need to +** be destroyed. */ static void setResultStrOrError( sqlite3_context *pCtx, /* Function context */ @@ -90904,7 +93645,23 @@ static void setResultStrOrError( void (*xDel)(void*) /* Destructor function */ ){ Mem *pOut = pCtx->pOut; - int rc = sqlite3VdbeMemSetStr(pOut, z, n, enc, xDel); + int rc; + if( enc==SQLITE_UTF8 ){ + rc = sqlite3VdbeMemSetText(pOut, z, n, xDel); + }else if( enc==SQLITE_UTF8_ZT ){ + /* It is usually considered improper to assert() on an input. However, + ** the following assert() is checking for inputs that are documented + ** to result in undefined behavior. */ + assert( z==0 + || n<0 + || n>pOut->db->aLimit[SQLITE_LIMIT_LENGTH] + || z[n]==0 + ); + rc = sqlite3VdbeMemSetText(pOut, z, n, xDel); + pOut->flags |= MEM_Term; + }else{ + rc = sqlite3VdbeMemSetStr(pOut, z, n, enc, xDel); + } if( rc ){ if( rc==SQLITE_TOOBIG ){ sqlite3_result_error_toobig(pCtx); @@ -91097,7 +93854,7 @@ SQLITE_API void sqlite3_result_text64( #endif assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); assert( xDel!=SQLITE_DYNAMIC ); - if( enc!=SQLITE_UTF8 ){ + if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF8_ZT ){ if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE; n &= ~(u64)1; } @@ -91191,7 +93948,7 @@ SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){ } } -/* Force an SQLITE_TOOBIG error. */ +/* Cause the SQL function to raise an SQLITE_TOOBIG error. */ SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){ #ifdef SQLITE_ENABLE_API_ARMOR if( pCtx==0 ) return; @@ -91202,7 +93959,7 @@ SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){ SQLITE_UTF8, SQLITE_STATIC); } -/* An SQLITE_NOMEM error. */ +/* Cause the SQL function to raise an SQLITE_NOMEM error. */ SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){ #ifdef SQLITE_ENABLE_API_ARMOR if( pCtx==0 ) return; @@ -91213,6 +93970,64 @@ SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){ sqlite3OomFault(pCtx->pOut->db); } +/* Make the return value of the SQL function or virtual table pCtx +** be the content of the sqlite3_str object pStr. The eOwn flag +** determines ownership of the sqlite3_str object and its content. +** +** eOwn Ownership transfer +** ------------- ------------------------------------------------ +** +** SQLITE_COPY The SQL function returns a copy the sqlite3_str +** content and leaves the sqlite3_str object itself +** unchanged. +** +** SQLITE_XFER The content of the sqlite3_str is transferred to +** the SQL function and the SQL function takes +** responsibility for freeing that content when it is +** no longer needed. The sqlite3_str object is reset +** to an empty string. +** +** SQLITE_FINISH Like SQLITE_XFER except that the pStr is also +** freed using sqlite3_str_free(). +*/ +SQLITE_API void sqlite3_result_str(sqlite3_context *pCtx, sqlite3_str *pStr, int eOwn){ +#ifdef SQLITE_ENABLE_API_ARMOR + if( pCtx==0 ) return; + if( pStr==0 ) return; +#endif + testcase( pStr==(sqlite3_str*)&sqlite3OomStr ); + if( pStr->accError==0 ){ + if( pStr->nChar==0 ){ + setResultStrOrError(pCtx, "", 0, SQLITE_UTF8_ZT, SQLITE_STATIC); + sqlite3_str_reset(pStr); + }else{ + const char *zText = sqlite3_str_value(pStr); + /* Only internal code has the ability to capture a pointer to + ** an sqlite3_str object that uses static buffer. And none of + ** those internal use cases every invoke the sqlite3_result_str() + ** interface on a static-buffer sqlite3_str. Should this change + ** in the future, the following assert() will let us know. */ + assert( isMalloced(pStr) ); + if( eOwn==SQLITE_COPY ){ + setResultStrOrError(pCtx, zText, pStr->nChar, + SQLITE_UTF8, SQLITE_TRANSIENT); + }else{ + setResultStrOrError(pCtx, zText, pStr->nChar, + SQLITE_UTF8_ZT, SQLITE_DYNAMIC); + sqlite3StrAccumInit(pStr, pStr->db, 0, 0, pStr->mxAlloc); + } + } + }else if( pStr->accError==SQLITE_NOMEM ){ + sqlite3_result_error_nomem(pCtx); + }else{ + assert( pStr->accError==SQLITE_TOOBIG ); + sqlite3_result_error_toobig(pCtx); + } + if( eOwn==SQLITE_FINISH ){ + sqlite3_str_free(pStr); + } +} + #ifndef SQLITE_UNTESTABLE /* Force the INT64 value currently stored as the result to be ** a MEM_IntReal value. See the SQLITE_TESTCTRL_RESULT_INTREAL @@ -91248,6 +94063,8 @@ static int doWalCallbacks(sqlite3 *db){ } } } +#else + UNUSED_PARAMETER(db); #endif return rc; } @@ -91294,7 +94111,7 @@ static int sqlite3Step(Vdbe *p){ } assert( db->nVdbeWrite>0 || db->autoCommit==0 - || (db->nDeferredCons==0 && db->nDeferredImmCons==0) + || ((db->nDeferredCons + db->nDeferredImmCons)==0) ); #ifndef SQLITE_OMIT_TRACE @@ -91555,7 +94372,7 @@ static int valueFromValueList( Mem sMem; /* Raw content of current row */ memset(&sMem, 0, sizeof(sMem)); sz = sqlite3BtreePayloadSize(pRhs->pCsr); - rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,(int)sz,&sMem); + rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,sz,&sMem); if( rc==SQLITE_OK ){ u8 *zBuf = (u8*)sMem.z; u32 iSerial; @@ -91805,6 +94622,7 @@ static const Mem *columnNullValue(void){ #ifdef SQLITE_DEBUG /* .pScopyFrom = */ (Mem*)0, /* .mScopyFlags= */ 0, + /* .bScopy = */ 0, #endif }; return &nullMem; @@ -91846,7 +94664,7 @@ static Mem *columnMem(sqlite3_stmt *pStmt, int i){ ** sqlite3_column_int64() ** sqlite3_column_text() ** sqlite3_column_text16() -** sqlite3_column_real() +** sqlite3_column_double() ** sqlite3_column_bytes() ** sqlite3_column_bytes16() ** sqlite3_column_blob() @@ -92162,10 +94980,8 @@ static int vdbeUnbind(Vdbe *p, unsigned int i){ sqlite3_mutex_leave(p->db->mutex); return SQLITE_RANGE; } + pVar = &p->aVar[i]; - sqlite3VdbeMemRelease(pVar); - pVar->flags = MEM_Null; - p->db->errCode = SQLITE_OK; /* If the bit corresponding to this variable in Vdbe.expmask is set, then ** binding a new value to this variable invalidates the current query plan. @@ -92177,9 +94993,22 @@ static int vdbeUnbind(Vdbe *p, unsigned int i){ ** following any change to the bindings of that parameter. */ assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 ); + assert( (p->expmask & p->smimask)==p->smimask ); if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){ - p->expired = 1; + /* If the p->smimask bit is also set, then only expire the statement if + ** the value being clobbered was integer value 0 or 1. */ + if( (p->smimask==0) + || (p->smimask & (i>=31 ? 0x80000000 : (u32)1<<i))==0 + || ((pVar->flags & MEM_Int)!=0 && pVar->u.i>=0 && pVar->u.i<=1) + ){ + p->expired = 1; + } } + + sqlite3VdbeMemRelease(pVar); + pVar->flags = MEM_Null; + p->db->errCode = SQLITE_OK; + return SQLITE_OK; } @@ -92203,7 +95032,23 @@ static int bindText( assert( p!=0 && p->aVar!=0 && i>0 && i<=p->nVar ); /* tag-20240917-01 */ if( zData!=0 ){ pVar = &p->aVar[i-1]; - rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel); + if( encoding==SQLITE_UTF8 ){ + rc = sqlite3VdbeMemSetText(pVar, zData, nData, xDel); + }else if( encoding==SQLITE_UTF8_ZT ){ + /* It is usually consider improper to assert() on an input. + ** However, the following assert() is checking for inputs + ** that are documented to result in undefined behavior. */ + assert( zData==0 + || nData<0 + || nData>pVar->db->aLimit[SQLITE_LIMIT_LENGTH] + || ((u8*)zData)[nData]==0 + ); + rc = sqlite3VdbeMemSetText(pVar, zData, nData, xDel); + pVar->flags |= MEM_Term; + }else{ + rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel); + if( encoding==0 ) pVar->enc = ENC(p->db); + } if( rc==SQLITE_OK && encoding!=0 ){ rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db)); } @@ -92260,15 +95105,46 @@ SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){ return sqlite3_bind_int64(p, i, (i64)iValue); } SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){ - int rc; - Vdbe *p = (Vdbe *)pStmt; - rc = vdbeUnbind(p, (u32)(i-1)); - if( rc==SQLITE_OK ){ - assert( p!=0 && p->aVar!=0 && i>0 && i<=p->nVar ); /* tag-20240917-01 */ - sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue); + Mem *pVar; + Vdbe *p = (Vdbe*)pStmt; + if( vdbeSafetyNotNull(p) ){ + return SQLITE_MISUSE_BKPT; + } + sqlite3_mutex_enter(p->db->mutex); + if( p->eVdbeState!=VDBE_READY_STATE ){ + sqlite3Error(p->db, SQLITE_MISUSE_BKPT); sqlite3_mutex_leave(p->db->mutex); + sqlite3_log(SQLITE_MISUSE, + "bind on a busy prepared statement: [%s]", p->zSql); + return SQLITE_MISUSE_BKPT; } - return rc; + if( i<=0 || (--i)>=p->nVar ){ + sqlite3Error(p->db, SQLITE_RANGE); + sqlite3_mutex_leave(p->db->mutex); + return SQLITE_RANGE; + } + pVar = &p->aVar[i]; + if( p->expmask!=0 ){ + u32 expireMask = i>=32 ? 0x80000000 : (u32)1 << i; + assert( (p->expmask & p->smimask)==p->smimask ); + if( (p->expmask & expireMask)!=0 ){ + if( (p->smimask & expireMask)!=0 ){ + /* If the smimask bit is set, only expire the prepared statement + ** if the value is changing to or from (0,1) and something else */ + int sm1 = (pVar->flags & MEM_Int)!=0 && pVar->u.i>=0 && pVar->u.i<=1; + int sm2 = iValue>=0 && iValue<=1; + if( sm1!=sm2 ){ + p->expired = 1; + } + }else if( (pVar->flags & MEM_Int)==0 || iValue!=pVar->u.i ){ + /* Always expire if the smimask bit is clear */ + p->expired = 1; + } + } + } + sqlite3VdbeMemSetInt64(pVar, iValue); + sqlite3_mutex_leave(p->db->mutex); + return SQLITE_OK; } SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){ int rc; @@ -92317,9 +95193,9 @@ SQLITE_API int sqlite3_bind_text64( unsigned char enc ){ assert( xDel!=SQLITE_DYNAMIC ); - if( enc!=SQLITE_UTF8 ){ + if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF8_ZT ){ if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE; - nData &= ~(u16)1; + nData &= ~(u64)1; } return bindText(pStmt, i, zData, nData, xDel, enc); } @@ -92674,7 +95550,7 @@ static UnpackedRecord *vdbeUnpackRecord( pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo); if( pRet ){ memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1)); - sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet); + sqlite3VdbeRecordUnpack(nKey, pKey, pRet); } return pRet; } @@ -92687,6 +95563,7 @@ SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppVa PreUpdate *p; Mem *pMem; int rc = SQLITE_OK; + int iStore = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( db==0 || ppValue==0 ){ @@ -92701,67 +95578,78 @@ SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppVa goto preupdate_old_out; } if( p->pPk ){ - iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx); + iStore = sqlite3TableColumnToIndex(p->pPk, iIdx); + }else if( iIdx >= p->pTab->nCol ){ + rc = SQLITE_MISUSE_BKPT; + goto preupdate_old_out; + }else{ + iStore = sqlite3TableColumnToStorage(p->pTab, iIdx); } - if( iIdx>=p->pCsr->nField || iIdx<0 ){ + if( iStore>=p->pCsr->nField || iStore<0 ){ rc = SQLITE_RANGE; goto preupdate_old_out; } - /* If the old.* record has not yet been loaded into memory, do so now. */ - if( p->pUnpacked==0 ){ - u32 nRec; - u8 *aRec; + if( iIdx==p->pTab->iPKey ){ + *ppValue = pMem = &p->oldipk; + sqlite3VdbeMemSetInt64(pMem, p->iKey1); + }else{ - assert( p->pCsr->eCurType==CURTYPE_BTREE ); - nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor); - aRec = sqlite3DbMallocRaw(db, nRec); - if( !aRec ) goto preupdate_old_out; - rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec); - if( rc==SQLITE_OK ){ - p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec); - if( !p->pUnpacked ) rc = SQLITE_NOMEM; - } - if( rc!=SQLITE_OK ){ - sqlite3DbFree(db, aRec); - goto preupdate_old_out; + /* If the old.* record has not yet been loaded into memory, do so now. */ + if( p->pUnpacked==0 ){ + u32 nRec; + u8 *aRec; + + assert( p->pCsr->eCurType==CURTYPE_BTREE ); + nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor); + aRec = sqlite3DbMallocRaw(db, nRec); + if( !aRec ) goto preupdate_old_out; + rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec); + if( rc==SQLITE_OK ){ + p->pUnpacked = vdbeUnpackRecord(p->pKeyinfo, nRec, aRec); + if( !p->pUnpacked ) rc = SQLITE_NOMEM; + } + if( rc!=SQLITE_OK ){ + sqlite3DbFree(db, aRec); + goto preupdate_old_out; + } + p->aRecord = aRec; } - p->aRecord = aRec; - } - pMem = *ppValue = &p->pUnpacked->aMem[iIdx]; - if( iIdx==p->pTab->iPKey ){ - sqlite3VdbeMemSetInt64(pMem, p->iKey1); - }else if( iIdx>=p->pUnpacked->nField ){ - /* This occurs when the table has been extended using ALTER TABLE - ** ADD COLUMN. The value to return is the default value of the column. */ - Column *pCol = &p->pTab->aCol[iIdx]; - if( pCol->iDflt>0 ){ - if( p->apDflt==0 ){ - int nByte = sizeof(sqlite3_value*)*p->pTab->nCol; - p->apDflt = (sqlite3_value**)sqlite3DbMallocZero(db, nByte); - if( p->apDflt==0 ) goto preupdate_old_out; - } - if( p->apDflt[iIdx]==0 ){ - sqlite3_value *pVal = 0; - Expr *pDflt; - assert( p->pTab!=0 && IsOrdinaryTable(p->pTab) ); - pDflt = p->pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr; - rc = sqlite3ValueFromExpr(db, pDflt, ENC(db), pCol->affinity, &pVal); - if( rc==SQLITE_OK && pVal==0 ){ - rc = SQLITE_CORRUPT_BKPT; + pMem = *ppValue = &p->pUnpacked->aMem[iStore]; + if( iStore>=p->pUnpacked->nField ){ + /* This occurs when the table has been extended using ALTER TABLE + ** ADD COLUMN. The value to return is the default value of the column. */ + Column *pCol = &p->pTab->aCol[iIdx]; + if( pCol->iDflt>0 ){ + if( p->apDflt==0 ){ + int nByte; + assert( sizeof(sqlite3_value*)*UMXV(p->pTab->nCol) < 0x7fffffff ); + nByte = sizeof(sqlite3_value*)*p->pTab->nCol; + p->apDflt = (sqlite3_value**)sqlite3DbMallocZero(db, nByte); + if( p->apDflt==0 ) goto preupdate_old_out; + } + if( p->apDflt[iIdx]==0 ){ + sqlite3_value *pVal = 0; + Expr *pDflt; + assert( p->pTab!=0 && IsOrdinaryTable(p->pTab) ); + pDflt = p->pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr; + rc = sqlite3ValueFromExpr(db, pDflt, ENC(db), pCol->affinity, &pVal); + if( rc==SQLITE_OK && pVal==0 ){ + rc = SQLITE_CORRUPT_BKPT; + } + p->apDflt[iIdx] = pVal; } - p->apDflt[iIdx] = pVal; + *ppValue = p->apDflt[iIdx]; + }else{ + *ppValue = (sqlite3_value *)columnNullValue(); + } + }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){ + if( pMem->flags & (MEM_Int|MEM_IntReal) ){ + testcase( pMem->flags & MEM_Int ); + testcase( pMem->flags & MEM_IntReal ); + sqlite3VdbeMemRealify(pMem); } - *ppValue = p->apDflt[iIdx]; - }else{ - *ppValue = (sqlite3_value *)columnNullValue(); - } - }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){ - if( pMem->flags & (MEM_Int|MEM_IntReal) ){ - testcase( pMem->flags & MEM_Int ); - testcase( pMem->flags & MEM_IntReal ); - sqlite3VdbeMemRealify(pMem); } } @@ -92783,7 +95671,7 @@ SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){ #else p = db->pPreUpdate; #endif - return (p ? p->keyinfo.nKeyField : 0); + return (p ? p->pKeyinfo->nKeyField : 0); } #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ @@ -92835,6 +95723,7 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppVa PreUpdate *p; int rc = SQLITE_OK; Mem *pMem; + int iStore = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( db==0 || ppValue==0 ){ @@ -92847,9 +95736,14 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppVa goto preupdate_new_out; } if( p->pPk && p->op!=SQLITE_UPDATE ){ - iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx); + iStore = sqlite3TableColumnToIndex(p->pPk, iIdx); + }else if( iIdx >= p->pTab->nCol ){ + return SQLITE_MISUSE_BKPT; + }else{ + iStore = sqlite3TableColumnToStorage(p->pTab, iIdx); } - if( iIdx>=p->pCsr->nField || iIdx<0 ){ + + if( iStore>=p->pCsr->nField || iStore<0 ){ rc = SQLITE_RANGE; goto preupdate_new_out; } @@ -92862,40 +95756,46 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppVa Mem *pData = &p->v->aMem[p->iNewReg]; rc = ExpandBlob(pData); if( rc!=SQLITE_OK ) goto preupdate_new_out; - pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z); + pUnpack = vdbeUnpackRecord(p->pKeyinfo, pData->n, pData->z); if( !pUnpack ){ rc = SQLITE_NOMEM; goto preupdate_new_out; } p->pNewUnpacked = pUnpack; } - pMem = &pUnpack->aMem[iIdx]; + pMem = &pUnpack->aMem[iStore]; if( iIdx==p->pTab->iPKey ){ sqlite3VdbeMemSetInt64(pMem, p->iKey2); - }else if( iIdx>=pUnpack->nField ){ + }else if( iStore>=pUnpack->nField ){ pMem = (sqlite3_value *)columnNullValue(); + }else if( (p->pTab->aCol) + && (p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL) + && (pMem->flags & (MEM_Int|MEM_IntReal)) + ){ + sqlite3VdbeMemRealify(pMem); } }else{ - /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required + /* For an UPDATE, memory cell (p->iNewReg+1+iStore) contains the required ** value. Make a copy of the cell contents and return a pointer to it. ** It is not safe to return a pointer to the memory cell itself as the ** caller may modify the value text encoding. */ assert( p->op==SQLITE_UPDATE ); if( !p->aNew ){ - p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField); + assert( sizeof(Mem)*UMXV(p->pCsr->nField) < 0x7fffffff ); + p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem)*p->pCsr->nField); if( !p->aNew ){ rc = SQLITE_NOMEM; goto preupdate_new_out; } } - assert( iIdx>=0 && iIdx<p->pCsr->nField ); - pMem = &p->aNew[iIdx]; + assert( iStore>=0 && iStore<p->pCsr->nField ); + pMem = &p->aNew[iStore]; if( pMem->flags==0 ){ if( iIdx==p->pTab->iPKey ){ sqlite3VdbeMemSetInt64(pMem, p->iKey2); }else{ - rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]); + rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iStore]); if( rc!=SQLITE_OK ) goto preupdate_new_out; } } @@ -93119,10 +96019,10 @@ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){ ** a host parameter. If the text contains no host parameters, return ** the total number of bytes in the text. */ -static int findNextHostParameter(const char *zSql, int *pnToken){ +static i64 findNextHostParameter(const char *zSql, i64 *pnToken){ int tokenType; - int nTotal = 0; - int n; + i64 nTotal = 0; + i64 n; *pnToken = 0; while( zSql[0] ){ @@ -93169,8 +96069,8 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql( sqlite3 *db; /* The database connection */ int idx = 0; /* Index of a host parameter */ int nextIndex = 1; /* Index of next ? host parameter */ - int n; /* Length of a token prefix */ - int nToken; /* Length of the parameter token */ + i64 n; /* Length of a token prefix */ + i64 nToken; /* Length of the parameter token */ int i; /* Loop counter */ Mem *pVar; /* Value of a host parameter */ StrAccum out; /* Accumulate the output here */ @@ -93335,17 +96235,19 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql( #ifndef SQLITE_HWTIME_H #define SQLITE_HWTIME_H -/* -** The following routine only works on Pentium-class (or newer) processors. -** It uses the RDTSC opcode to read the cycle count value out of the -** processor and returns that value. This can be used for high-res -** profiling. -*/ -#if !defined(__STRICT_ANSI__) && \ - (defined(__GNUC__) || defined(_MSC_VER)) && \ - (defined(i386) || defined(__i386__) || defined(_M_IX86)) +#if defined(_MSC_VER) && defined(_WIN32) + +/* #include "windows.h" */ + #include <profileapi.h> + + __inline sqlite3_uint64 sqlite3Hwtime(void){ + LARGE_INTEGER tm; + QueryPerformanceCounter(&tm); + return (sqlite3_uint64)tm.QuadPart; + } - #if defined(__GNUC__) +#elif !defined(__STRICT_ANSI__) && defined(__GNUC__) && \ + (defined(i586) || defined(__i586__) || defined(_M_IX86)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ unsigned int lo, hi; @@ -93353,17 +96255,6 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql( return (sqlite_uint64)hi << 32 | lo; } - #elif defined(_MSC_VER) - - __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ - __asm { - rdtsc - ret ; return value at EDX:EAX - } - } - - #endif - #elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ @@ -93372,6 +96263,14 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql( return (sqlite_uint64)hi << 32 | lo; } +#elif !defined(__STRICT_ANSI__) && defined(__GNUC__) && defined(__aarch64__) + + __inline__ sqlite_uint64 sqlite3Hwtime(void){ + sqlite3_uint64 cnt; + __asm__ __volatile__ ("mrs %0, cntvct_el0" : "=r" (cnt)); + return cnt; + } + #elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__)) __inline__ sqlite_uint64 sqlite3Hwtime(void){ @@ -93653,11 +96552,11 @@ static VdbeCursor *allocateCursor( */ Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem; - int nByte; + i64 nByte; VdbeCursor *pCx = 0; - nByte = - ROUND8P(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + - (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0); + nByte = SZ_VDBECURSOR(nField); + assert( ROUND8(nByte)==nByte ); + if( eCurType==CURTYPE_BTREE ) nByte += sqlite3BtreeCursorSize(); assert( iCur>=0 && iCur<p->nCursor ); if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/ @@ -93681,7 +96580,7 @@ static VdbeCursor *allocateCursor( pMem->szMalloc = 0; return 0; } - pMem->szMalloc = nByte; + pMem->szMalloc = (int)nByte; } p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->zMalloc; @@ -93690,8 +96589,8 @@ static VdbeCursor *allocateCursor( pCx->nField = nField; pCx->aOffset = &pCx->aType[nField]; if( eCurType==CURTYPE_BTREE ){ - pCx->uc.pCursor = (BtCursor*) - &pMem->z[ROUND8P(sizeof(VdbeCursor))+2*sizeof(u32)*nField]; + assert( ROUND8(SZ_VDBECURSOR(nField))==SZ_VDBECURSOR(nField) ); + pCx->uc.pCursor = (BtCursor*)&pMem->z[SZ_VDBECURSOR(nField)]; sqlite3BtreeCursorZero(pCx->uc.pCursor); } return pCx; @@ -93730,12 +96629,11 @@ static int alsoAnInt(Mem *pRec, double rValue, i64 *piValue){ */ static void applyNumericAffinity(Mem *pRec, int bTryForInt){ double rValue; - u8 enc = pRec->enc; int rc; assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str ); - rc = sqlite3AtoF(pRec->z, &rValue, pRec->n, enc); + rc = sqlite3MemRealValueRC(pRec, &rValue); if( rc<=0 ) return; - if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){ + if( (rc&2)==0 && alsoAnInt(pRec, rValue, &pRec->u.i) ){ pRec->flags |= MEM_Int; }else{ pRec->u.r = rValue; @@ -93815,7 +96713,12 @@ SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){ int eType = sqlite3_value_type(pVal); if( eType==SQLITE_TEXT ){ Mem *pMem = (Mem*)pVal; +#if SQLITE_THREADSAFE>0 + sqlite3_mutex *pMutex = pMem->db ? pMem->db->mutex : 0; +#endif + sqlite3_mutex_enter(pMutex); applyNumericAffinity(pMem, 0); + sqlite3_mutex_leave(pMutex); eType = sqlite3_value_type(pVal); } return eType; @@ -93848,15 +96751,15 @@ static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){ pMem->u.i = 0; return MEM_Int; } - rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc); + rc = sqlite3MemRealValueRC(pMem, &pMem->u.r); if( rc<=0 ){ - if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){ + if( (rc&2)==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){ pMem->u.i = ix; return MEM_Int; }else{ return MEM_Real; } - }else if( rc==1 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){ + }else if( (rc&2)==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){ pMem->u.i = ix; return MEM_Int; } @@ -93984,6 +96887,7 @@ static void registerTrace(int iReg, Mem *p){ printf("R[%d] = ", iReg); memTracePrint(p); if( p->pScopyFrom ){ + assert( p->pScopyFrom->bScopy ); printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg])); } printf("\n"); @@ -94060,6 +96964,10 @@ static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){ /* ** Compute a bloom filter hash using pOp->p4.i registers from aMem[] beginning ** with pOp->p3. Return the hash. +** +** IMPORTANT RESTRICTION (tag-202607231411): This hash is only valid if the +** collating sequence for TEXT is BINARY. Hence, Bloom filters that use this +** hash will not work for look-ups that use any other collating sequence. */ static u64 filterHash(const Mem *aMem, const Op *pOp){ int i, mx; @@ -94072,17 +96980,33 @@ static u64 filterHash(const Mem *aMem, const Op *pOp){ h += p->u.i; }else if( p->flags & MEM_Real ){ h += sqlite3VdbeIntValue(p); - }else if( p->flags & (MEM_Str|MEM_Blob) ){ - /* All strings have the same hash and all blobs have the same hash, - ** though, at least, those hashes are different from each other and - ** from NULL. */ - h += 4093 + (p->flags & (MEM_Str|MEM_Blob)); + }else if( p->flags & MEM_Str ){ + u64 x; + h += p->n; + if( p->n >= (int)sizeof(x) ){ + memcpy(&x, p->z, sizeof(x)); + h += x; + memcpy(&x, p->z + p->n - sizeof(x), sizeof(x)); + h += x; + }else{ + x = 0; + memcpy(&x, p->z, p->n); + h += x; + } + }else if( p->flags & MEM_Blob ){ + int n = p->n; + u64 x = 0; + if( n ){ + memcpy(&x, p->z, MIN(n, (int)sizeof(x))); + h += x; + } + h += n; + if( p->flags & MEM_Zero ) h += p->u.nZero; } } return h; } - /* ** For OP_Column, factor out the case where content is loaded from ** overflow pages, so that the code to implement this case is separate @@ -94093,7 +97017,7 @@ static u64 filterHash(const Mem *aMem, const Op *pOp){ static SQLITE_NOINLINE int vdbeColumnFromOverflow( VdbeCursor *pC, /* The BTree cursor from which we are reading */ int iCol, /* The column to read */ - int t, /* The serial-type code for the column value */ + u32 t, /* The serial-type code for the column value */ i64 iOffset, /* Offset to the start of the content value */ u32 cacheStatus, /* Current Vdbe.cacheCtr value */ u32 colCacheCtr, /* Current value of the column cache counter */ @@ -94154,6 +97078,7 @@ static SQLITE_NOINLINE int vdbeColumnFromOverflow( }else{ rc = sqlite3VdbeMemSetStr(pDest, pBuf, len, 0, sqlite3RCStrUnref); + pDest->enc = encoding; } }else{ rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, iOffset, len, pDest); @@ -94168,6 +97093,70 @@ static SQLITE_NOINLINE int vdbeColumnFromOverflow( return rc; } +/* +** Memory cell pMem may contain a blob or a NULL value. Cursor pCsr is +** open on an index. If the current index entry matches the blob value in +** pMem byte-for-byte, set pMem to NULL and return 1. Otherwise, return 0. +** +** If an error occurs, set (*pRc) to an SQLite error code. Return 1 in this +** case as well. +*/ +static SQLITE_NOINLINE int vdbeIndexKeyCompare( + BtCursor *pCsr, /* Cursor to compare key to */ + Mem *pMem, + int *pRc +){ + int ret = 0; + u32 nKey = 0; + + assert( pMem->flags & (MEM_Blob|MEM_Null) ); + nKey = sqlite3BtreePayloadSize(pCsr); + if( nKey==(u32)pMem->n && ALWAYS((pMem->flags & MEM_Blob)!=0) ){ + /* This code could just use sqlite3BtreePayloadFetch(). But calling that + ** function here apparently prevents compilers from inlining it in other, + ** more performance critical, places. So this code uses + ** MemFromBtreeZeroOffset(), which is just as fast in most cases, but also + ** handles the case where the index record uses overflow pages. */ + Mem m; + memset(&m, 0, sizeof(m)); + *pRc = sqlite3VdbeMemFromBtreeZeroOffset(pCsr, nKey, &m); + ret = (*pRc!=SQLITE_OK || 0==memcmp(pMem->z, m.z, nKey)); + sqlite3VdbeMemReleaseMalloc(&m); + } + + return ret; +} + +/* +** Send a "statement aborts" message to the error log. +*/ +static SQLITE_NOINLINE void sqlite3VdbeLogAbort( + Vdbe *p, /* The statement that is running at the time of failure */ + int rc, /* Error code */ + Op *pOp, /* Opcode that filed */ + Op *aOp /* All opcodes */ +){ + const char *zSql = p->zSql; /* Original SQL text */ + const char *zPrefix = ""; /* Prefix added to SQL text */ + int pc; /* Opcode address */ + char zXtra[100]; /* Buffer space to store zPrefix */ + + if( p->pFrame ){ + assert( aOp[0].opcode==OP_Init ); + if( aOp[0].p4.z!=0 ){ + assert( aOp[0].p4.z[0]=='-' + && aOp[0].p4.z[1]=='-' + && aOp[0].p4.z[2]==' ' ); + sqlite3_snprintf(sizeof(zXtra), zXtra,"/* %s */ ",aOp[0].p4.z+3); + zPrefix = zXtra; + }else{ + zPrefix = "/* unknown trigger */ "; + } + } + pc = (int)(pOp - aOp); + sqlite3_log(rc, "statement aborts at %d: %s; [%s%s]", + pc, p->zErrMsg, zPrefix, zSql); +} /* ** Return the symbolic name for the data type of a pMem @@ -94693,8 +97682,7 @@ case OP_Halt: { }else{ sqlite3VdbeError(p, "%s", pOp->p4.z); } - pcx = (int)(pOp - aOp); - sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg); + sqlite3VdbeLogAbort(p, pOp->p1, pOp, aOp); } rc = sqlite3VdbeHalt(p); assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR ); @@ -94719,31 +97707,35 @@ case OP_Integer: { /* out2 */ break; } -/* Opcode: Int64 * P2 * P4 * -** Synopsis: r[P2]=P4 +/* Opcode: Int64 P1 P2 P3 * * +** Synopsis: r[P2]=PINT13 ** -** P4 is a pointer to a 64-bit integer value. -** Write that value into register P2. +** Combine P1 and P3 into a signed 64-bit integer. P1 is the least +** significant 32 bits and P3 is the most significant. Store the +** result in register P2. */ case OP_Int64: { /* out2 */ pOut = out2Prerelease(p, pOp); - assert( pOp->p4.pI64!=0 ); - pOut->u.i = *pOp->p4.pI64; + pOut->u.i = INT32_TO_64(pOp->p1,pOp->p3); break; } #ifndef SQLITE_OMIT_FLOATING_POINT -/* Opcode: Real * P2 * P4 * -** Synopsis: r[P2]=P4 +/* Opcode: Real P1 P2 P3 * * +** Synopsis: r[P2]=PDBL13 ** -** P4 is a pointer to a 64-bit floating point value. -** Write that value into register P2. +** P1 and P3 are combined to 64 bits with P1 being the lower the P3 +** the upper. The result is interpreted as a 64-bit floating-point +** and stored in register P2. */ case OP_Real: { /* same as TK_FLOAT, out2 */ + u64 ii; pOut = out2Prerelease(p, pOp); pOut->flags = MEM_Real; - assert( !sqlite3IsNaN(*pOp->p4.pReal) ); - pOut->u.r = *pOp->p4.pReal; + ii = (u64)INT32_TO_64(pOp->p1,pOp->p3); + swapMixedEndianFloat(ii); + memcpy(&pOut->u.r, &ii, 8); + assert( !sqlite3IsNaN(pOut->u.r) ); break; } #endif @@ -94967,6 +97959,7 @@ case OP_Move: { { int i; for(i=1; i<p->nMem; i++){ if( aMem[i].pScopyFrom==pIn1 ){ + assert( aMem[i].bScopy ); aMem[i].pScopyFrom = pOut; } } @@ -95039,6 +98032,7 @@ case OP_SCopy: { /* out2 */ #ifdef SQLITE_DEBUG pOut->pScopyFrom = pIn1; pOut->mScopyFlags = pIn1->flags; + pIn1->bScopy = 1; #endif break; } @@ -95071,7 +98065,7 @@ case OP_IntCopy: { /* out2 */ ** RETURNING clause. */ case OP_FkCheck: { - if( (rc = sqlite3VdbeCheckFk(p,0))!=SQLITE_OK ){ + if( (rc = sqlite3VdbeCheckFkImmediate(p))!=SQLITE_OK ){ goto abort_due_to_error; } break; @@ -95163,10 +98157,14 @@ case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem; flags2 = pIn2->flags & ~MEM_Str; } - nByte = pIn1->n + pIn2->n; + nByte = pIn1->n; + nByte += pIn2->n; if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; } +#if SQLITE_MAX_LENGTH>2147483645 + if( nByte>2147483645 ){ goto too_big; } +#endif if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){ goto no_mem; } @@ -95444,7 +98442,18 @@ case OP_AddImm: { /* in1 */ case OP_MustBeInt: { /* jump0, in1 */ pIn1 = &aMem[pOp->p1]; if( (pIn1->flags & MEM_Int)==0 ){ - applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding); + if( (pIn1->flags & MEM_Real)!=0 ){ + sqlite3_int64 ix; + if( pIn1->u.r>=-9223372036854775808.0 + && pIn1->u.r<+9223372036854775808.0 + && (double)(ix = sqlite3RealToI64(pIn1->u.r))==pIn1->u.r + ){ + pIn1->u.i = ix; + MemSetTypeFlag(pIn1, MEM_Int); + } + }else{ + applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding); + } if( (pIn1->flags & MEM_Int)==0 ){ VdbeBranchTaken(1, 2); if( pOp->p2==0 ){ @@ -95850,6 +98859,7 @@ case OP_Compare: { pKeyInfo = pOp->p4.pKeyInfo; assert( n>0 ); assert( pKeyInfo!=0 ); + assert( pKeyInfo->aSortFlags!=0 ); p1 = pOp->p1; p2 = pOp->p2; #ifdef SQLITE_DEBUG @@ -96018,7 +99028,7 @@ case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */ break; } -/* Opcode: Once P1 P2 * * * +/* Opcode: Once P1 P2 P3 * * ** ** Fall through to the next instruction the first time this opcode is ** encountered on each invocation of the byte-code program. Jump to P2 @@ -96034,6 +99044,12 @@ case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */ ** whether or not the jump should be taken. The bitmask is necessary ** because the self-altering code trick does not work for recursive ** triggers. +** +** The P3 operand is not used directly by this opcode. However P3 is +** used by the code generator as follows: If this opcode is the start +** of a subroutine and that subroutine uses a Bloom filter, then P3 will +** be the register that holds that Bloom filter. See tag-202407032019 +** in the source code for implementation details. */ case OP_Once: { /* jump */ u32 iAddr; /* Address of this instruction */ @@ -96523,30 +99539,91 @@ case OP_Column: { /* ncycle */ assert( t==pC->aType[p2] ); if( pC->szRow>=aOffset[p2+1] ){ /* This is the common case where the desired content fits on the original - ** page - where the content is not on an overflow page */ + ** page - where the content is not on an overflow page. + ** + ** The big switch() is an in-line variant of sqlite3VdbeSerialGet() that + ** has been optimized for the OP_Column opcode. + */ zData = pC->aRow + aOffset[p2]; - if( t<12 ){ - sqlite3VdbeSerialGet(zData, t, pDest); - }else{ - /* If the column value is a string, we need a persistent value, not - ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent - ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize(). - */ - static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term }; - pDest->n = len = (t-12)/2; - pDest->enc = encoding; - if( pDest->szMalloc < len+2 ){ - if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) goto too_big; + switch( t ){ + case 0: + case 11: pDest->flags = MEM_Null; - if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem; - }else{ - pDest->z = pDest->zMalloc; + break; + case 1: + pDest->u.i = ONE_BYTE_INT(zData); + pDest->flags = MEM_Int; + testcase( pDest->u.i<0 ); + break; + case 2: + pDest->u.i = TWO_BYTE_INT(zData); + pDest->flags = MEM_Int; + testcase( pDest->u.i<0 ); + break; + case 3: + pDest->u.i = THREE_BYTE_INT(zData); + pDest->flags = MEM_Int; + testcase( pDest->u.i<0 ); + break; + case 4: + pDest->u.i = FOUR_BYTE_INT(zData); + pDest->flags = MEM_Int; + testcase( pDest->u.i<0 ); + break; + case 5: + pDest->u.i = SIX_BYTE_INT(zData); + pDest->flags = MEM_Int; + testcase( pDest->u.i<0 ); + break; + case 6: { + pDest->u.i = (i64)sqlite3Get8byte(zData); + pDest->flags = MEM_Int; + testcase( pDest->u.i<0 ); + break; } - memcpy(pDest->z, zData, len); - pDest->z[len] = 0; - pDest->z[len+1] = 0; - pDest->flags = aFlag[t&1]; - } + case 7: { + u64 x = sqlite3Get8byte(zData); + swapMixedEndianFloat(x); + pDest->flags = IsNaN(x) ? MEM_Null : MEM_Real; + memcpy(&pDest->u.r, &x, sizeof(x)); + testcase( pDest->u.r<0 ); + break; + } + case 8: + case 9: { + pDest->u.i = t-8; + pDest->flags = MEM_Int; + break; + } + case 10: + /* Internal use only: NULL with virtual table + ** UPDATE no-change flag set */ + pDest->flags = MEM_Null|MEM_Zero; + pDest->u.nZero = 0; + pDest->n = 0; + break; + default: { + /* If the column value is a string or blob, we need a persistent + ** value, not a MEM_Ephem value. This case is a fast short-cut + ** that is equivalent to calling sqlite3VdbeSerialGet() and + ** sqlite3VdbeDeephemeralize(). + */ + static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term }; + pDest->n = len = (t-12)/2; + pDest->enc = encoding; + if( pDest->szMalloc < len+2 ){ + if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) goto too_big; + pDest->flags = MEM_Null; + if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem; + }else{ + pDest->z = pDest->zMalloc; + } + memcpy(pDest->z, zData, len); + pDest->z[len] = 0; + pDest->z[len+1] = 0; + pDest->flags = aFlag[t&1]; + } + } /* End of switch */ }else{ u8 p5; pDest->enc = encoding; @@ -96606,6 +99683,15 @@ case OP_Column: { /* ncycle */ ** Take the affinities from the Table object in P4. If any value ** cannot be coerced into the correct type, then raise an error. ** +** If P3==0, then omit checking of VIRTUAL columns. +** +** If P3==1, then omit checking of all generated column, both VIRTUAL +** and STORED. +** +** If P3>=2, then only check column number P3-2 in the table (which will +** be a VIRTUAL column) against the value in reg[P1]. In this case, +** P2 will be 1. +** ** This opcode is similar to OP_Affinity except that this opcode ** forces the register type to the Table column type. This is used ** to implement "strict affinity". @@ -96619,8 +99705,8 @@ case OP_Column: { /* ncycle */ ** ** <ul> ** <li> P2 should be the number of non-virtual columns in the -** table of P4. -** <li> Table P4 should be a STRICT table. +** table of P4 unless P3>1, in which case P2 will be 1. +** <li> Table P4 is a STRICT table. ** </ul> ** ** If any precondition is false, an assertion fault occurs. @@ -96629,16 +99715,28 @@ case OP_TypeCheck: { Table *pTab; Column *aCol; int i; + int nCol; assert( pOp->p4type==P4_TABLE ); pTab = pOp->p4.pTab; assert( pTab->tabFlags & TF_Strict ); - assert( pTab->nNVCol==pOp->p2 ); + assert( pOp->p3>=0 && pOp->p3<pTab->nCol+2 ); aCol = pTab->aCol; pIn1 = &aMem[pOp->p1]; - for(i=0; i<pTab->nCol; i++){ - if( aCol[i].colFlags & COLFLAG_GENERATED ){ - if( aCol[i].colFlags & COLFLAG_VIRTUAL ) continue; + if( pOp->p3<2 ){ + assert( pTab->nNVCol==pOp->p2 ); + i = 0; + nCol = pTab->nCol; + }else{ + i = pOp->p3-2; + nCol = i+1; + assert( i<pTab->nCol ); + assert( aCol[i].colFlags & COLFLAG_VIRTUAL ); + assert( pOp->p2==1 ); + } + for(; i<nCol; i++){ + if( (aCol[i].colFlags & COLFLAG_GENERATED)!=0 && pOp->p3<2 ){ + if( (aCol[i].colFlags & COLFLAG_VIRTUAL)!=0 ) continue; if( pOp->p3 ){ pIn1++; continue; } } assert( pIn1 < &aMem[pOp->p1+pOp->p2] ); @@ -96725,22 +99823,9 @@ case OP_Affinity: { assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) ); applyAffinity(pIn1, zAffinity[0], encoding); if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){ - /* When applying REAL affinity, if the result is still an MEM_Int - ** that will fit in 6 bytes, then change the type to MEM_IntReal - ** so that we keep the high-resolution integer value but know that - ** the type really wants to be REAL. */ - testcase( pIn1->u.i==140737488355328LL ); - testcase( pIn1->u.i==140737488355327LL ); - testcase( pIn1->u.i==-140737488355328LL ); - testcase( pIn1->u.i==-140737488355329LL ); - if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){ - pIn1->flags |= MEM_IntReal; - pIn1->flags &= ~MEM_Int; - }else{ - pIn1->u.r = (double)pIn1->u.i; - pIn1->flags |= MEM_Real; - pIn1->flags &= ~(MEM_Int|MEM_Str); - } + pIn1->u.r = (double)pIn1->u.i; + pIn1->flags |= MEM_Real; + pIn1->flags &= ~(MEM_Int|MEM_Str); } REGISTER_TRACE((int)(pIn1-aMem), pIn1); zAffinity++; @@ -96960,7 +100045,7 @@ case OP_MakeRecord: { len = (u32)pRec->n; serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0); if( pRec->flags & MEM_Zero ){ - serial_type += pRec->u.nZero*2; + serial_type += (u32)pRec->u.nZero*2; if( nData ){ if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem; len += pRec->u.nZero; @@ -96993,12 +100078,24 @@ case OP_MakeRecord: { } nByte = nHdr+nData; + /* If we are able to put an over-run area of 7 bytes on the end of the + ** memory allocation into which the record is being constructed, then + ** the encoding of integer values can go faster. This is only possible + ** if SQLITE_MAX_LENGTH is no with 7 of INT32_MAX and if the host CPU + ** byte-order is known at compile-time. + */ +#if SQLITE_MAX_LENGTH<=2147483640 && SQLITE_BYTEORDER>0 +# define OVERRUN 7 /* We are able to allocate an overrun of 7 bytes */ +#else +# define OVERRUN 0 /* No overrun will be available */ +#endif + /* Make sure the output register has a buffer large enough to store ** the new record. The output register (pOp->p3) is not allowed to ** be one of the input registers (because the following call to ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used). */ - if( nByte+nZero<=pOut->szMalloc ){ + if( nByte+nZero<=pOut->szMalloc-OVERRUN ){ /* The output register is already large enough to hold the record. ** No error checks or buffer enlargement is required */ pOut->z = pOut->zMalloc; @@ -97008,7 +100105,7 @@ case OP_MakeRecord: { if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){ goto too_big; } - if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){ + if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte+OVERRUN) ){ goto no_mem; } } @@ -97051,6 +100148,27 @@ case OP_MakeRecord: { } len = sqlite3SmallTypeSizes[serial_type]; assert( len>=1 && len<=8 && len!=5 && len!=7 ); +#if SQLITE_BYTEORDER==1234 + v = sqlite3BSwap64(v); + if( OVERRUN ){ + static const u8 aShift[] = { 0, 56, 48, 40, 32, 16, 0, 0 }; + v >>= aShift[serial_type]; + memcpy(zPayload, &v, 8); + }else{ + /* Test this limb by compiling with -DSQLITE_MAX_LENGTH=2147483647 */ + memcpy(zPayload, (u8*)&v + 8 - len, len); + } +#elif SQLITE_BYTEORDER==4321 + if( OVERRUN ){ + static const u8 aShift[] = { 0, 56, 48, 40, 32, 16, 0, 0 }; + v <<= aShift[serial_type]; + memcpy(zPayload, &v, 8); + }else{ + /* Test this limb by compiling with -DSQLITE_MAX_LENGTH=2147483647 */ + memcpy(zPayload, (u8*)&v + 8 - len, len); + } +#else + /* Test this limb by compiling with -DSQLITE_BYTEORDER=0 */ switch( len ){ default: zPayload[7] = (u8)(v&0xff); v >>= 8; zPayload[6] = (u8)(v&0xff); v >>= 8; @@ -97066,6 +100184,8 @@ case OP_MakeRecord: { /* no break */ deliberate_fall_through case 1: zPayload[0] = (u8)(v&0xff); } +#endif +#undef OVERRUN /* We are done with the OVERRUN macro now */ zPayload += len; } }else if( serial_type<0x80 ){ @@ -97079,6 +100199,7 @@ case OP_MakeRecord: { zHdr += sqlite3PutVarint(zHdr, serial_type); if( pRec->n ){ assert( pRec->z!=0 ); + assert( pRec->z!=(const char*)sqlite3CtypeMap ); memcpy(zPayload, pRec->z, pRec->n); zPayload += pRec->n; } @@ -97226,7 +100347,7 @@ case OP_Savepoint: { */ int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint; if( isTransaction && p1==SAVEPOINT_RELEASE ){ - if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ + if( (rc = sqlite3VdbeCheckFkDeferred(p))!=SQLITE_OK ){ goto vdbe_return; } db->autoCommit = 1; @@ -97344,7 +100465,7 @@ case OP_AutoCommit: { "SQL statements in progress"); rc = SQLITE_BUSY; goto abort_due_to_error; - }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){ + }else if( (rc = sqlite3VdbeCheckFkDeferred(p))!=SQLITE_OK ){ goto vdbe_return; }else{ db->autoCommit = (u8)desiredAutoCommit; @@ -97915,9 +101036,11 @@ case OP_OpenEphemeral: { /* ncycle */ } } pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED); + assert( p->apCsr[pOp->p1]==pCx ); if( rc ){ assert( !sqlite3BtreeClosesWithCursor(pCx->ub.pBtx, pCx->uc.pCursor) ); sqlite3BtreeClose(pCx->ub.pBtx); + p->apCsr[pOp->p1] = 0; /* Not required; helps with static analysis */ }else{ assert( sqlite3BtreeClosesWithCursor(pCx->ub.pBtx, pCx->uc.pCursor) ); } @@ -98020,21 +101143,21 @@ case OP_Close: { /* ncycle */ } #ifdef SQLITE_ENABLE_COLUMN_USED_MASK -/* Opcode: ColumnsUsed P1 * * P4 * +/* Opcode: ColumnsUsed P1 P2 P3 * * +** Synopsis: Cursor P1 uses columns PHEX23 ** ** This opcode (which only exists if SQLite was compiled with ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the -** table or index for cursor P1 are used. P4 is a 64-bit integer -** (P4_INT64) in which the first 63 bits are one for each of the -** first 63 columns of the table or index that are actually used -** by the cursor. The high-order bit is set if any column after -** the 64th is used. +** table or index for cursor P1 are used. P2 and P3 combine to give +** a 64-bit unsigned integer mask. P2 stores the lower 32 bits and +** P3 stores the upper 32 bits. If the high-order bit of P3 is set +** that means that and 64-th or some later column is used. */ case OP_ColumnsUsed: { VdbeCursor *pC; pC = p->apCsr[pOp->p1]; assert( pC->eCurType==CURTYPE_BTREE ); - pC->maskUsed = *(u64*)pOp->p4.pI64; + pC->maskUsed = INT32_TO_64(pOp->p2,pOp->p3); break; } #endif @@ -98545,24 +101668,6 @@ case OP_SeekHit: { /* ncycle */ break; } -/* Opcode: IfNotOpen P1 P2 * * * -** Synopsis: if( !csr[P1] ) goto P2 -** -** If cursor P1 is not open or if P1 is set to a NULL row using the -** OP_NullRow opcode, then jump to instruction P2. Otherwise, fall through. -*/ -case OP_IfNotOpen: { /* jump */ - VdbeCursor *pCur; - - assert( pOp->p1>=0 && pOp->p1<p->nCursor ); - pCur = p->apCsr[pOp->p1]; - VdbeBranchTaken(pCur==0 || pCur->nullRow, 2); - if( pCur==0 || pCur->nullRow ){ - goto jump_to_p2_and_check_for_interrupt; - } - break; -} - /* Opcode: Found P1 P2 P3 P4 * ** Synopsis: key=r[P3@P4] ** @@ -98714,7 +101819,7 @@ case OP_Found: { /* jump, in3, ncycle */ if( rc ) goto no_mem; pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo); if( pIdxKey==0 ) goto no_mem; - sqlite3VdbeRecordUnpack(pC->pKeyInfo, r.aMem->n, r.aMem->z, pIdxKey); + sqlite3VdbeRecordUnpack(r.aMem->n, r.aMem->z, pIdxKey); pIdxKey->default_rc = 0; rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, pIdxKey, &pC->seekResult); sqlite3DbFreeNN(db, pIdxKey); @@ -98804,7 +101909,7 @@ case OP_SeekRowid: { /* jump0, in3, ncycle */ VdbeCursor *pC; BtCursor *pCrsr; int res; - u64 iKey; + i64 iKey; pIn3 = &aMem[pOp->p3]; testcase( pIn3->flags & MEM_Int ); @@ -98818,9 +101923,21 @@ case OP_SeekRowid: { /* jump0, in3, ncycle */ ** changing the datatype of pIn3, however, as it is used by other ** parts of the prepared statement. */ Mem x = pIn3[0]; - applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding); - if( (x.flags & MEM_Int)==0 ) goto jump_to_p2; - iKey = x.u.i; + if( x.flags & MEM_Str ){ + applyNumericAffinity(&x, 1); + } + if( x.flags & MEM_Int ){ + iKey = x.u.i; + }else + if( (x.flags & MEM_Real)==0 + || x.u.r < -9223372036854775808.0 + || x.u.r > 9223372036854774784.0 + /* ^^^^^^^^^^^^^^^^^^^^^-- same value as every other double + ** between 9223372036854774263.0 and 923372036854775295.0 */ + || (double)(iKey = sqlite3RealToI64(x.u.r))!=x.u.r + ){ + goto jump_to_p2; + } goto notExistsWithKey; } /* Fall through into OP_NotExists */ @@ -99428,7 +102545,7 @@ case OP_RowData: { /* The OP_RowData opcodes always follow OP_NotExists or ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions ** that might invalidate the cursor. - ** If this where not the case, on of the following assert()s + ** If this were not the case, one of the following assert()s ** would fail. Should this ever change (because of changes in the code ** generator) then the fix would be to insert a call to ** sqlite3VdbeCursorMoveto(). @@ -99500,14 +102617,17 @@ case OP_Rowid: { /* out2, ncycle */ break; } -/* Opcode: NullRow P1 * * * * +/* Opcode: NullRow P1 P2 * * * ** -** Move the cursor P1 to a null row. Any OP_Column operations +** Move the cursor P1 to a null row if P2 is 0. Any OP_Column operations ** that occur while the cursor is on the null row will always ** write a NULL. ** ** If cursor P1 is not previously opened, open it now to a special ** pseudo-cursor that always returns NULL for every column. +** +** If P2 is not 0, then the nullRow flag on the pseudo-cursor is +** turned off. */ case OP_NullRow: { VdbeCursor *pC; @@ -99524,7 +102644,7 @@ case OP_NullRow: { pC->noReuse = 1; pC->uc.pCursor = sqlite3BtreeFakeValidCursor(); } - pC->nullRow = 1; + pC->nullRow = (pOp->p2==0); pC->cacheStatus = CACHE_STALE; if( pC->eCurType==CURTYPE_BTREE ){ assert( pC->uc.pCursor!=0 ); @@ -99712,6 +102832,32 @@ case OP_Rewind: { /* jump0, ncycle */ break; } +/* Opcode: IfEmpty P1 P2 * * * +** Synopsis: if( empty(P1) ) goto P2 +** +** Check to see if the b-tree table that cursor P1 references is empty +** and jump to P2 if it is. +*/ +case OP_IfEmpty: { /* jump */ + VdbeCursor *pC; + BtCursor *pCrsr; + int res; + + assert( pOp->p1>=0 && pOp->p1<p->nCursor ); + assert( pOp->p2>=0 && pOp->p2<p->nOp ); + + pC = p->apCsr[pOp->p1]; + assert( pC!=0 ); + assert( pC->eCurType==CURTYPE_BTREE ); + pCrsr = pC->uc.pCursor; + assert( pCrsr ); + rc = sqlite3BtreeIsEmpty(pCrsr, &res); + if( rc ) goto abort_due_to_error; + VdbeBranchTaken(res!=0,2); + if( res ) goto jump_to_p2; + break; +} + /* Opcode: Next P1 P2 P3 * P5 ** ** Advance cursor P1 so that it points to the next key/data pair in its @@ -99904,20 +103050,22 @@ case OP_SorterInsert: { /* in2 */ break; } -/* Opcode: IdxDelete P1 P2 P3 * P5 -** Synopsis: key=r[P2@P3] +/* Opcode: IdxDelete P1 P2 P3 P4 P5 +** Synopsis: key=r[P2@P5] ** -** The content of P3 registers starting at register P2 form +** The content of P5 registers starting at register P2 form ** an unpacked index key. This opcode removes that entry from the ** index opened by cursor P1. ** -** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error -** if no matching index entry is found. This happens when running -** an UPDATE or DELETE statement and the index entry to be updated -** or deleted is not found. For some uses of IdxDelete -** (example: the EXCEPT operator) it does not matter that no matching -** entry is found. For those cases, P5 is zero. Also, do not raise -** this (self-correcting and non-critical) error if in writable_schema mode. +** P4 is a pointer to an Index structure. +** +** If P3 is non-zero, it is the register number of a register holding +** a record that will be inserted into this index. If that record is +** identical to the one that would be deleted by this instruction, +** skip the delete and set register P3 to NULL. +** +** Raise an SQLITE_CORRUPT_INDEX error if no matching index entry is found +** and not in writable_schema mode. */ case OP_IdxDelete: { VdbeCursor *pC; @@ -99925,8 +103073,8 @@ case OP_IdxDelete: { int res; UnpackedRecord r; - assert( pOp->p3>0 ); - assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 ); + assert( pOp->p5>0 ); + assert( pOp->p2>0 && pOp->p2+pOp->p5<=(p->nMem+1 - p->nCursor)+1 ); assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; assert( pC!=0 ); @@ -99935,18 +103083,34 @@ case OP_IdxDelete: { pCrsr = pC->uc.pCursor; assert( pCrsr!=0 ); r.pKeyInfo = pC->pKeyInfo; - r.nField = (u16)pOp->p3; + r.nField = pOp->p5; r.default_rc = 0; r.aMem = &aMem[pOp->p2]; rc = sqlite3BtreeIndexMoveto(pCrsr, &r, &res); if( rc ) goto abort_due_to_error; - if( res==0 ){ - rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE); + if( res!=0 ){ + rc = sqlite3VdbeFindIndexKey(pCrsr, pOp->p4.pIdx, &r, &res, 0); + if( rc!=SQLITE_OK ) goto abort_due_to_error; + if( res!=0 ){ + if( !sqlite3WritableSchema(db) ){ + rc = sqlite3ReportError( + SQLITE_CORRUPT_INDEX, __LINE__, "index corruption"); + goto abort_due_to_error; + } + pC->cacheStatus = CACHE_STALE; + pC->seekResult = 0; + break; + } + } + + if( pOp->p3 && vdbeIndexKeyCompare(pCrsr, &aMem[pOp->p3], &rc) ){ if( rc ) goto abort_due_to_error; - }else if( pOp->p5 && !sqlite3WritableSchema(db) ){ - rc = sqlite3ReportError(SQLITE_CORRUPT_INDEX, __LINE__, "index corruption"); - goto abort_due_to_error; + sqlite3VdbeMemSetNull(&aMem[pOp->p3]); + break; } + + rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE); + if( rc ) goto abort_due_to_error; assert( pC->deferredMoveto==0 ); pC->cacheStatus = CACHE_STALE; pC->seekResult = 0; @@ -100018,6 +103182,11 @@ case OP_IdxRowid: { /* out2, ncycle */ assert( pTabCur->eCurType==CURTYPE_BTREE ); assert( pTabCur->uc.pCursor!=0 ); assert( pTabCur->isTable ); +#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG) + assert( + sqlite3BtreeCursorHintTblCsr(pC->uc.pCursor)==pTabCur->uc.pCursor + ); +#endif pTabCur->nullRow = 0; pTabCur->movetoTarget = rowid; pTabCur->deferredMoveto = 1; @@ -100378,12 +103547,19 @@ case OP_SqlExec: { break; } -/* Opcode: ParseSchema P1 * * P4 * +/* Opcode: ParseSchema P1 * * P4 P5 ** ** Read and parse all entries from the schema table of database P1 ** that match the WHERE clause P4. If P4 is a NULL pointer, then the ** entire schema for P1 is reparsed. ** +** When P4 is NULL, the P5 value is used as the mFlags argument +** to sqlite3InitOne(). In other words, P5 should be a mask composed +** of INITFLAG_* values. +** +** The P4==0 case is only used by ALTER TABLE and P5!=0 for all such +** cases. For uses other than ALTER TABLE, P4<>0 and P5==0. +** ** This opcode invokes the parser to create a new virtual machine, ** then runs the new virtual machine. It is thus a re-entrant opcode. */ @@ -100411,6 +103587,7 @@ case OP_ParseSchema: { #ifndef SQLITE_OMIT_ALTERTABLE if( pOp->p4.z==0 ){ + assert( pOp->p5!=0 ); sqlite3SchemaClear(db->aDb[iDb].pSchema); db->mDbFlags &= ~DBFLAG_SchemaKnownOk; rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5); @@ -100419,6 +103596,7 @@ case OP_ParseSchema: { }else #endif { + assert( pOp->p5==0 ); zSchema = LEGACY_SCHEMA_TABLE; initData.db = db; initData.iDb = iDb; @@ -100573,6 +103751,58 @@ case OP_IntegrityCk: { sqlite3VdbeChangeEncoding(pIn1, encoding); goto check_for_interrupt; } + +/* Opcode: IFindKey P1 P2 P3 P4 * +** +** This instruction always follows an OP_Found with the same P1, P2 and P3 +** values as this instruction and a non-zero P4 value. The P4 value to +** this opcode is of type P4_INDEX and contains a pointer to the Index +** object of for the index being searched. +** +** This opcode uses sqlite3VdbeFindIndexKey() to search around the current +** cursor location for an index key that exactly matches all fields that +** are not indexed expressions or references to VIRTUAL generated columns, +** and either exactly match or are real numbers that are within 2 ULPs of +** each other if the don't match. +** +** To put it another way, this opcode looks for nearby index entries that +** are very close to the search key, but which might have small differences +** in floating-point values that come via an expression. +** +** If no nearby alternative entry is found in cursor P1, then jump to P2. +** But if a close match is found, fall through. +** +** This opcode is used by PRAGMA integrity_check to help distinguish +** between truely corrupt indexes and expression indexes that are holding +** floating-point values that are off by one or two ULPs. +*/ +case OP_IFindKey: { /* jump, in3 */ + VdbeCursor *pC; + int res; + UnpackedRecord r; + + assert( pOp[-1].opcode==OP_Found ); + assert( pOp[-1].p1==pOp->p1 ); + assert( pOp[-1].p3==pOp->p3 ); + pC = p->apCsr[pOp->p1]; + assert( pOp->p4type==P4_INDEX ); + assert( pC->eCurType==CURTYPE_BTREE ); + assert( pC->uc.pCursor!=0 ); + assert( pC->isTable==0 ); + + memset(&r, 0, sizeof(r)); + r.aMem = &aMem[pOp->p3]; + r.nField = pOp->p4.pIdx->nColumn; + r.pKeyInfo = pC->pKeyInfo; + + rc = sqlite3VdbeFindIndexKey(pC->uc.pCursor, pOp->p4.pIdx, &r, &res, 1); + if( rc || res!=0 ){ + rc = SQLITE_OK; + goto jump_to_p2; + } + pC->nullRow = 0; + break; +}; #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ /* Opcode: RowSetAdd P1 P2 * * * @@ -100697,7 +103927,7 @@ case OP_RowSetTest: { /* jump, in1, in3 */ */ case OP_Program: { /* jump0 */ int nMem; /* Number of memory registers for sub-program */ - int nByte; /* Bytes of runtime space required for sub-program */ + i64 nByte; /* Bytes of runtime space required for sub-program */ Mem *pRt; /* Register to allocate runtime space */ Mem *pMem; /* Used to iterate through memory cells */ Mem *pEnd; /* Last memory cell in new array */ @@ -100728,7 +103958,7 @@ case OP_Program: { /* jump0 */ if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){ rc = SQLITE_ERROR; - sqlite3VdbeError(p, "too many levels of trigger recursion"); + sqlite3VdbeError(p, "triggers nested too deep"); goto abort_due_to_error; } @@ -100748,7 +103978,7 @@ case OP_Program: { /* jump0 */ nByte = ROUND8(sizeof(VdbeFrame)) + nMem * sizeof(Mem) + pProgram->nCsr * sizeof(VdbeCursor*) - + (pProgram->nOp + 7)/8; + + (7 + (i64)pProgram->nOp)/8; pFrame = sqlite3DbMallocZero(db, nByte); if( !pFrame ){ goto no_mem; @@ -100756,7 +103986,7 @@ case OP_Program: { /* jump0 */ sqlite3VdbeMemRelease(pRt); pRt->flags = MEM_Blob|MEM_Dyn; pRt->z = (char*)pFrame; - pRt->n = nByte; + pRt->n = (int)nByte; pRt->xDel = sqlite3VdbeFrameMemDel; pFrame->v = p; @@ -100855,12 +104085,14 @@ case OP_Param: { /* out2 */ ** statement counter is incremented (immediate foreign key constraints). */ case OP_FkCounter: { - if( db->flags & SQLITE_DeferFKs ){ - db->nDeferredImmCons += pOp->p2; - }else if( pOp->p1 ){ + if( pOp->p1 ){ db->nDeferredCons += pOp->p2; }else{ - p->nFkConstraint += pOp->p2; + if( db->flags & SQLITE_DeferFKs ){ + db->nDeferredImmCons += pOp->p2; + }else{ + p->nFkConstraint += pOp->p2; + } } break; } @@ -101075,7 +104307,7 @@ case OP_AggStep: { ** ** Note: We could avoid this by using a regular memory cell from aMem[] for ** the accumulator, instead of allocating one here. */ - nAlloc = ROUND8P( sizeof(pCtx[0]) + (n-1)*sizeof(sqlite3_value*) ); + nAlloc = ROUND8P( SZ_CONTEXT(n) ); pCtx = sqlite3DbMallocRawNN(db, nAlloc + sizeof(Mem)); if( pCtx==0 ) goto no_mem; pCtx->pOut = (Mem*)((u8*)pCtx + nAlloc); @@ -101246,6 +104478,7 @@ case OP_Checkpoint: { || pOp->p2==SQLITE_CHECKPOINT_FULL || pOp->p2==SQLITE_CHECKPOINT_RESTART || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE + || pOp->p2==SQLITE_CHECKPOINT_NOOP ); rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]); if( rc ){ @@ -101581,7 +104814,14 @@ case OP_VOpen: { /* ncycle */ const sqlite3_module *pModule; assert( p->bIsReader ); - pCur = 0; + pCur = p->apCsr[pOp->p1]; + if( pCur!=0 + && ALWAYS( pCur->eCurType==CURTYPE_VTAB ) + && ALWAYS( pCur->uc.pVCur->pVtab==pOp->p4.pVtab->pVtab ) + ){ + /* This opcode is a no-op if the cursor is already open */ + break; + } pVCur = 0; pVtab = pOp->p4.pVtab->pVtab; if( pVtab==0 || NEVER(pVtab->pModule==0) ){ @@ -101735,6 +104975,7 @@ case OP_VFilter: { /* jump, ncycle */ /* Invoke the xFilter method */ apArg = p->apArg; + assert( nArg<=p->napArg ); for(i = 0; i<nArg; i++){ apArg[i] = &pArgc[i+1]; } @@ -101945,6 +105186,7 @@ case OP_VUpdate: { u8 vtabOnConflict = db->vtabOnConflict; apArg = p->apArg; pX = &aMem[pOp->p3]; + assert( nArg<=p->napArg ); for(i=0; i<nArg; i++){ assert( memIsValid(pX) ); memAboutToChange(p, pX); @@ -102327,23 +105569,37 @@ case OP_Init: { /* jump0 */ } #ifdef SQLITE_ENABLE_CURSOR_HINTS -/* Opcode: CursorHint P1 * * P4 * +/* Opcode: CursorHint P1 * P3 P4 * ** -** Provide a hint to cursor P1 that it only needs to return rows that -** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer -** to values currently held in registers. TK_COLUMN terms in the P4 +** Provide a hint to cursor P1. +** +** If P4 is of type P4_EXPR, then the hint is that the cursor need only return +** rows that satisfy the Expr in P4. TK_REGISTER terms in the P4 expression +** refer to values currently held in registers. TK_COLUMN terms in the P4 ** expression refer to columns in the b-tree to which cursor P1 is pointing. +** P3 is ignore in this case. +** +** Or, if P4 is P4_NOTUSED, then the hint is that cursor P1 is an index cursor +** used to drive table cursor P3. In other words, that this VM may execute +** OP_DeferredSeek instructions to lazily position P3 based on current +** position of P1. */ case OP_CursorHint: { VdbeCursor *pC; + pC = p->apCsr[pOp->p1]; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); - assert( pOp->p4type==P4_EXPR ); - pC = p->apCsr[pOp->p1]; + if( pC ){ assert( pC->eCurType==CURTYPE_BTREE ); - sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE, - pOp->p4.pExpr, aMem); + if( pOp->p4type==P4_EXPR ){ + sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE, + pOp->p4.pExpr, aMem); + }else if( p->apCsr[pOp->p3] ){ + sqlite3BtreeCursorHint( + pC->uc.pCursor, BTREE_HINT_TABLECURSOR, p->apCsr[pOp->p3]->uc.pCursor + ); + } } break; } @@ -102521,8 +105777,7 @@ default: { /* This is really OP_Noop, OP_Explain */ p->rc = rc; sqlite3SystemError(db, rc); testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(rc, "statement aborts at %d: [%s] %s", - (int)(pOp - aOp), p->zSql, p->zErrMsg); + sqlite3VdbeLogAbort(p, rc, pOp, aOp); if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p); if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db); if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){ @@ -102731,6 +105986,7 @@ SQLITE_API int sqlite3_blob_open( char *zErr = 0; Table *pTab; Incrblob *pBlob = 0; + int iDb; Parse sParse; #ifdef SQLITE_ENABLE_API_ARMOR @@ -102776,7 +106032,10 @@ SQLITE_API int sqlite3_blob_open( sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable); } #endif - if( !pTab ){ + if( pTab==0 + || ((iDb = sqlite3SchemaToIndex(db, pTab->pSchema))==1 && + sqlite3OpenTempDatabase(&sParse)) + ){ if( sParse.zErrMsg ){ sqlite3DbFree(db, zErr); zErr = sParse.zErrMsg; @@ -102787,15 +106046,11 @@ SQLITE_API int sqlite3_blob_open( goto blob_open_out; } pBlob->pTab = pTab; - pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName; + pBlob->zDb = db->aDb[iDb].zDbSName; /* Now search pTab for the exact column. */ - for(iCol=0; iCol<pTab->nCol; iCol++) { - if( sqlite3StrICmp(pTab->aCol[iCol].zCnName, zColumn)==0 ){ - break; - } - } - if( iCol==pTab->nCol ){ + iCol = sqlite3ColumnIndex(pTab, zColumn); + if( iCol<0 ){ sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn); rc = SQLITE_ERROR; @@ -102875,7 +106130,6 @@ SQLITE_API int sqlite3_blob_open( {OP_Halt, 0, 0, 0}, /* 5 */ }; Vdbe *v = (Vdbe *)pBlob->pStmt; - int iDb = sqlite3SchemaToIndex(db, pTab->pSchema); VdbeOp *aOp; sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag, @@ -102984,7 +106238,7 @@ static int blobReadWrite( int iOffset, int (*xCall)(BtCursor*, u32, u32, void*) ){ - int rc; + int rc = SQLITE_OK; Incrblob *p = (Incrblob *)pBlob; Vdbe *v; sqlite3 *db; @@ -103024,17 +106278,32 @@ static int blobReadWrite( ** using the incremental-blob API, this works. For the sessions module ** anyhow. */ - sqlite3_int64 iKey; - iKey = sqlite3BtreeIntegerKey(p->pCsr); - assert( v->apCsr[0]!=0 ); - assert( v->apCsr[0]->eCurType==CURTYPE_BTREE ); - sqlite3VdbePreUpdateHook( - v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1, p->iCol - ); + if( sqlite3BtreeCursorIsValidNN(p->pCsr)==0 ){ + /* If the cursor is not currently valid, try to reseek it. This + ** always either fails or finds the correct row - the cursor will + ** have been marked permanently CURSOR_INVALID if the open row has + ** been deleted. */ + int bDiff = 0; + rc = sqlite3BtreeCursorRestore(p->pCsr, &bDiff); + assert( bDiff==0 || sqlite3BtreeCursorIsValidNN(p->pCsr)==0 ); + } + if( sqlite3BtreeCursorIsValidNN(p->pCsr) ){ + sqlite3_int64 iKey; + iKey = sqlite3BtreeIntegerKey(p->pCsr); + assert( v->apCsr[0]!=0 ); + assert( v->apCsr[0]->eCurType==CURTYPE_BTREE ); + sqlite3VdbePreUpdateHook( + v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1, p->iCol + ); + } + } + if( rc==SQLITE_OK ){ + rc = xCall(p->pCsr, iOffset+p->iOffset, n, z); } +#else + rc = xCall(p->pCsr, iOffset+p->iOffset, n, z); #endif - rc = xCall(p->pCsr, iOffset+p->iOffset, n, z); sqlite3BtreeLeaveCursor(p->pCsr); if( rc==SQLITE_ABORT ){ sqlite3VdbeFinalize(v); @@ -103423,6 +106692,7 @@ struct SortSubtask { SorterCompare xCompare; /* Compare function to use */ SorterFile file; /* Temp file for level-0 PMAs */ SorterFile file2; /* Space for other PMAs */ + u64 nSpill; /* Total bytes written by this task */ }; @@ -103453,11 +106723,15 @@ struct VdbeSorter { u8 iPrev; /* Previous thread used to flush PMA */ u8 nTask; /* Size of aTask[] array */ u8 typeMask; - SortSubtask aTask[1]; /* One or more subtasks */ + SortSubtask aTask[FLEXARRAY]; /* One or more subtasks */ }; +/* Size (in bytes) of a VdbeSorter object that works with N or fewer subtasks */ +#define SZ_VDBESORTER(N) (offsetof(VdbeSorter,aTask)+(N)*sizeof(SortSubtask)) + #define SORTER_TYPE_INTEGER 0x01 #define SORTER_TYPE_TEXT 0x02 +#define SORTER_TYPE_REAL 0x04 /* ** An instance of the following object is used to read records out of a @@ -103540,6 +106814,7 @@ struct PmaWriter { int iBufEnd; /* Last byte of buffer to write */ i64 iWriteOff; /* Offset of start of buffer in file */ sqlite3_file *pFd; /* File handle to write to */ + u64 nPmaSpill; /* Total number of bytes written */ }; /* @@ -103884,7 +107159,7 @@ static int vdbeSorterCompareTail( ){ UnpackedRecord *r2 = pTask->pUnpacked; if( *pbKey2Cached==0 ){ - sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2); + sqlite3VdbeRecordUnpack(nKey2, pKey2, r2); *pbKey2Cached = 1; } return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1); @@ -103911,7 +107186,7 @@ static int vdbeSorterCompare( ){ UnpackedRecord *r2 = pTask->pUnpacked; if( !*pbKey2Cached ){ - sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2); + sqlite3VdbeRecordUnpack(nKey2, pKey2, r2); *pbKey2Cached = 1; } return sqlite3VdbeRecordCompare(nKey1, pKey1, r2); @@ -103951,6 +107226,7 @@ static int vdbeSorterCompareText( ); } }else{ + assert( pTask->pSorter->pKeyInfo->aSortFlags!=0 ); assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) ); if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){ res = res * -1; @@ -104014,6 +107290,7 @@ static int vdbeSorterCompareInt( } } + assert( pTask->pSorter->pKeyInfo->aSortFlags!=0 ); if( res==0 ){ if( pTask->pSorter->pKeyInfo->nKeyField>1 ){ res = vdbeSorterCompareTail( @@ -104028,6 +107305,150 @@ static int vdbeSorterCompareInt( return res; } +/* Helper function for vdbeSorterCompareReal(). +** +** The first elements of both pKey1 and pKey2 have been decoded into double +** values r1 and r2. Do the comparison between those keys and return the +** result. If r1==r2, break the tie with a comparison of subsequent elements +** from each key. +*/ +static int vdbeSorterFinishRealCompare( + SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ + int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ + const void *pKey1, int nKey1, /* Left side of comparison */ + const void *pKey2, int nKey2, /* Right side of comparison */ + double r1, /* REAL value of first element of pKey1 */ + double r2 /* REAL value of first element of pKey2 */ +){ + int res; + if( r1<r2 ){ + res = -1; + }else if( r1>r2 ){ + res = +1; + }else{ + res = 0; + } + assert( pTask->pSorter->pKeyInfo->aSortFlags!=0 ); + if( res==0 ){ + if( pTask->pSorter->pKeyInfo->nKeyField>1 ){ + res = vdbeSorterCompareTail( + pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2 + ); + } + }else if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){ + assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) ); + res = res * -1; + } + return res; +} + +/* Helper function for vdbeSorterCompareReal(). +** +** Buffer p[] is a record where the first term is guaranteed to be either +** a floating-point value, or an integer stand-in for a floating point +** value (a MEM_IntReal). Whatever its format, extract the value and +** return it. +*/ +static double vdbeSorterGetReal(const u8 *p){ + double r; /* the return value */ + + assert( p[0]<0x80 ); /* 1-byte headers: nAllField<13 */ + assert( p[1]>0 && p[1]<10 ); /* first fields proven numeric */ + + if( p[1]==7 ){ + u64 x = sqlite3Get8byte(p + p[0]); + swapMixedEndianFloat(x); + assert( !IsNaN(x) ); + memcpy(&r, &x, sizeof(r)); + }else{ + Mem m; + m.u.i = 0; + sqlite3VdbeSerialGet(p + p[0], p[1], &m); + assert( m.flags==MEM_Int ); + r = (double)m.u.i; + } + return r; +} + +/* Helper function for vdbeSorterCompareReal() +** +** This routine handles the case of comparing two floating-point values +** where one or both of the floating-point are represented by integers. +** In other words, where one both is an MEM_RealInt. +** +** This subroutine is factored out from vdbeSorterCompareReal() for +** efficiency. If inlined into vdbeSorterCompareReal(), this routine +** will use extra stack space and consume CPU cycles setting up and +** breaking down that stack space, even if in the common case where +** this path is not used. +*/ +static SQLITE_NOINLINE int vdbeSorterCompareRealInt( + SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ + int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ + const void *pKey1, int nKey1, /* Left side of comparison */ + const void *pKey2, int nKey2 /* Right side of comparison */ +){ + const u8 * const p1 = (const u8 * const)pKey1; + const u8 * const p2 = (const u8 * const)pKey2; + if( p1[1]==6 || p2[1]==6 ){ + /* 64-bit integer values cannot be represented exactly by a double so + ** must be handled by the generalized comparison function. */ + return vdbeSorterCompare(pTask, + pbKey2Cached, pKey1,nKey1, pKey2,nKey2); + }else{ + double r1 = vdbeSorterGetReal(p1); + double r2 = vdbeSorterGetReal(p2); + return vdbeSorterFinishRealCompare(pTask,pbKey2Cached, + pKey1,nKey1,pKey2,nKey2,r1,r2); + } +} + +/* +** Comparison function optimized for the case where the first term +** of both keys are either MEM_Real or MEM_RealInt. +** +** See also vdbeSorterCompareInt() for MEM_Int values and +** vdbeSorterCompareText() for MEM_Str values. The general +** case is vdbeSorterCompare() which handles anything, but is slower. +*/ +static int vdbeSorterCompareReal( + SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ + int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ + const void *pKey1, int nKey1, /* Left side of comparison */ + const void *pKey2, int nKey2 /* Right side of comparison */ +){ + const u8*const p1 = (const u8*const)pKey1; /* Left key record */ + const u8*const p2 = (const u8*const)pKey2; /* Right key record */ + u64 x; /* A real value stored as an integer */ + double r1; /* First element of pKey1 */ + double r2; /* First element of pKey2 */ + + assert( p1[0]<0x80 && p2[0]<0x80 ); /* 1-byte headers: nAllField<13 */ + assert( p1[1]>0 && p1[1]<10 ); /* first field guaranteed numeric */ + assert( p2[1]>0 && p2[1]<10 ); /* first field guaranteed numeric */ + + if( p1[1]!=7 || p2[1]!=7 ){ + /* One or both floating point values are stored as INTEGER. This might + ** be because of the MEM_RealInt encoding. Try to optimize that case. */ + return vdbeSorterCompareRealInt(pTask, + pbKey2Cached, pKey1,nKey1, pKey2,nKey2 + ); + } + assert( p1[0]<=nKey1-8 && p2[0]<=nKey2-8 ); + + x = sqlite3Get8byte(p1 + *p1); + swapMixedEndianFloat(x); + assert( !IsNaN(x) ); + memcpy(&r1, &x, sizeof(r1)); + x = sqlite3Get8byte(p2 + *p2); + swapMixedEndianFloat(x); + assert( !IsNaN(x) ); + memcpy(&r2, &x, sizeof(r2)); + return vdbeSorterFinishRealCompare(pTask, + pbKey2Cached, pKey1,nKey1, pKey2,nKey2, r1, r2 + ); +} + /* ** Initialize the temporary index cursor just opened as a sorter cursor. ** @@ -104057,7 +107478,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit( VdbeSorter *pSorter; /* The new sorter */ KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */ int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */ - int sz; /* Size of pSorter in bytes */ + i64 sz; /* Size of pSorter in bytes */ int rc = SQLITE_OK; #if SQLITE_MAX_WORKER_THREADS==0 # define nWorker 0 @@ -104085,8 +107506,11 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit( assert( pCsr->pKeyInfo ); assert( !pCsr->isEphemeral ); assert( pCsr->eCurType==CURTYPE_SORTER ); - szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*); - sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask); + assert( sizeof(KeyInfo) + UMXV(pCsr->pKeyInfo->nKeyField)*sizeof(CollSeq*) + < 0x7fffffff ); + assert( pCsr->pKeyInfo->nKeyField<=pCsr->pKeyInfo->nAllField ); + szKeyInfo = SZ_KEYINFO(pCsr->pKeyInfo->nAllField); + sz = SZ_VDBESORTER(nWorker+1); pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo); pCsr->uc.pSorter = pSorter; @@ -104099,7 +107523,12 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit( pKeyInfo->db = 0; if( nField && nWorker==0 ){ pKeyInfo->nKeyField = nField; + assert( nField<=pCsr->pKeyInfo->nAllField ); } + /* It is OK that pKeyInfo reuses the aSortFlags field from pCsr->pKeyInfo, + ** since the pCsr->pKeyInfo->aSortFlags[] array is invariant and lives + ** longer that pSorter. */ + assert( pKeyInfo->aSortFlags==pCsr->pKeyInfo->aSortFlags ); sqlite3BtreeEnter(pBt); pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(pBt); sqlite3BtreeLeave(pBt); @@ -104142,7 +107571,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit( && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl) && (pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL)==0 ){ - pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT; + pSorter->typeMask = SORTER_TYPE_INTEGER|SORTER_TYPE_TEXT|SORTER_TYPE_REAL; } } @@ -104298,7 +107727,7 @@ static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){ */ static MergeEngine *vdbeMergeEngineNew(int nReader){ int N = 2; /* Smallest power of two >= nReader */ - int nByte; /* Total bytes of space to allocate */ + i64 nByte; /* Total bytes of space to allocate */ MergeEngine *pNew; /* Pointer to allocated object to return */ assert( nReader<=SORTER_MAX_MERGE_COUNT ); @@ -104388,6 +107817,12 @@ SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){ assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; if( pSorter ){ + /* Increment db->nSpill by the total number of bytes of data written + ** to temp files by this sort operation. */ + int ii; + for(ii=0; ii<pSorter->nTask; ii++){ + db->nSpill += pSorter->aTask[ii].nSpill; + } sqlite3VdbeSorterReset(db, pSorter); sqlite3_free(pSorter->list.aMemory); sqlite3DbFree(db, pSorter); @@ -104508,10 +107943,12 @@ static SorterRecord *vdbeSorterMerge( ** sorter object passed as the only argument. */ static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){ - if( p->typeMask==SORTER_TYPE_INTEGER ){ + if( p->typeMask & SORTER_TYPE_INTEGER ){ return vdbeSorterCompareInt; - }else if( p->typeMask==SORTER_TYPE_TEXT ){ + }else if( p->typeMask & SORTER_TYPE_TEXT ){ return vdbeSorterCompareText; + }else if( p->typeMask & SORTER_TYPE_REAL ){ + return vdbeSorterCompareReal; } return vdbeSorterCompare; } @@ -104550,6 +107987,10 @@ static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){ p->u.pNext = 0; for(i=0; aSlot[i]; i++){ p = vdbeSorterMerge(pTask, p, aSlot[i]); + /* ,--Each aSlot[] holds twice as much as the previous. So we cannot use + ** | up all 64 aSlots[] with only a 64-bit address space. + ** v */ + assert( i<ArraySize(aSlot) ); aSlot[i] = 0; } aSlot[i] = p; @@ -104609,6 +108050,7 @@ static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){ &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, p->iWriteOff + p->iBufStart ); + p->nPmaSpill += (p->iBufEnd - p->iBufStart); p->iBufStart = p->iBufEnd = 0; p->iWriteOff += p->nBuffer; } @@ -104625,17 +108067,20 @@ static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){ ** required. Otherwise, return an SQLite error code. ** ** Before returning, set *piEof to the offset immediately following the -** last byte written to the file. +** last byte written to the file. Also, increment (*pnSpill) by the total +** number of bytes written to the file. */ -static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){ +static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof, u64 *pnSpill){ int rc; if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){ p->eFWErr = sqlite3OsWrite(p->pFd, &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, p->iWriteOff + p->iBufStart ); + p->nPmaSpill += (p->iBufEnd - p->iBufStart); } *piEof = (p->iWriteOff + p->iBufEnd); + *pnSpill += p->nPmaSpill; sqlite3_free(p->aBuffer); rc = p->eFWErr; memset(p, 0, sizeof(PmaWriter)); @@ -104715,7 +108160,7 @@ static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){ if( pList->aMemory==0 ) sqlite3_free(p); } pList->pList = p; - rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof); + rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof, &pTask->nSpill); } vdbeSorterWorkDebug(pTask, "exit"); @@ -104901,8 +108346,12 @@ SQLITE_PRIVATE int sqlite3VdbeSorterWrite( assert( pCsr->eCurType==CURTYPE_SORTER ); pSorter = pCsr->uc.pSorter; getVarint32NR((const u8*)&pVal->z[1], t); - if( t>0 && t<10 && t!=7 ){ - pSorter->typeMask &= SORTER_TYPE_INTEGER; + if( t>0 && t<10 ){ + if( t==7 ){ + pSorter->typeMask &= SORTER_TYPE_REAL; + }else{ + pSorter->typeMask &= (SORTER_TYPE_INTEGER|SORTER_TYPE_REAL); + } }else if( t>10 && (t & 0x01) ){ pSorter->typeMask &= SORTER_TYPE_TEXT; }else{ @@ -105029,7 +108478,7 @@ static int vdbeIncrPopulate(IncrMerger *pIncr){ rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy); } - rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof); + rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof, &pTask->nSpill); if( rc==SQLITE_OK ) rc = rc2; vdbeSorterPopulateDebug(pTask, "exit"); return rc; @@ -105875,7 +109324,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterCompare( assert( r2->nField==nKeyCol ); pKey = vdbeSorterRowkey(pSorter, &nKey); - sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2); + sqlite3VdbeRecordUnpack(nKey, pKey, r2); for(i=0; i<nKeyCol; i++){ if( r2->aMem[i].flags & MEM_Null ){ *pRes = -1; @@ -107341,7 +110790,6 @@ static int lookupName( Schema *pSchema = 0; /* Schema of the expression */ int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */ Table *pTab = 0; /* Table holding the row */ - Column *pCol; /* A column of pTab */ ExprList *pFJMatch = 0; /* Matches for FULL JOIN .. USING */ const char *zCol = pRight->u.zToken; @@ -107392,7 +110840,6 @@ static int lookupName( if( pSrcList ){ for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){ - u8 hCol; pTab = pItem->pSTab; assert( pTab!=0 && pTab->zName!=0 ); assert( pTab->nCol>0 || pParse->nErr ); @@ -107422,10 +110869,13 @@ static int lookupName( if( cnt>0 ){ if( pItem->fg.isUsing==0 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0 + || pMatch==pItem ){ /* Two or more tables have the same column name which is - ** not joined by USING. This is an error. Signal as much - ** by clearing pFJMatch and letting cnt go above 1. */ + ** not joined by USING. Or, a single table has two columns + ** that match a USING term (if pMatch==pItem). These are both + ** "ambiguous column name" errors. Signal as much by clearing + ** pFJMatch and letting cnt go above 1. */ sqlite3ExprListDelete(db, pFJMatch); pFJMatch = 0; }else @@ -107480,43 +110930,38 @@ static int lookupName( sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab); } } - hCol = sqlite3StrIHash(zCol); - for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){ - if( pCol->hName==hCol - && sqlite3StrICmp(pCol->zCnName, zCol)==0 - ){ - if( cnt>0 ){ - if( pItem->fg.isUsing==0 - || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0 - ){ - /* Two or more tables have the same column name which is - ** not joined by USING. This is an error. Signal as much - ** by clearing pFJMatch and letting cnt go above 1. */ - sqlite3ExprListDelete(db, pFJMatch); - pFJMatch = 0; - }else - if( (pItem->fg.jointype & JT_RIGHT)==0 ){ - /* An INNER or LEFT JOIN. Use the left-most table */ - continue; - }else - if( (pItem->fg.jointype & JT_LEFT)==0 ){ - /* A RIGHT JOIN. Use the right-most table */ - cnt = 0; - sqlite3ExprListDelete(db, pFJMatch); - pFJMatch = 0; - }else{ - /* For a FULL JOIN, we must construct a coalesce() func */ - extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn); - } - } - cnt++; - pMatch = pItem; - /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ - pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; - if( pItem->fg.isNestedFrom ){ - sqlite3SrcItemColumnUsed(pItem, j); + j = sqlite3ColumnIndex(pTab, zCol); + if( j>=0 ){ + if( cnt>0 ){ + if( pItem->fg.isUsing==0 + || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0 + ){ + /* Two or more tables have the same column name which is + ** not joined by USING. This is an error. Signal as much + ** by clearing pFJMatch and letting cnt go above 1. */ + sqlite3ExprListDelete(db, pFJMatch); + pFJMatch = 0; + }else + if( (pItem->fg.jointype & JT_RIGHT)==0 ){ + /* An INNER or LEFT JOIN. Use the left-most table */ + continue; + }else + if( (pItem->fg.jointype & JT_LEFT)==0 ){ + /* A RIGHT JOIN. Use the right-most table */ + cnt = 0; + sqlite3ExprListDelete(db, pFJMatch); + pFJMatch = 0; + }else{ + /* For a FULL JOIN, we must construct a coalesce() func */ + extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn); } - break; + } + cnt++; + pMatch = pItem; + /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ + pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; + if( pItem->fg.isNestedFrom ){ + sqlite3SrcItemColumnUsed(pItem, j); } } if( 0==cnt && VisibleRowid(pTab) ){ @@ -107606,23 +111051,18 @@ static int lookupName( if( pTab ){ int iCol; - u8 hCol = sqlite3StrIHash(zCol); pSchema = pTab->pSchema; cntTab++; - for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){ - if( pCol->hName==hCol - && sqlite3StrICmp(pCol->zCnName, zCol)==0 - ){ - if( iCol==pTab->iPKey ){ - iCol = -1; - } - break; + iCol = sqlite3ColumnIndex(pTab, zCol); + if( iCol>=0 ){ + if( pTab->iPKey==iCol ) iCol = -1; + }else{ + if( sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ + iCol = -1; + }else{ + iCol = pTab->nCol; } } - if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ - /* IMP: R-51414-32910 */ - iCol = -1; - } if( iCol<pTab->nCol ){ cnt++; pMatch = 0; @@ -107810,7 +111250,7 @@ static int lookupName( ** cnt>1 means there were two or more matches. ** ** cnt==0 is always an error. cnt>1 is often an error, but might - ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING. + ** be multiple matches for a NATURAL OUTER JOIN or a OUTER JOIN USING. */ assert( pFJMatch==0 || cnt>0 ); assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) ); @@ -107830,6 +111270,7 @@ static int lookupName( pExpr->op = TK_FUNCTION; pExpr->u.zToken = "coalesce"; pExpr->x.pList = pFJMatch; + pExpr->affExpr = SQLITE_AFF_DEFER; cnt = 1; goto lookupname_end; }else{ @@ -107892,10 +111333,19 @@ static int lookupName( if( cnt==1 ){ assert( pNC!=0 ); #ifndef SQLITE_OMIT_AUTHORIZATION - if( pParse->db->xAuth - && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER) - ){ - sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); + if( db->xAuth ){ + if( pFJMatch ){ + assert( pExpr->op==TK_FUNCTION ); + assert( sqlite3_stricmp(pExpr->u.zToken,"coalesce")==0 ); + assert( pExpr->x.pList==pFJMatch ); + assert( pFJMatch->nExpr>0 ); + for(i=0; i<pFJMatch->nExpr; i++){ + assert( pFJMatch->a[i].pExpr->op==TK_COLUMN ); + sqlite3AuthRead(pParse,pFJMatch->a[i].pExpr,pSchema,pNC->pSrcList); + } + }else if( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ){ + sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); + } } #endif /* Increment the nRef value on all name contexts from TopNC up to @@ -107985,19 +111435,48 @@ static void notValidImpl( /* ** Expression p should encode a floating point value between 1.0 and 0.0. -** Return 1024 times this value. Or return -1 if p is not a floating point -** value between 1.0 and 0.0. +** Return 134,217,728 (2^27) times this value. Or return -1 if p is not +** a floating point value between 1.0 and 0.0. */ static int exprProbability(Expr *p){ double r = -1.0; if( p->op!=TK_FLOAT ) return -1; assert( !ExprHasProperty(p, EP_IntValue) ); - sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8); + sqlite3AtoF(p->u.zToken, &r); assert( r>=0.0 ); if( r>1.0 ) return -1; return (int)(r*134217728.0); } +/* +** Set the EP_SubtArg property on every expression inside of +** pList. If any subexpression is actually a subquery, then +** also set the EP_SubtArg property on the first result-set +** column of that subquery. +*/ +static SQLITE_NOINLINE void resolveSetExprSubtypeArg(ExprList *pList){ + int nn, ii; + nn = pList ? pList->nExpr : 0; + for(ii=0; ii<nn; ii++){ + Expr *pExpr = pList->a[ii].pExpr; + while( 1 /*exit-by-break*/ ){ + ExprSetProperty(pExpr, EP_SubtArg); + if( pExpr->op==TK_SELECT ){ + assert( ExprUseXSelect(pExpr) ); + assert( pExpr->x.pSelect!=0 ); + resolveSetExprSubtypeArg(pExpr->x.pSelect->pEList); + break; + } + if( pExpr->op==TK_UPLUS ){ + pExpr = pExpr->pLeft; + assert( pExpr!=0 ); + }else{ + break; + } + } + } +} + /* ** This routine is callback for sqlite3WalkExpr(). ** @@ -108242,10 +111721,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ if( (pDef->funcFlags & SQLITE_SUBTYPE) || ExprHasProperty(pExpr, EP_SubtArg) ){ - int ii; - for(ii=0; ii<n; ii++){ - ExprSetProperty(pList->a[ii].pExpr, EP_SubtArg); - } + resolveSetExprSubtypeArg(pList); } if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){ @@ -108261,13 +111737,12 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ ** sqlite_version() that might change over time cannot be used ** in an index or generated column. Curiously, they can be used ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all - ** all this. */ + ** allow this. */ sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr|NC_PartIdx|NC_GenCol, 0, pExpr); }else{ assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */ pExpr->op2 = pNC->ncFlags & NC_SelfRef; - if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL); } if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0 && pParse->nested==0 @@ -108276,13 +111751,19 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ /* Internal-use-only functions are disallowed unless the ** SQL is being compiled using sqlite3NestedParse() or ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be - ** used to activate internal functions for testing purposes */ - no_such_func = 1; + ** used to activate internal functions for testing purposes. + ** + ** The 2 value for no_such_func means that the function is + ** an internal-use-only function which should be treated as a + ** non-existant function for name resolution purposes. + */ + no_such_func = 2; pDef = 0; }else if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 && !IN_RENAME_OBJECT ){ + if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL); sqlite3ExprFunctionUsable(pParse, pExpr, pDef); } } @@ -108320,9 +111801,16 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ is_agg = 0; } #endif - else if( no_such_func && pParse->db->init.busy==0 + else if( no_such_func + && (pParse->db->init.busy==0 || + (no_such_func==2 && pParse->db->init.busy==2)) + /* Suppress "no such function" errors when reading + ** the sqlite_schema table. Except, do raise the error + ** if init.busy is 2, meaning the schema parse is due + ** to an ALTER TABLE ADD COLUMN statement, and the function + ** is an internal-use-only function (no_such_func==2). */ #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION - && pParse->explain==0 + && pParse->explain==0 #endif ){ sqlite3ErrorMsg(pParse, "no such function: %#T", pExpr); @@ -108417,11 +111905,13 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ return WRC_Prune; } #ifndef SQLITE_OMIT_SUBQUERY + case TK_EXISTS: case TK_SELECT: - case TK_EXISTS: testcase( pExpr->op==TK_EXISTS ); #endif case TK_IN: { testcase( pExpr->op==TK_IN ); + testcase( pExpr->op==TK_EXISTS ); + testcase( pExpr->op==TK_SELECT ); if( ExprUseXSelect(pExpr) ){ int nRef = pNC->nRef; testcase( pNC->ncFlags & NC_IsCheck ); @@ -108429,6 +111919,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){ testcase( pNC->ncFlags & NC_IdxExpr ); testcase( pNC->ncFlags & NC_GenCol ); assert( pExpr->x.pSelect ); + if( pExpr->op==TK_EXISTS ) pParse->bHasExists = 1; if( pNC->ncFlags & NC_SelfRef ){ notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr); }else{ @@ -108576,7 +112067,7 @@ static int resolveOrderByTermToExprList( int rc; /* Return code from subprocedures */ u8 savedSuppErr; /* Saved value of db->suppressErr */ - assert( sqlite3ExprIsInteger(pE, &i, 0)==0 ); + assert( sqlite3ExprIsInteger(pE, &i, 0, 0)==0 ); pEList = pSelect->pEList; /* Resolve all names in the ORDER BY term expression @@ -108675,7 +112166,7 @@ static int resolveCompoundOrderBy( if( pItem->fg.done ) continue; pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr); if( NEVER(pE==0) ) continue; - if( sqlite3ExprIsInteger(pE, &iCol, 0) ){ + if( sqlite3ExprIsInteger(pE, &iCol, 0, 0) ){ if( iCol<=0 || iCol>pEList->nExpr ){ resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE); return 1; @@ -108709,10 +112200,8 @@ static int resolveCompoundOrderBy( /* Convert the ORDER BY term into an integer column number iCol, ** taking care to preserve the COLLATE clause if it exists. */ if( !IN_RENAME_OBJECT ){ - Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); + Expr *pNew = sqlite3ExprInt32(db, iCol); if( pNew==0 ) return 1; - pNew->flags |= EP_IntValue; - pNew->u.iValue = iCol; if( pItem->pExpr==pE ){ pItem->pExpr = pNew; }else{ @@ -108860,7 +112349,7 @@ static int resolveOrderGroupBy( continue; } } - if( sqlite3ExprIsInteger(pE2, &iCol, 0) ){ + if( sqlite3ExprIsInteger(pE2, &iCol, 0, 0) ){ /* The ORDER BY term is an integer constant. Again, set the column ** number so that sqlite3ResolveOrderGroupBy() will convert the ** order-by term to a copy of the result-set expression */ @@ -109066,10 +112555,6 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ } #endif - /* The ORDER BY and GROUP BY clauses may not refer to terms in - ** outer queries - */ - sNC.pNext = 0; sNC.ncFlags |= NC_AllowAgg|NC_AllowWin; /* If this is a converted compound query, move the ORDER BY clause from @@ -109132,6 +112617,14 @@ static int resolveSelectStep(Walker *pWalker, Select *p){ return WRC_Abort; } + /* If the SELECT statement contains ON clauses that were moved into + ** the WHERE clause, go through and verify that none of the terms + ** in the ON clauses reference tables to the right of the ON clause. */ + if( (p->selFlags & SF_OnToWhere) ){ + sqlite3SelectCheckOnClauses(pParse, p); + if( pParse->nErr ) return WRC_Abort; + } + /* Advance to the next term of the compound */ p = p->pPrior; @@ -109336,20 +112829,25 @@ SQLITE_PRIVATE int sqlite3ResolveSelfReference( Expr *pExpr, /* Expression to resolve. May be NULL. */ ExprList *pList /* Expression list to resolve. May be NULL. */ ){ - SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ + SrcList *pSrc; /* Fake SrcList for pParse->pNewTable */ NameContext sNC; /* Name context for pParse->pNewTable */ int rc; + union { + SrcList sSrc; + u8 srcSpace[SZ_SRCLIST_1]; /* Memory space for the fake SrcList */ + } uSrc; assert( type==0 || pTab!=0 ); assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr || type==NC_GenCol || pTab==0 ); memset(&sNC, 0, sizeof(sNC)); - memset(&sSrc, 0, sizeof(sSrc)); + memset(&uSrc, 0, sizeof(uSrc)); + pSrc = &uSrc.sSrc; if( pTab ){ - sSrc.nSrc = 1; - sSrc.a[0].zName = pTab->zName; - sSrc.a[0].pSTab = pTab; - sSrc.a[0].iCursor = -1; + pSrc->nSrc = 1; + pSrc->a[0].zName = pTab->zName; + pSrc->a[0].pSTab = pTab; + pSrc->a[0].iCursor = -1; if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){ /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP ** schema elements */ @@ -109357,7 +112855,7 @@ SQLITE_PRIVATE int sqlite3ResolveSelfReference( } } sNC.pParse = pParse; - sNC.pSrcList = &sSrc; + sNC.pSrcList = pSrc; sNC.ncFlags = type | NC_IsDDL; if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc; if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList); @@ -109441,7 +112939,9 @@ SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr){ pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr ); } - if( op==TK_VECTOR ){ + if( op==TK_VECTOR + || (op==TK_FUNCTION && pExpr->affExpr==SQLITE_AFF_DEFER) + ){ assert( ExprUseXList(pExpr) ); return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr); } @@ -109539,23 +113039,29 @@ SQLITE_PRIVATE int sqlite3ExprDataType(const Expr *pExpr){ ** and the pExpr parameter is returned unchanged. */ SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken( - const Parse *pParse, /* Parsing context */ + Parse *pParse, /* Parsing context */ Expr *pExpr, /* Add the "COLLATE" clause to this expression */ const Token *pCollName, /* Name of collating sequence */ int dequote /* True to dequote pCollName */ ){ - if( pCollName->n>0 ){ + if( pCollName->n>0 && pParse->nErr==0 ){ Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote); + assert( pExpr!=0 ); if( pNew ){ pNew->pLeft = pExpr; pNew->flags |= EP_Collate|EP_Skip; +#if SQLITE_MAX_EXPR_DEPTH>0 + pNew->nHeight = pExpr->nHeight+1; + sqlite3ExprCheckHeight(pParse, pNew->nHeight); + testcase( pParse->nErr>0 ); +#endif pExpr = pNew; } } return pExpr; } SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString( - const Parse *pParse, /* Parsing context */ + Parse *pParse, /* Parsing context */ Expr *pExpr, /* Add the "COLLATE" clause to this expression */ const char *zC /* The collating sequence name */ ){ @@ -109634,7 +113140,9 @@ SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){ p = p->pLeft; continue; } - if( op==TK_VECTOR ){ + if( op==TK_VECTOR + || (op==TK_FUNCTION && p->affExpr==SQLITE_AFF_DEFER) + ){ assert( ExprUseXList(p) ); p = p->x.pList->a[0].pExpr; continue; @@ -109695,7 +113203,9 @@ SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){ SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){ CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1); CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2); - return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0; + assert( (pColl1==pColl2) == + (sqlite3_stricmp(pColl1->zName,pColl2->zName)==0) ); + return pColl1==pColl2; } /* @@ -109847,7 +113357,7 @@ static int codeCompare( p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, (void*)p4, P4_COLLSEQ); - sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5); + sqlite3VdbeChangeP5(pParse->pVdbe, (u16)p5); return addr; } @@ -110025,6 +113535,7 @@ static int exprVectorRegister( Expr *pVector, /* Vector to extract element from */ int iField, /* Field to extract from pVector */ int regSelect, /* First in array of registers */ + Expr *pTmp, /* Temporary space */ Expr **ppExpr, /* OUT: Expression element */ int *pRegFree /* OUT: Temp register to free */ ){ @@ -110036,8 +113547,17 @@ static int exprVectorRegister( } if( op==TK_SELECT ){ assert( ExprUseXSelect(pVector) ); - *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr; - return regSelect+iField; + /* Use the temporary expression node to wrap expression iField of the + ** sub-select in a TK_SELECT_COLUMN node. This causes the caller to + ** use the affinity of the expression in any comparison, but not the + ** collation sequence. */ + memset(pTmp, 0, sizeof(Expr)); + pTmp->op = TK_SELECT_COLUMN; + pTmp->pLeft = pVector; + pTmp->iColumn = iField; + pTmp->iTable = pVector->x.pSelect->pEList->nExpr; + *ppExpr = pTmp; + return regSelect+iField; } if( op==TK_VECTOR ){ assert( ExprUseXList(pVector) ); @@ -110104,11 +113624,12 @@ static void codeVectorCompare( for(i=0; 1 /*Loop exits by "break"*/; i++){ int regFree1 = 0, regFree2 = 0; Expr *pL = 0, *pR = 0; + Expr tmp1, tmp2; int r1, r2; assert( i>=0 && i<nLeft ); if( addrCmp ) sqlite3VdbeJumpHere(v, addrCmp); - r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1); - r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2); + r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &tmp1, &pL, &regFree1); + r2 = exprVectorRegister(pParse, pRight, i, regRight, &tmp2, &pR, &regFree2); addrCmp = sqlite3VdbeCurrentAddr(v); codeCompare(pParse, pL, pR, opx, r1, r2, addrDone, p5, isCommuted); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); @@ -110299,34 +113820,22 @@ SQLITE_PRIVATE Expr *sqlite3ExprAlloc( int dequote /* True to dequote */ ){ Expr *pNew; - int nExtra = 0; - int iValue = 0; + int nExtra = pToken ? pToken->n+1 : 0; assert( db!=0 ); - if( pToken ){ - if( op!=TK_INTEGER || pToken->z==0 - || sqlite3GetInt32(pToken->z, &iValue)==0 ){ - nExtra = pToken->n+1; /* tag-20240227-a */ - assert( iValue>=0 ); - } - } pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra); if( pNew ){ memset(pNew, 0, sizeof(Expr)); pNew->op = (u8)op; pNew->iAgg = -1; - if( pToken ){ - if( nExtra==0 ){ - pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse); - pNew->u.iValue = iValue; - }else{ - pNew->u.zToken = (char*)&pNew[1]; - assert( pToken->z!=0 || pToken->n==0 ); - if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n); - pNew->u.zToken[pToken->n] = 0; - if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){ - sqlite3DequoteExpr(pNew); - } + if( nExtra ){ + assert( pToken!=0 ); + pNew->u.zToken = (char*)&pNew[1]; + assert( pToken->z!=0 || pToken->n==0 ); + if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n); + pNew->u.zToken[pToken->n] = 0; + if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){ + sqlite3DequoteExpr(pNew); } } #if SQLITE_MAX_EXPR_DEPTH>0 @@ -110351,6 +113860,24 @@ SQLITE_PRIVATE Expr *sqlite3Expr( return sqlite3ExprAlloc(db, op, &x, 0); } +/* +** Allocate an expression for a 32-bit signed integer literal. +*/ +SQLITE_PRIVATE Expr *sqlite3ExprInt32(sqlite3 *db, int iVal){ + Expr *pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)); + if( pNew ){ + memset(pNew, 0, sizeof(Expr)); + pNew->op = TK_INTEGER; + pNew->iAgg = -1; + pNew->flags = EP_IntValue|EP_Leaf|(iVal?EP_IsTrue:EP_IsFalse); + pNew->u.iValue = iVal; +#if SQLITE_MAX_EXPR_DEPTH>0 + pNew->nHeight = 1; +#endif + } + return pNew; +} + /* ** Attach subtrees pLeft and pRight to the Expr node pRoot. ** @@ -110508,12 +114035,12 @@ SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){ return pLeft; }else{ u32 f = pLeft->flags | pRight->flags; - if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse))==EP_IsFalse + if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse|EP_HasFunc))==EP_IsFalse && !IN_RENAME_OBJECT ){ sqlite3ExprDeferredDelete(pParse, pLeft); sqlite3ExprDeferredDelete(pParse, pRight); - return sqlite3Expr(db, TK_INTEGER, "0"); + return sqlite3ExprInt32(db, 0); }else{ return sqlite3PExpr(pParse, TK_AND, pLeft, pRight); } @@ -110603,6 +114130,11 @@ SQLITE_PRIVATE void sqlite3ExprAddFunctionOrderBy( sqlite3ExprListDelete(db, pOrderBy); return; } + if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); + sqlite3ExprListDelete(db, pOrderBy); + return; + } pOB = sqlite3ExprAlloc(db, TK_ORDER, 0, 0); if( pOB==0 ){ @@ -110633,7 +114165,9 @@ SQLITE_PRIVATE void sqlite3ExprFunctionUsable( ){ assert( !IN_RENAME_OBJECT ); assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 ); - if( ExprHasProperty(pExpr, EP_FromDDL) ){ + if( ExprHasProperty(pExpr, EP_FromDDL) + || pParse->prepFlags & SQLITE_PREPARE_FROM_DDL + ){ if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0 || (pParse->db->flags & SQLITE_TrustedSchema)==0 ){ @@ -110707,6 +114241,8 @@ SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n if( x>pParse->nVar ){ pParse->nVar = (int)x; doAdd = 1; + }else if( x<SQLITE_VNBMC*64 ){ + doAdd = (pParse->aVnbmc[x>>6] & MASKBIT64(x&63))==0; }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){ doAdd = 1; } @@ -110723,6 +114259,9 @@ SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n } if( doAdd ){ pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x); + if( pParse->pVList!=0 && x<SQLITE_VNBMC*64 ){ + pParse->aVnbmc[x>>6] |= MASKBIT64(x&63); + } } } pExpr->iColumn = x; @@ -111106,7 +114645,7 @@ static Expr *exprDup( SQLITE_PRIVATE With *sqlite3WithDup(sqlite3 *db, With *p){ With *pRet = 0; if( p ){ - sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1); + sqlite3_int64 nByte = SZ_WITH(p->nCte); pRet = sqlite3DbMallocZero(db, nByte); if( pRet ){ int i; @@ -111217,7 +114756,6 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, const ExprList *p, int } pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName); pItem->fg = pOldItem->fg; - pItem->fg.done = 0; pItem->u = pOldItem->u; } return pNew; @@ -111234,11 +114772,9 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, const ExprList *p, int SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, const SrcList *p, int flags){ SrcList *pNew; int i; - int nByte; assert( db!=0 ); if( p==0 ) return 0; - nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0); - pNew = sqlite3DbMallocRawNN(db, nByte ); + pNew = sqlite3DbMallocRawNN(db, SZ_SRCLIST(p->nSrc) ); if( pNew==0 ) return 0; pNew->nSrc = pNew->nAlloc = p->nSrc; for(i=0; i<p->nSrc; i++){ @@ -111300,16 +114836,13 @@ SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, const IdList *p){ int i; assert( db!=0 ); if( p==0 ) return 0; - assert( p->eU4!=EU4_EXPR ); - pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew)+(p->nId-1)*sizeof(p->a[0]) ); + pNew = sqlite3DbMallocRawNN(db, SZ_IDLIST(p->nId)); if( pNew==0 ) return 0; pNew->nId = p->nId; - pNew->eU4 = p->eU4; for(i=0; i<p->nId; i++){ struct IdList_item *pNewItem = &pNew->a[i]; const struct IdList_item *pOldItem = &p->a[i]; pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); - pNewItem->u4 = pOldItem->u4; } return pNew; } @@ -111335,9 +114868,7 @@ SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, const Select *pDup, int fla pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags); pNew->iLimit = 0; pNew->iOffset = 0; - pNew->selFlags = p->selFlags & ~SF_UsesEphemeral; - pNew->addrOpenEphm[0] = -1; - pNew->addrOpenEphm[1] = -1; + pNew->selFlags = p->selFlags; pNew->nSelectRow = p->nSelectRow; pNew->pWith = sqlite3WithDup(db, p->pWith); #ifndef SQLITE_OMIT_WINDOWFUNC @@ -111387,7 +114918,7 @@ SQLITE_PRIVATE SQLITE_NOINLINE ExprList *sqlite3ExprListAppendNew( struct ExprList_item *pItem; ExprList *pList; - pList = sqlite3DbMallocRawNN(db, sizeof(ExprList)+sizeof(pList->a[0])*4 ); + pList = sqlite3DbMallocRawNN(db, SZ_EXPRLIST(4)); if( pList==0 ){ sqlite3ExprDelete(db, pExpr); return 0; @@ -111407,8 +114938,7 @@ SQLITE_PRIVATE SQLITE_NOINLINE ExprList *sqlite3ExprListAppendGrow( struct ExprList_item *pItem; ExprList *pNew; pList->nAlloc *= 2; - pNew = sqlite3DbRealloc(db, pList, - sizeof(*pList)+(pList->nAlloc-1)*sizeof(pList->a[0])); + pNew = sqlite3DbRealloc(db, pList, SZ_EXPRLIST(pList->nAlloc)); if( pNew==0 ){ sqlite3ExprListDelete(db, pList); sqlite3ExprDelete(db, pExpr); @@ -111744,6 +115274,85 @@ SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){ return pExpr; } +/* +** Return true if it might be advantageous to compute the right operand +** of expression pExpr first, before the left operand. +** +** Normally the left operand is computed before the right operand. But if +** the left operand contains a subquery and the right does not, then it +** might be more efficient to compute the right operand first. +*/ +static int exprEvalRhsFirst(Expr *pExpr){ + if( ExprHasProperty(pExpr->pLeft, EP_Subquery) + && !ExprHasProperty(pExpr->pRight, EP_Subquery) + ){ + return 1; + }else{ + return 0; + } +} + +/* +** Compute the two operands of a binary operator. +** +** If either operand contains a subquery, then the code strives to +** compute the operand containing the subquery second. If the other +** operand evalutes to NULL, then a jump is made. The address of the +** IsNull operand that does this jump is returned. The caller can use +** this to optimize the computation so as to avoid doing the potentially +** expensive subquery. +** +** If no optimization opportunities exist, return 0. +*/ +static int exprComputeOperands( + Parse *pParse, /* Parsing context */ + Expr *pExpr, /* The comparison expression */ + int *pR1, /* OUT: Register holding the left operand */ + int *pR2, /* OUT: Register holding the right operand */ + int *pFree1, /* OUT: Temp register to free if not zero */ + int *pFree2 /* OUT: Another temp register to free if not zero */ +){ + int addrIsNull; + int r1, r2; + Vdbe *v = pParse->pVdbe; + + assert( v!=0 ); + /* + ** If the left operand contains a (possibly expensive) subquery and the + ** right operand does not and the right operation might be NULL, + ** then compute the right operand first and do an IsNull jump if the + ** right operand evalutes to NULL. + */ + if( exprEvalRhsFirst(pExpr) && sqlite3ExprCanBeNull(pExpr->pRight) ){ + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, pFree2); + addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, r2); + VdbeComment((v, "skip left operand")); + VdbeCoverage(v); + }else{ + r2 = 0; /* Silence a false-positive uninit-var warning in MSVC */ + addrIsNull = 0; + } + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, pFree1); + if( addrIsNull==0 ){ + /* + ** If the right operand contains a subquery and the left operand does not + ** and the left operand might be NULL, then do an IsNull check + ** check on the left operand before computing the right operand. + */ + if( ExprHasProperty(pExpr->pRight, EP_Subquery) + && sqlite3ExprCanBeNull(pExpr->pLeft) + ){ + addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, r1); + VdbeComment((v, "skip right operand")); + VdbeCoverage(v); + } + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, pFree2); + } + *pR1 = r1; + *pR2 = r2; + return addrIsNull; +} + /* ** pExpr is a TK_FUNCTION node. Try to determine whether or not the ** function is a constant function. A function is constant if all of @@ -111784,7 +115393,7 @@ static SQLITE_NOINLINE int exprNodeIsConstantFunction( if( pDef==0 || pDef->xFinalize!=0 || (pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0 - || ExprHasProperty(pExpr, EP_WinFunc) + || NEVER(ExprHasProperty(pExpr, EP_WinFunc)) ){ pWalker->eCode = 0; return WRC_Abort; @@ -111805,6 +115414,7 @@ static SQLITE_NOINLINE int exprNodeIsConstantFunction( ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2 ** sqlite3ExprIsTableConstant() pWalker->eCode==3 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5 +** sqlite3ExprListIsConstant() pWalker->eCode==1 or 6 ** ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression ** is found to not be a constant. @@ -111831,19 +115441,25 @@ static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ } switch( pExpr->op ){ - /* Consider functions to be constant if all their arguments are constant - ** and either pWalker->eCode==4 or 5 or the function has the - ** SQLITE_FUNC_CONST flag. */ case TK_FUNCTION: - if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc)) - && !ExprHasProperty(pExpr, EP_WinFunc) - ){ + if( ExprHasProperty(pExpr, EP_WinFunc) ){ + pWalker->eCode = 0; /* Window functions are never constant */ + return WRC_Abort; + }else if( pWalker->eCode>=4 && pWalker->eCode<=5 ){ + /* Functions used within a CREATE TABLE statement are constant as + ** long as all of their arguments are constant */ if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL); return WRC_Continue; + }else if( ExprHasProperty(pExpr,EP_ConstFunc) ){ + /* Functions marked with EP_ConstFunc are constant as long as + ** all their arugments are constant and they are not window functions */ + return WRC_Continue; }else if( pWalker->pParse ){ + /* Functions are constant if they have SQLITE_FUNC_CONSTANT or + ** SQLITE_FUNC_SLOCHNG and if all arguments are constant */ return exprNodeIsConstantFunction(pWalker, pExpr); }else{ - pWalker->eCode = 0; + pWalker->eCode = 0; /* Function call is not constant */ return WRC_Abort; } case TK_ID: @@ -111877,6 +115493,13 @@ static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ testcase( pExpr->op==TK_RAISE ); pWalker->eCode = 0; return WRC_Abort; + case TK_IS: + case TK_ISNOT: + if( pWalker->eCode==6 ){ + pWalker->eCode = 0; + return WRC_Abort; + } + return WRC_Continue; case TK_VARIABLE: if( pWalker->eCode==5 ){ /* Silently convert bound parameters that appear inside of CREATE @@ -111911,7 +115534,7 @@ static int exprIsConst(Parse *pParse, Expr *p, int initFlag){ /* ** Walk an expression tree. Return non-zero if the expression is constant -** and 0 if it involves variables or function calls. +** or return zero if the expression involves variables or function calls. ** ** For the purposes of this function, a double-quoted string (ex: "abc") ** is considered a variable but a single-quoted string (ex: 'abc') is @@ -111927,11 +115550,27 @@ SQLITE_PRIVATE int sqlite3ExprIsConstant(Parse *pParse, Expr *p){ return exprIsConst(pParse, p, 1); } +/* +** Return true if all expressions in pList are constant. If parameter bNoIs +** is true, do not consider expressions that contain "IS" operators to be +** constant. IS operators are not always considered constant as expressions +** like "x IS TRUE" need to be transformed to TK_TRUTH expression nodes, +** which happens at the same time as column name resolution. +*/ +SQLITE_PRIVATE int sqlite3ExprListIsConstant(Parse *pParse, ExprList *pList, int bNoIs){ + const int iInit = bNoIs ? 6 : 1; + int ii; + for(ii=0; ii<pList->nExpr; ii++){ + if( 0==exprIsConst(pParse, pList->a[ii].pExpr, iInit) ) return 0; + } + return 1; +} + /* ** Walk an expression tree. Return non-zero if ** ** (1) the expression is constant, and -** (2) the expression does originate in the ON or USING clause +** (2) the expression does not originate in the ON or USING clause ** of a LEFT JOIN, and ** (3) the expression does not contain any EP_FixedCol TK_COLUMN ** operands created by the constant propagation optimization. @@ -112014,7 +115653,7 @@ static int sqlite3ExprIsTableConstant(Expr *p, int iCur, int bAllowSubq){ ** (4a) pExpr must come from an ON clause.. ** (4b) and specifically the ON clause associated with the LEFT JOIN. ** -** (5) If pSrc is not the right operand of a LEFT JOIN or the left +** (5) If pSrc is the right operand of a LEFT JOIN or the left ** operand of a RIGHT JOIN, then pExpr must be from the WHERE ** clause, not an ON clause. ** @@ -112168,65 +115807,68 @@ SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){ #endif /* -** If the expression p codes a constant integer that is small enough -** to fit in a 32-bit integer, return 1 and put the value of the integer -** in *pValue. If the expression is not an integer or if it is too big -** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged. +** If the expression p codes a constant integer between 0 and 0x7fffffff, +** then return 1 and put the value of the integer in *pValue. If the +** expression is not an integer or if it is an integer that is out side +** the range of 0...0x7fffffff, then return 0 and leave *pValue unchanged. ** ** If the pParse pointer is provided, then allow the expression p to be -** a parameter (TK_VARIABLE) that is bound to an integer. -** But if pParse is NULL, then p must be a pure integer literal. -*/ -SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr *p, int *pValue, Parse *pParse){ - int rc = 0; - if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */ - - /* If an expression is an integer literal that fits in a signed 32-bit - ** integer, then the EP_IntValue flag will have already been set */ - assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0 - || sqlite3GetInt32(p->u.zToken, &rc)==0 ); - - if( p->flags & EP_IntValue ){ - *pValue = p->u.iValue; - return 1; - } - switch( p->op ){ - case TK_UPLUS: { - rc = sqlite3ExprIsInteger(p->pLeft, pValue, 0); - break; +** a parameter (TK_VARIABLE) that is bound to an integer between 0 and +** 0x7fffffff. Variables that hold anything other than integers, or that +** hold integers outside the range of 0..0x7fffffff are not seen. +** But if pParse is NULL, then p must be a pure integer literal between +** 0 and 0x7fffffff. +** +** If pParse is not NULL and expression p is a variable, then the variable +** is marked so as to cause the statement to be reprepared each time a new +** value is bound to it. Except, if parameter bRSI is true, then the statement +** will only be reprepared if the rebind changes the value to or from a +** "small integer" (either 0 or 1). +*/ +SQLITE_PRIVATE int sqlite3ExprIsInteger(const Expr *p, int *pValue, Parse *pParse, int bRSI){ + int iSign = 1; /* Either +1 or -1. */ + while( 1/*exit-by-break*/ ){ + if( NEVER(p==0) ) return 0; + if( ExprUseUValue(p) ){ + *pValue = p->u.iValue*iSign; + return 1; } - case TK_UMINUS: { - int v = 0; - if( sqlite3ExprIsInteger(p->pLeft, &v, 0) ){ - assert( ((unsigned int)v)!=0x80000000 ); - *pValue = -v; - rc = 1; - } - break; + if( p->op==TK_UPLUS ){ + p = p->pLeft; + pParse = 0; + continue; } - case TK_VARIABLE: { - sqlite3_value *pVal; - if( pParse==0 ) break; + if( p->op==TK_UMINUS ){ + iSign = -iSign; + p = p->pLeft; + pParse = 0; + continue; + } + if( p->op==TK_VARIABLE && pParse!=0 ){ + sqlite3_value *pVal; /* The variable */ + int rc = 0; /* 1 if successful, 0 if failed */ + assert( iSign==1 ); if( NEVER(pParse->pVdbe==0) ) break; if( (pParse->db->flags & SQLITE_EnableQPSG)!=0 ) break; - sqlite3VdbeSetVarmask(pParse->pVdbe, p->iColumn); pVal = sqlite3VdbeGetBoundValue(pParse->pReprepare, p->iColumn, SQLITE_AFF_BLOB); if( pVal ){ - if( sqlite3_value_type(pVal)==SQLITE_INTEGER ){ - sqlite3_int64 vv = sqlite3_value_int64(pVal); - if( vv == (vv & 0x7fffffff) ){ /* non-negative numbers only */ - *pValue = (int)vv; - rc = 1; - } + i64 vv; + if( sqlite3_value_type(pVal)==SQLITE_INTEGER + && (vv = sqlite3_value_int64(pVal))>=0 + && vv<=0x7fffffff + ){ + *pValue = (int)vv; + rc = 1; } sqlite3ValueFree(pVal); } - break; + sqlite3VdbeReprepareOnBind(pParse->pVdbe, p->iColumn, bRSI); + return rc; } - default: break; + break; } - return rc; + return 0; } /* @@ -112337,13 +115979,7 @@ SQLITE_PRIVATE const char *sqlite3RowidAlias(Table *pTab){ int ii; assert( VisibleRowid(pTab) ); for(ii=0; ii<ArraySize(azOpt); ii++){ - int iCol; - for(iCol=0; iCol<pTab->nCol; iCol++){ - if( sqlite3_stricmp(azOpt[ii], pTab->aCol[iCol].zCnName)==0 ) break; - } - if( iCol==pTab->nCol ){ - return azOpt[ii]; - } + if( sqlite3ColumnIndex(pTab, azOpt[ii])<0 ) return azOpt[ii]; } return 0; } @@ -112366,10 +116002,8 @@ static Select *isCandidateForInOpt(const Expr *pX){ if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */ p = pX->x.pSelect; if( p->pPrior ) return 0; /* Not a compound SELECT */ - if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ - testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); - testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); - return 0; /* No DISTINCT keyword and no aggregate functions */ + if( p->selFlags & SF_Aggregate ){ + return 0; /* No GROUP BY keyword or aggregate functions */ } assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */ if( p->pLimit ) return 0; /* Has no LIMIT clause */ @@ -112401,13 +116035,24 @@ static Select *isCandidateForInOpt(const Expr *pX){ ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull ** to be set to NULL if iCur contains one or more NULL values. */ -static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){ +static void sqlite3SetHasNullFlag( + Vdbe *v, /* Write new code into this statement under construction */ + int iCur, /* Cursor for the index */ + int regHasNull, /* Register in which to store hasNull flag */ + int eSortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ +){ int addr1; + int op; sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull); - addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v); + if( eSortOrder==SQLITE_SO_ASC ){ + op = OP_Rewind; + }else{ + op = OP_Last; + } + addr1 = sqlite3VdbeAddOp1(v, op, iCur); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull); sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); - VdbeComment((v, "first_entry_in(%d)", iCur)); + VdbeComment((v, op==OP_Last?"last_entry_in(%d)":"first_entry_in(%d)", iCur)); sqlite3VdbeJumpHere(v, addr1); } #endif @@ -112653,6 +116298,7 @@ SQLITE_PRIVATE int sqlite3FindInIndex( if( aiMap ) aiMap[i] = j; } + assert( nExpr>0 && nExpr<BMS ); assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) ); if( colUsed==(MASKBIT(nExpr)-1) ){ /* If we reach this point, that means the index pIdx is usable */ @@ -112667,13 +116313,14 @@ SQLITE_PRIVATE int sqlite3FindInIndex( if( prRhsHasNull ){ #ifdef SQLITE_ENABLE_COLUMN_USED_MASK - i64 mask = (1<<nExpr)-1; - sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, - iTab, 0, 0, (u8*)&mask, P4_INT64); + u64 mask = (1<<nExpr)-1; + sqlite3VdbeAddOp3(v, OP_ColumnsUsed, + iTab, LOWER32(mask), UPPER32(mask)); #endif *prRhsHasNull = ++pParse->nMem; if( nExpr==1 ){ - sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull); + sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull, + pIdx->aSortOrder[0]); } } sqlite3VdbeJumpHere(v, iAddr); @@ -112706,6 +116353,7 @@ SQLITE_PRIVATE int sqlite3FindInIndex( */ u32 savedNQueryLoop = pParse->nQueryLoop; int rMayHaveNull = 0; + int bloomOk = (inFlags & IN_INDEX_MEMBERSHIP)!=0; eType = IN_INDEX_EPH; if( inFlags & IN_INDEX_LOOP ){ pParse->nQueryLoop = 0; @@ -112713,9 +116361,15 @@ SQLITE_PRIVATE int sqlite3FindInIndex( *prRhsHasNull = rMayHaveNull = ++pParse->nMem; } assert( pX->op==TK_IN ); - sqlite3CodeRhsOfIN(pParse, pX, iTab); + if( !bloomOk + && ExprUseXSelect(pX) + && (pX->x.pSelect->selFlags & SF_ClonedRhsIn)!=0 + ){ + bloomOk = 1; + } + sqlite3CodeRhsOfIN(pParse, pX, iTab, bloomOk); if( rMayHaveNull ){ - sqlite3SetHasNullFlag(v, iTab, rMayHaveNull); + sqlite3SetHasNullFlag(v, iTab, rMayHaveNull, SQLITE_SO_ASC); } pParse->nQueryLoop = savedNQueryLoop; } @@ -112746,7 +116400,7 @@ static char *exprINAffinity(Parse *pParse, const Expr *pExpr){ char *zRet; assert( pExpr->op==TK_IN ); - zRet = sqlite3DbMallocRaw(pParse->db, nVal+1); + zRet = sqlite3DbMallocRaw(pParse->db, 1+(i64)nVal); if( zRet ){ int i; for(i=0; i<nVal; i++){ @@ -112832,6 +116486,7 @@ static int findCompatibleInRhsSubrtn( assert( pOp->opcode==OP_BeginSubrtn ); pSig = pOp->p4.pSubrtnSig; assert( pSig!=0 ); + if( !pSig->bComplete ) continue; if( pNewSig->selId!=pSig->selId ) continue; if( strcmp(pNewSig->zAff,pSig->zAff)!=0 ) continue; pExpr->y.sub.iAddr = pSig->iAddr; @@ -112870,7 +116525,8 @@ static int findCompatibleInRhsSubrtn( SQLITE_PRIVATE void sqlite3CodeRhsOfIN( Parse *pParse, /* Parsing context */ Expr *pExpr, /* The IN operator */ - int iTab /* Use this cursor number */ + int iTab, /* Use this cursor number */ + int allowBloom /* True to allow the use of a Bloom filter */ ){ int addrOnce = 0; /* Address of the OP_Once instruction at top */ int addr; /* Address of OP_OpenEphemeral instruction */ @@ -112878,6 +116534,7 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN( KeyInfo *pKeyInfo = 0; /* Key information */ int nVal; /* Size of vector pLeft */ Vdbe *v; /* The prepared statement under construction */ + SubrtnSig *pSig = 0; /* Signature for this subroutine */ v = pParse->pVdbe; assert( v!=0 ); @@ -112898,7 +116555,6 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN( ** Compute a signature for the RHS of the IN operator to facility ** finding and reusing prior instances of the same IN operator. */ - SubrtnSig *pSig = 0; assert( !ExprUseXSelect(pExpr) || pExpr->x.pSelect!=0 ); if( ExprUseXSelect(pExpr) && (pExpr->x.pSelect->selFlags & SF_All)==0 ){ pSig = sqlite3DbMallocRawNN(pParse->db, sizeof(pSig[0])); @@ -112941,6 +116597,7 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN( pExpr->y.sub.iAddr = sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1; if( pSig ){ + pSig->bComplete = 0; pSig->iAddr = pExpr->y.sub.iAddr; pSig->regReturn = pExpr->y.sub.regReturn; pSig->iTable = iTab; @@ -112967,6 +116624,8 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN( } #endif pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1); + assert( pKeyInfo!=0 || pParse->nErr ); + if( pKeyInfo==0 ) return; if( ExprUseXSelect(pExpr) ){ /* Case 1: expr IN (SELECT ...) @@ -112991,40 +116650,48 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN( sqlite3SelectDestInit(&dest, SRT_Set, iTab); dest.zAffSdst = exprINAffinity(pParse, pExpr); pSelect->iLimit = 0; - if( addrOnce && OptimizationEnabled(pParse->db, SQLITE_BloomFilter) ){ + assert( pEList!=0 ); + assert( pEList->nExpr>0 ); + assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); + for(i=0; i<nVal; i++){ + Expr *p = sqlite3VectorFieldSubexpr(pLeft, i); + CollSeq *pColl; + pKeyInfo->aColl[i] = pColl = sqlite3BinaryCompareCollSeq( + pParse, p, pEList->a[i].pExpr + ); + if( !sqlite3IsBinary(pColl) ){ + allowBloom = 0; /* tag-202607231411 */ + } + } + if( addrOnce + && allowBloom + && OptimizationEnabled(pParse->db, SQLITE_BloomFilter) + ){ int regBloom = ++pParse->nMem; addrBloom = sqlite3VdbeAddOp2(v, OP_Blob, 10000, regBloom); VdbeComment((v, "Bloom filter")); dest.iSDParm2 = regBloom; + sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); + pKeyInfo = 0; } testcase( pSelect->selFlags & SF_Distinct ); - testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */ pCopy = sqlite3SelectDup(pParse->db, pSelect, 0); rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest); sqlite3SelectDelete(pParse->db, pCopy); sqlite3DbFree(pParse->db, dest.zAffSdst); if( addrBloom ){ + /* Remember that location of the Bloom filter in the P3 operand + ** of the OP_Once that began this subroutine. tag-202407032019 */ sqlite3VdbeGetOp(v, addrOnce)->p3 = dest.iSDParm2; if( dest.iSDParm2==0 ){ - sqlite3VdbeChangeToNoop(v, addrBloom); - }else{ - sqlite3VdbeGetOp(v, addrOnce)->p3 = dest.iSDParm2; + /* If the Bloom filter won't actually be used, keep it small */ + sqlite3VdbeGetOp(v, addrBloom)->p1 = 10; } } if( rc ){ sqlite3KeyInfoUnref(pKeyInfo); return; } - assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */ - assert( pEList!=0 ); - assert( pEList->nExpr>0 ); - assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); - for(i=0; i<nVal; i++){ - Expr *p = sqlite3VectorFieldSubexpr(pLeft, i); - pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq( - pParse, p, pEList->a[i].pExpr - ); - } } }else if( ALWAYS(pExpr->x.pList!=0) ){ /* Case 2: expr IN (exprlist) @@ -113045,10 +116712,9 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN( }else if( affinity==SQLITE_AFF_REAL ){ affinity = SQLITE_AFF_NUMERIC; } - if( pKeyInfo ){ - assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); - pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); - } + assert( pKeyInfo!=0 ); + assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); + pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); /* Loop through each expression in <exprlist>. */ r1 = sqlite3GetTempReg(pParse); @@ -113076,6 +116742,7 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN( sqlite3ReleaseTempReg(pParse, r1); sqlite3ReleaseTempReg(pParse, r2); } + if( pSig ) pSig->bComplete = 1; if( pKeyInfo ){ sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); } @@ -113179,9 +116846,22 @@ SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){ pParse->nMem += nReg; if( pExpr->op==TK_SELECT ){ dest.eDest = SRT_Mem; - dest.iSdst = dest.iSDParm; + if( (pSel->selFlags&SF_Distinct) && pSel->pLimit && pSel->pLimit->pRight ){ + /* If there is both a DISTINCT and an OFFSET clause, then allocate + ** a separate dest.iSdst array for sqlite3Select() and other + ** routines to populate. In this case results will be copied over + ** into the dest.iSDParm array only after OFFSET processing. This + ** ensures that in the case where OFFSET excludes all rows, the + ** dest.iSDParm array is not left populated with the contents of the + ** last row visited - it should be all NULLs if all rows were + ** excluded by OFFSET. */ + dest.iSdst = pParse->nMem+1; + pParse->nMem += nReg; + }else{ + dest.iSdst = dest.iSDParm; + } dest.nSdst = nReg; - sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1); + sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, pParse->nMem); VdbeComment((v, "Init subquery result")); }else{ dest.eDest = SRT_Exists; @@ -113189,20 +116869,26 @@ SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){ VdbeComment((v, "Init EXISTS result")); } if( pSel->pLimit ){ - /* The subquery already has a limit. If the pre-existing limit is X - ** then make the new limit X<>0 so that the new limit is either 1 or 0 */ - sqlite3 *db = pParse->db; - pLimit = sqlite3Expr(db, TK_INTEGER, "0"); - if( pLimit ){ - pLimit->affExpr = SQLITE_AFF_NUMERIC; - pLimit = sqlite3PExpr(pParse, TK_NE, - sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit); + /* The subquery already has a limit. If the pre-existing limit X is + ** not already integer value 1 or 0, then make the new limit X<>0 so that + ** the new limit is either 1 or 0 */ + Expr *pLeft = pSel->pLimit->pLeft; + if( ExprHasProperty(pLeft, EP_IntValue)==0 + || (pLeft->u.iValue!=1 && pLeft->u.iValue!=0) + ){ + sqlite3 *db = pParse->db; + pLimit = sqlite3ExprInt32(db, 0); + if( pLimit ){ + pLimit->affExpr = SQLITE_AFF_NUMERIC; + pLimit = sqlite3PExpr(pParse, TK_NE, + sqlite3ExprDup(db, pLeft, 0), pLimit); + } + sqlite3ExprDeferredDelete(pParse, pLeft); + pSel->pLimit->pLeft = pLimit; } - sqlite3ExprDeferredDelete(pParse, pSel->pLimit->pLeft); - pSel->pLimit->pLeft = pLimit; }else{ /* If there is no pre-existing limit add a limit of 1 */ - pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1"); + pLimit = sqlite3ExprInt32(pParse->db, 1); pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0); } pSel->iLimit = 0; @@ -113218,6 +116904,12 @@ SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){ } sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1); + if( dest.eDest==SRT_Mem + && sqlite3ExprCanReturnSubtype(pParse, pSel->pEList->a[0].pExpr) + ){ + sqlite3VdbeAddOp1(v, OP_ClrSubtype, rReg); + } + /* Subroutine return */ assert( ExprUseYSub(pExpr) ); assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn @@ -113287,7 +116979,6 @@ static void sqlite3ExprCodeIN( int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */ int eType; /* Type of the RHS */ int rLhs; /* Register(s) holding the LHS values */ - int rLhsOrig; /* LHS values prior to reordering by aiMap[] */ Vdbe *v; /* Statement under construction */ int *aiMap = 0; /* Map from vector field to index column */ char *zAff = 0; /* Affinity string for comparisons */ @@ -113350,19 +117041,8 @@ static void sqlite3ExprCodeIN( ** by code generated below. */ assert( pParse->okConstFactor==okConstFactor ); pParse->okConstFactor = 0; - rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy); + rLhs = exprCodeVector(pParse, pLeft, &iDummy); pParse->okConstFactor = okConstFactor; - for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */ - if( i==nVector ){ - /* LHS fields are not reordered */ - rLhs = rLhsOrig; - }else{ - /* Need to reorder the LHS fields according to aiMap */ - rLhs = sqlite3GetTempRange(pParse, nVector); - for(i=0; i<nVector; i++){ - sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0); - } - } /* If sqlite3FindInIndex() did not find or create an index that is ** suitable for evaluating the IN operator, then evaluate using a @@ -113377,6 +117057,7 @@ static void sqlite3ExprCodeIN( int r2, regToFree; int regCkNull = 0; int ii; + assert( nVector==1 ); assert( ExprUseXList(pExpr) ); pList = pExpr->x.pList; pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); @@ -113418,6 +117099,40 @@ static void sqlite3ExprCodeIN( goto sqlite3ExprCodeIN_finished; } + if( eType!=IN_INDEX_ROWID ){ + /* If this IN operator will use an index, then the order of columns in the + ** vector might be different from the order in the index. In that case, + ** we need to reorder the LHS values to be in index order. Run Affinity + ** before reordering the columns, so that the affinity is correct. + */ + if( nVector==1 ){ + char aff = zAff[0]; + if( aff>=SQLITE_AFF_TEXT && aff!=sqlite3ExprAffinity(pLeft) ){ + /* The OP_Affinity below may change the value. In this case, create a + ** copy of rLhs to run OP_Affinity on, in case the original register + ** is used again (e.g. if it is TK_AGG_COLUMN). */ + int rTmp = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_Copy, rLhs, rTmp, 0); + rLhs = rTmp; + sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, 1, 0, zAff, 1); + } + }else{ + sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector); + } + + for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */ + if( i!=nVector ){ + /* Need to reorder the LHS fields according to aiMap */ + int rLhsOrig = rLhs; + rLhs = sqlite3GetTempRange(pParse, nVector); + for(i=0; i<nVector; i++){ + testcase( aiMap[i]!=i ); + sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0); + } + } + } + + /* Step 2: Check to see if the LHS contains any NULL columns. If the ** LHS does contain NULLs then the result must be either FALSE or NULL. ** We will then skip the binary search of the RHS. @@ -113431,7 +117146,8 @@ static void sqlite3ExprCodeIN( Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i); if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error; if( sqlite3ExprCanBeNull(p) ){ - sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2); + testcase( aiMap[i]!=i ); + sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+aiMap[i], destStep2); VdbeCoverage(v); } } @@ -113444,18 +117160,19 @@ static void sqlite3ExprCodeIN( /* In this case, the RHS is the ROWID of table b-tree and so we also ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4 ** into a single opcode. */ + assert( nVector==1 ); sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs); VdbeCoverage(v); addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */ }else{ - sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector); if( destIfFalse==destIfNull ){ /* Combine Step 3 and Step 5 into a single opcode */ if( ExprHasProperty(pExpr, EP_Subrtn) ){ const VdbeOp *pOp = sqlite3VdbeGetOp(v, pExpr->y.sub.iAddr); assert( pOp->opcode==OP_Once || pParse->nErr ); - if( pOp->opcode==OP_Once && pOp->p3>0 ){ - assert( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) ); + if( pOp->p3>0 ){ /* tag-202407032019 */ + assert( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) + || pParse->nErr ); sqlite3VdbeAddOp4Int(v, OP_Filter, pOp->p3, destIfFalse, rLhs, nVector); VdbeCoverage(v); } @@ -113490,7 +117207,13 @@ static void sqlite3ExprCodeIN( ** of the RHS. */ if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6); - addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse); + if( eType==IN_INDEX_INDEX_DESC ){ + addrTop = sqlite3VdbeAddOp2(v, OP_Last, iTab, destIfFalse); + }else{ + testcase( eType==IN_INDEX_EPH ); + testcase( eType==IN_INDEX_ROWID ); + addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse); + } VdbeCoverage(v); if( nVector>1 ){ destNotNull = sqlite3VdbeMakeLabel(pParse); @@ -113504,9 +117227,19 @@ static void sqlite3ExprCodeIN( CollSeq *pColl; int r3 = sqlite3GetTempReg(pParse); p = sqlite3VectorFieldSubexpr(pLeft, i); - pColl = sqlite3ExprCollSeq(pParse, p); - sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3); - sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3, + if( ExprUseXSelect(pExpr) ){ + Expr *pRhs = pExpr->x.pSelect->pEList->a[i].pExpr; + pColl = sqlite3BinaryCompareCollSeq(pParse, p, pRhs); + }else{ + /* If the RHS of the IN(...) expression are scalar expressions, do + ** not consider their collation sequences. The documentation says + ** "The collating sequence used for expressions of the form "x IN (y, z, + ** ...)" is the collating sequence of x.". */ + pColl = sqlite3ExprCollSeq(pParse, p); + } + testcase( aiMap[i]!=i ); + sqlite3VdbeAddOp3(v, OP_Column, iTab, aiMap[i], r3); + sqlite3VdbeAddOp4(v, OP_Ne, rLhs+aiMap[i], destNotNull, r3, (void*)pColl, P4_COLLSEQ); VdbeCoverage(v); sqlite3ReleaseTempReg(pParse, r3); @@ -113526,7 +117259,6 @@ static void sqlite3ExprCodeIN( sqlite3VdbeJumpHere(v, addrTruthOp); sqlite3ExprCodeIN_finished: - if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs); VdbeComment((v, "end IN expr")); sqlite3ExprCodeIN_oom_error: sqlite3DbFree(pParse->db, aiMap); @@ -113546,10 +117278,10 @@ static void sqlite3ExprCodeIN( static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){ if( ALWAYS(z!=0) ){ double value; - sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8); + sqlite3AtoF(z, &value); assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */ if( negateFlag ) value = -value; - sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL); + sqlite3VdbeAddDouble(v, iMem, value); } } #endif @@ -113590,7 +117322,7 @@ static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){ #endif }else{ if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; } - sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64); + sqlite3VdbeAddInt64(v, iMem, value); } } } @@ -113641,7 +117373,12 @@ SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn( iAddr = 0; } sqlite3ExprCodeCopy(pParse, sqlite3ColumnExpr(pTab,pCol), regOut); - if( pCol->affinity>=SQLITE_AFF_TEXT ){ + if( (pCol->colFlags & COLFLAG_VIRTUAL)!=0 + && (pTab->tabFlags & TF_Strict)!=0 + ){ + int p3 = 2+(int)(pCol - pTab->aCol); + sqlite3VdbeAddOp4(v, OP_TypeCheck, regOut, 1, p3, (char*)pTab, P4_TABLE); + }else if( pCol->affinity>=SQLITE_AFF_TEXT ){ sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1); } if( iAddr ) sqlite3VdbeJumpHere(v, iAddr); @@ -113666,12 +117403,12 @@ SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable( if( iCol<0 || iCol==pTab->iPKey ){ sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); VdbeComment((v, "%s.rowid", pTab->zName)); - }else{ - int op; + }else{ int x; if( IsVirtual(pTab) ){ - op = OP_VColumn; x = iCol; + sqlite3VdbeAddOp3(v, OP_VColumn, iTabCur, x, regOut); + return; #ifndef SQLITE_OMIT_GENERATED_COLUMNS }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){ Parse *pParse = sqlite3VdbeParser(v); @@ -113691,13 +117428,11 @@ SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable( }else if( !HasRowid(pTab) ){ testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) ); x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol); - op = OP_Column; }else{ x = sqlite3TableColumnToStorage(pTab,iCol); testcase( x!=iCol ); - op = OP_Column; } - sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut); + sqlite3VdbeAddOp3(v, OP_Column, iTabCur, x, regOut); sqlite3ColumnDefault(v, pTab, iCol, regOut); } } @@ -113923,36 +117658,52 @@ static int exprCodeInlineFunction( } /* -** Expression Node callback for sqlite3ExprCanReturnSubtype(). +** Expression Node callback for sqlite3ExprCanReturnSubtype(). If +** pExpr is able to return a subtype, set pWalker->eCode and abort +** the search. If pExpr can never return a subtype, prune search. +** +** The only expressions that can return a subtype are: +** +** 1. A function, including an aggregate function +** 2. The no-op "+" operator +** 3. A CASE...END expression +** 4. A CAST() expression +** 5. A "expr COLLATE colseq" expression. ** -** Only a function call is able to return a subtype. So if the node -** is not a function call, return WRC_Prune immediately. +** For any other kind of expression, prune the search. ** -** A function call is able to return a subtype if it has the -** SQLITE_RESULT_SUBTYPE property. +** For case 1, the expression can yield a subtype if the function has +** the SQLITE_RESULT_SUBTYPE property. Functions can also return +** a subtype (via sqlite3_result_value()) if any of the arguments can +** return a subtype. ** -** Assume that every function is able to pass-through a subtype from -** one of its argument (using sqlite3_result_value()). Most functions -** are not this way, but we don't have a mechanism to distinguish those -** that are from those that are not, so assume they all work this way. -** That means that if one of its arguments is another function and that -** other function is able to return a subtype, then this function is -** able to return a subtype. +** In all cases 1 through 5, the expression might also return a subtype +** if any operand can return a subtype. */ static int exprNodeCanReturnSubtype(Walker *pWalker, Expr *pExpr){ int n; FuncDef *pDef; sqlite3 *db; - if( pExpr->op!=TK_FUNCTION ){ + if( pExpr->op==TK_CASE || pExpr->op==TK_UPLUS + || pExpr->op==TK_COLLATE || pExpr->op==TK_CAST + ){ + return WRC_Continue; + } + if( pExpr->op!=TK_FUNCTION && pExpr->op!=TK_AGG_FUNCTION ){ return WRC_Prune; } assert( ExprUseXList(pExpr) ); db = pWalker->pParse->db; - n = ALWAYS(pExpr->x.pList) ? pExpr->x.pList->nExpr : 0; + n = pExpr->x.pList ? pExpr->x.pList->nExpr : 0; pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0); - if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){ +#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION + if( pDef==0 ) return WRC_Continue; +#else + assert( pDef!=0 ); +#endif + if( (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){ pWalker->eCode = 1; - return WRC_Prune; + return WRC_Abort; } return WRC_Continue; } @@ -113965,7 +117716,7 @@ static int exprNodeCanReturnSubtype(Walker *pWalker, Expr *pExpr){ ** are acceptable as they only disable an optimization. False negatives, ** on the other hand, can lead to incorrect answers. */ -static int sqlite3ExprCanReturnSubtype(Parse *pParse, Expr *pExpr){ +SQLITE_PRIVATE int sqlite3ExprCanReturnSubtype(Parse *pParse, Expr *pExpr){ Walker w; memset(&w, 0, sizeof(w)); w.pParse = pParse; @@ -114020,10 +117771,16 @@ static SQLITE_NOINLINE int sqlite3IndexedExprLookup( v = pParse->pVdbe; assert( v!=0 ); - if( p->bMaybeNullRow ){ - /* If the index is on a NULL row due to an outer join, then we - ** cannot extract the value from the index. The value must be - ** computed using the original expression. */ + if( p->bMaybeNullRow || sqlite3ExprIsConstant(pParse, pExpr) ){ + /* The value of pExpr should be computed from the original expression, + ** not from the index, if either: + ** + ** 1. The index might be on a NULL row due to an outer join. + ** + ** 2. The expression is a constant. This prevents an attempt to + ** use an index value outside of the loop that positions the + ** index. (Bug 2026-10-11T19:26:40Z). + */ int addr = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target); VdbeCoverage(v); @@ -114046,7 +117803,7 @@ static SQLITE_NOINLINE int sqlite3IndexedExprLookup( /* -** Expresion pExpr is guaranteed to be a TK_COLUMN or equivalent. This +** Expression pExpr is guaranteed to be a TK_COLUMN or equivalent. This ** function checks the Parse.pIdxPartExpr list to see if this column ** can be replaced with a constant value. If so, it generates code to ** put the constant value in a register (ideally, but not necessarily, @@ -114069,6 +117826,11 @@ static int exprPartidxExprLookup(Parse *pParse, Expr *pExpr, int iTarget){ ret = sqlite3ExprCodeTarget(pParse, p->pExpr, iTarget); sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, ret, 1, 0, (const char*)&p->aff, 1); + if( sqlite3ExprCanReturnSubtype(pParse, p->pExpr) ){ + /* If the expression value may have a sub-type, clear it. Values + ** read from columns do not have subtypes. */ + sqlite3VdbeAddOp1(pParse->pVdbe, OP_ClrSubtype, ret); + } if( addr ){ sqlite3VdbeJumpHere(v, addr); sqlite3VdbeChangeP3(v, addr, ret); @@ -114079,6 +117841,80 @@ static int exprPartidxExprLookup(Parse *pParse, Expr *pExpr, int iTarget){ return 0; } +/* +** Generate code that evaluates an AND or OR operator leaving a +** boolean result in a register. pExpr is the AND/OR expression. +** Store the result in the "target" register. Use short-circuit +** evaluation to avoid computing both operands, if possible. +** +** The code generated might require the use of a temporary register. +** If it does, then write the number of that temporary register +** into *pTmpReg. If not, leave *pTmpReg unchanged. +*/ +static SQLITE_NOINLINE int exprCodeTargetAndOr( + Parse *pParse, /* Parsing context */ + Expr *pExpr, /* AND or OR expression to be coded */ + int target, /* Put result in this register, guaranteed */ + int *pTmpReg /* Write a temporary register here */ +){ + int op; /* The opcode. TK_AND or TK_OR */ + int skipOp; /* Opcode for the branch that skips one operand */ + int addrSkip; /* Branch instruction that skips one of the operands */ + int regSS = 0; /* Register holding computed operand when other omitted */ + int r1, r2; /* Registers for left and right operands, respectively */ + Expr *pAlt; /* Alternative, simplified expression */ + Vdbe *v; /* statement being coded */ + + assert( pExpr!=0 ); + op = pExpr->op; + assert( op==TK_AND || op==TK_OR ); + assert( TK_AND==OP_And ); testcase( op==TK_AND ); + assert( TK_OR==OP_Or ); testcase( op==TK_OR ); + assert( pParse->pVdbe!=0 ); + v = pParse->pVdbe; + pAlt = sqlite3ExprSimplifiedAndOr(pExpr); + if( pAlt!=pExpr ){ + r1 = sqlite3ExprCodeTarget(pParse, pAlt, target); + sqlite3VdbeAddOp3(v, OP_And, r1, r1, target); + return target; + } + skipOp = op==TK_AND ? OP_IfNot : OP_If; + if( exprEvalRhsFirst(pExpr) ){ + /* Compute the right operand first. Skip the computation of the left + ** operand if the right operand fully determines the result */ + r2 = regSS = sqlite3ExprCodeTarget(pParse, pExpr->pRight, target); + addrSkip = sqlite3VdbeAddOp1(v, skipOp, r2); + VdbeComment((v, "skip left operand")); + VdbeCoverage(v); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, pTmpReg); + }else{ + /* Compute the left operand first */ + r1 = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + if( ExprHasProperty(pExpr->pRight, EP_Subquery) ){ + /* Skip over the computation of the right operand if the right + ** operand is a subquery and the left operand completely determines + ** the result */ + regSS = r1; + addrSkip = sqlite3VdbeAddOp1(v, skipOp, r1); + VdbeComment((v, "skip right operand")); + VdbeCoverage(v); + }else{ + addrSkip = regSS = 0; + } + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, pTmpReg); + } + sqlite3VdbeAddOp3(v, op, r2, r1, target); + testcase( (*pTmpReg)==0 ); + if( addrSkip ){ + sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2); + sqlite3VdbeJumpHere(v, addrSkip); + sqlite3VdbeAddOp3(v, OP_Or, regSS, regSS, target); + VdbeComment((v, "short-circut value")); + } + return target; +} + + /* ** Generate code into the current Vdbe to evaluate the given @@ -114270,6 +118106,12 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) sqlite3VdbeLoadString(v, target, pExpr->u.zToken); return target; } + case TK_NULLS: { + /* Set a range of registers to NULL. pExpr->y.nReg registers starting + ** with target */ + sqlite3VdbeAddOp3(v, OP_Null, 0, target, target + pExpr->y.nReg - 1); + return target; + } default: { /* Make NULL the default case so that if a bug causes an illegal ** Expr node to be passed into this function, it will be handled @@ -114320,7 +118162,7 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) case TK_ISNOT: op = (op==TK_IS) ? TK_EQ : TK_NE; p5 = SQLITE_NULLEQ; - /* fall-through */ + /* no break */ deliberate_fall_through case TK_LT: case TK_LE: case TK_GT: @@ -114328,11 +118170,17 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) case TK_NE: case TK_EQ: { Expr *pLeft = pExpr->pLeft; + int addrIsNull = 0; if( sqlite3ExprIsVector(pLeft) ){ codeVectorCompare(pParse, pExpr, target, op, p5); }else{ - r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); + if( ExprHasProperty(pExpr, EP_Subquery) && p5!=SQLITE_NULLEQ ){ + addrIsNull = exprComputeOperands(pParse, pExpr, + &r1, &r2, &regFree1, &regFree2); + }else{ + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); + } sqlite3VdbeAddOp2(v, OP_Integer, 1, inReg); codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2, sqlite3VdbeCurrentAddr(v)+2, p5, @@ -114347,6 +118195,11 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) sqlite3VdbeAddOp2(v, OP_Integer, 0, inReg); }else{ sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, inReg, r2); + if( addrIsNull ){ + sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2); + sqlite3VdbeJumpHere(v, addrIsNull); + sqlite3VdbeAddOp2(v, OP_Null, 0, inReg); + } } testcase( regFree1==0 ); testcase( regFree2==0 ); @@ -114354,7 +118207,10 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) break; } case TK_AND: - case TK_OR: + case TK_OR: { + inReg = exprCodeTargetAndOr(pParse, pExpr, target, &regFree1); + break; + } case TK_PLUS: case TK_STAR: case TK_MINUS: @@ -114365,8 +118221,7 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) case TK_LSHIFT: case TK_RSHIFT: case TK_CONCAT: { - assert( TK_AND==OP_And ); testcase( op==TK_AND ); - assert( TK_OR==OP_Or ); testcase( op==TK_OR ); + int addrIsNull; assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS ); assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS ); assert( TK_REM==OP_Remainder ); testcase( op==TK_REM ); @@ -114376,11 +118231,23 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT ); assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT ); assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); + if( ExprHasProperty(pExpr, EP_Subquery) ){ + addrIsNull = exprComputeOperands(pParse, pExpr, + &r1, &r2, &regFree1, &regFree2); + }else{ + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); + addrIsNull = 0; + } sqlite3VdbeAddOp3(v, op, r2, r1, target); testcase( regFree1==0 ); testcase( regFree2==0 ); + if( addrIsNull ){ + sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2); + sqlite3VdbeJumpHere(v, addrIsNull); + sqlite3VdbeAddOp2(v, OP_Null, 0, target); + VdbeComment((v, "short-circut value")); + } break; } case TK_UMINUS: { @@ -114492,7 +118359,12 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0); } #endif - if( pDef==0 || pDef->xFinalize!=0 ){ + if( pDef==0 + || pDef->xFinalize!=0 + || ((pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0 && + !pParse->nested && + (db->mDbFlags & DBFLAG_InternalFunc)==0) + ){ sqlite3ErrorMsg(pParse, "unknown function: %#T()", pExpr); break; } @@ -114954,6 +118826,25 @@ SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce( return regDest; } +/* +** Make arrangements to invoke OP_Null on a range of registers +** during initialization. +*/ +SQLITE_PRIVATE SQLITE_NOINLINE void sqlite3ExprNullRegisterRange( + Parse *pParse, /* Parsing context */ + int iReg, /* First register to set to NULL */ + int nReg /* Number of sequential registers to NULL out */ +){ + u8 okConstFactor = pParse->okConstFactor; + Expr t; + memset(&t, 0, sizeof(t)); + t.op = TK_NULLS; + t.y.nReg = nReg; + pParse->okConstFactor = 1; + sqlite3ExprCodeRunJustOnce(pParse, &t, iReg); + pParse->okConstFactor = okConstFactor; +} + /* ** Generate code to evaluate an expression and store the results ** into a register. Return the register number where the results @@ -115229,17 +119120,27 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr); if( pAlt!=pExpr ){ sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull); - }else if( op==TK_AND ){ - int d2 = sqlite3VdbeMakeLabel(pParse); - testcase( jumpIfNull==0 ); - sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, - jumpIfNull^SQLITE_JUMPIFNULL); - sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); - sqlite3VdbeResolveLabel(v, d2); }else{ - testcase( jumpIfNull==0 ); - sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); - sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); + Expr *pFirst, *pSecond; + if( exprEvalRhsFirst(pExpr) ){ + pFirst = pExpr->pRight; + pSecond = pExpr->pLeft; + }else{ + pFirst = pExpr->pLeft; + pSecond = pExpr->pRight; + } + if( op==TK_AND ){ + int d2 = sqlite3VdbeMakeLabel(pParse); + testcase( jumpIfNull==0 ); + sqlite3ExprIfFalse(pParse, pFirst, d2, + jumpIfNull^SQLITE_JUMPIFNULL); + sqlite3ExprIfTrue(pParse, pSecond, dest, jumpIfNull); + sqlite3VdbeResolveLabel(v, d2); + }else{ + testcase( jumpIfNull==0 ); + sqlite3ExprIfTrue(pParse, pFirst, dest, jumpIfNull); + sqlite3ExprIfTrue(pParse, pSecond, dest, jumpIfNull); + } } break; } @@ -115278,10 +119179,16 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int case TK_GE: case TK_NE: case TK_EQ: { + int addrIsNull; if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; - testcase( jumpIfNull==0 ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); + if( ExprHasProperty(pExpr, EP_Subquery) && jumpIfNull!=SQLITE_NULLEQ ){ + addrIsNull = exprComputeOperands(pParse, pExpr, + &r1, &r2, &regFree1, &regFree2); + }else{ + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); + addrIsNull = 0; + } codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted)); assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); @@ -115296,6 +119203,13 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); testcase( regFree1==0 ); testcase( regFree2==0 ); + if( addrIsNull ){ + if( jumpIfNull ){ + sqlite3VdbeChangeP2(v, addrIsNull, dest); + }else{ + sqlite3VdbeJumpHere(v, addrIsNull); + } + } break; } case TK_ISNULL: @@ -115303,11 +119217,11 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); - sqlite3VdbeTypeofColumn(v, r1); + assert( regFree1==0 || regFree1==r1 ); + if( regFree1 ) sqlite3VdbeTypeofColumn(v, r1); sqlite3VdbeAddOp2(v, op, r1, dest); VdbeCoverageIf(v, op==TK_ISNULL); VdbeCoverageIf(v, op==TK_NOTNULL); - testcase( regFree1==0 ); break; } case TK_BETWEEN: { @@ -115403,17 +119317,27 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr); if( pAlt!=pExpr ){ sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull); - }else if( pExpr->op==TK_AND ){ - testcase( jumpIfNull==0 ); - sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); - sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); }else{ - int d2 = sqlite3VdbeMakeLabel(pParse); - testcase( jumpIfNull==0 ); - sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, - jumpIfNull^SQLITE_JUMPIFNULL); - sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); - sqlite3VdbeResolveLabel(v, d2); + Expr *pFirst, *pSecond; + if( exprEvalRhsFirst(pExpr) ){ + pFirst = pExpr->pRight; + pSecond = pExpr->pLeft; + }else{ + pFirst = pExpr->pLeft; + pSecond = pExpr->pRight; + } + if( pExpr->op==TK_AND ){ + testcase( jumpIfNull==0 ); + sqlite3ExprIfFalse(pParse, pFirst, dest, jumpIfNull); + sqlite3ExprIfFalse(pParse, pSecond, dest, jumpIfNull); + }else{ + int d2 = sqlite3VdbeMakeLabel(pParse); + testcase( jumpIfNull==0 ); + sqlite3ExprIfTrue(pParse, pFirst, d2, + jumpIfNull^SQLITE_JUMPIFNULL); + sqlite3ExprIfFalse(pParse, pSecond, dest, jumpIfNull); + sqlite3VdbeResolveLabel(v, d2); + } } break; } @@ -115455,10 +119379,16 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int case TK_GE: case TK_NE: case TK_EQ: { + int addrIsNull; if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; - testcase( jumpIfNull==0 ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); + if( ExprHasProperty(pExpr, EP_Subquery) && jumpIfNull!=SQLITE_NULLEQ ){ + addrIsNull = exprComputeOperands(pParse, pExpr, + &r1, &r2, &regFree1, &regFree2); + }else{ + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2); + addrIsNull = 0; + } codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted)); assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); @@ -115473,16 +119403,23 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); testcase( regFree1==0 ); testcase( regFree2==0 ); + if( addrIsNull ){ + if( jumpIfNull ){ + sqlite3VdbeChangeP2(v, addrIsNull, dest); + }else{ + sqlite3VdbeJumpHere(v, addrIsNull); + } + } break; } case TK_ISNULL: case TK_NOTNULL: { r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1); - sqlite3VdbeTypeofColumn(v, r1); + assert( regFree1==0 || regFree1==r1 ); + if( regFree1 ) sqlite3VdbeTypeofColumn(v, r1); sqlite3VdbeAddOp2(v, op, r1, dest); testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL); testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL); - testcase( regFree1==0 ); break; } case TK_BETWEEN: { @@ -115548,31 +119485,37 @@ SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,i ** same as that currently bound to variable pVar, non-zero is returned. ** Otherwise, if the values are not the same or if pExpr is not a simple ** SQL value, zero is returned. +** +** If the SQLITE_EnableQPSG flag is set on the database connection, then +** this routine always returns false. */ -static int exprCompareVariable( +static SQLITE_NOINLINE int exprCompareVariable( const Parse *pParse, const Expr *pVar, const Expr *pExpr ){ - int res = 0; + int res = 2; int iVar; sqlite3_value *pL, *pR = 0; + if( pExpr->op==TK_VARIABLE && pVar->iColumn==pExpr->iColumn ){ + return 0; + } + if( (pParse->db->flags & SQLITE_EnableQPSG)!=0 ) return 2; sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR); if( pR ){ iVar = pVar->iColumn; - sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); + sqlite3VdbeReprepareOnBind(pParse->pVdbe, iVar, 0); pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB); if( pL ){ if( sqlite3_value_type(pL)==SQLITE_TEXT ){ sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */ } - res = 0==sqlite3MemCompare(pL, pR, 0); + res = sqlite3MemCompare(pL, pR, 0) ? 2 : 0; } sqlite3ValueFree(pR); sqlite3ValueFree(pL); } - return res; } @@ -115598,12 +119541,10 @@ static int exprCompareVariable( ** just might result in some slightly slower code. But returning ** an incorrect 0 or 1 could lead to a malfunction. ** -** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in -** pParse->pReprepare can be matched against literals in pB. The -** pParse->pVdbe->expmask bitmask is updated for each variable referenced. -** If pParse is NULL (the normal case) then any TK_VARIABLE term in -** Argument pParse should normally be NULL. If it is not NULL and pA or -** pB causes a return value of 2. +** If pParse is not NULL and SQLITE_EnableQPSG is off then TK_VARIABLE +** terms in pA with bindings in pParse->pReprepare can be matched against +** literals in pB. The pParse->pVdbe->expmask bitmask is updated for +** each variable referenced. */ SQLITE_PRIVATE int sqlite3ExprCompare( const Parse *pParse, @@ -115615,8 +119556,8 @@ SQLITE_PRIVATE int sqlite3ExprCompare( if( pA==0 || pB==0 ){ return pB==pA ? 0 : 2; } - if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){ - return 0; + if( pParse && pA->op==TK_VARIABLE ){ + return exprCompareVariable(pParse, pA, pB); } combinedFlags = pA->flags | pB->flags; if( combinedFlags & EP_IntValue ){ @@ -115811,18 +119752,70 @@ static int exprImpliesNotNull( return 0; } +/* +** Return true if the boolean value of the expression is always either +** FALSE or NULL. +*/ +static int sqlite3ExprIsNotTrue(Expr *pExpr){ + int v; + if( pExpr->op==TK_NULL ) return 1; + if( pExpr->op==TK_TRUEFALSE && sqlite3ExprTruthValue(pExpr)==0 ) return 1; + v = 1; + if( sqlite3ExprIsInteger(pExpr, &v, 0, 0) && v==0 ) return 1; + return 0; +} + +/* +** Return true if the expression is one of the following: +** +** CASE WHEN x THEN y END +** CASE WHEN x THEN y ELSE NULL END +** CASE WHEN x THEN y ELSE false END +** iif(x,y) +** iif(x,y,NULL) +** iif(x,y,false) +*/ +static int sqlite3ExprIsIIF(sqlite3 *db, const Expr *pExpr){ + ExprList *pList; + if( pExpr->op==TK_FUNCTION ){ + const char *z = pExpr->u.zToken; + FuncDef *pDef; + if( (z[0]!='i' && z[0]!='I') ) return 0; + if( pExpr->x.pList==0 ) return 0; + pDef = sqlite3FindFunction(db, z, pExpr->x.pList->nExpr, ENC(db), 0); +#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION + if( pDef==0 ) return 0; +#else + if( NEVER(pDef==0) ) return 0; +#endif + if( (pDef->funcFlags & SQLITE_FUNC_INLINE)==0 ) return 0; + if( SQLITE_PTR_TO_INT(pDef->pUserData)!=INLINEFUNC_iif ) return 0; + }else if( pExpr->op==TK_CASE ){ + if( pExpr->pLeft!=0 ) return 0; + }else{ + return 0; + } + pList = pExpr->x.pList; + assert( pList!=0 ); + if( pList->nExpr==2 ) return 1; + if( pList->nExpr==3 && sqlite3ExprIsNotTrue(pList->a[2].pExpr) ) return 1; + return 0; +} + /* ** Return true if we can prove the pE2 will always be true if pE1 is ** true. Return false if we cannot complete the proof or if pE2 might ** be false. Examples: ** -** pE1: x==5 pE2: x==5 Result: true -** pE1: x>0 pE2: x==5 Result: false -** pE1: x=21 pE2: x=21 OR y=43 Result: true -** pE1: x!=123 pE2: x IS NOT NULL Result: true -** pE1: x!=?1 pE2: x IS NOT NULL Result: true -** pE1: x IS NULL pE2: x IS NOT NULL Result: false -** pE1: x IS ?2 pE2: x IS NOT NULL Result: false +** pE1: x==5 pE2: x==5 Result: true +** pE1: x>0 pE2: x==5 Result: false +** pE1: x=21 pE2: x=21 OR y=43 Result: true +** pE1: x!=123 pE2: x IS NOT NULL Result: true +** pE1: x!=?1 pE2: x IS NOT NULL Result: true +** pE1: x IS NULL pE2: x IS NOT NULL Result: false +** pE1: x IS ?2 pE2: x IS NOT NULL Result: false +** pE1: iif(x,y) pE2: x Result: true +** PE1: iif(x,y,0) pE2: x Result: true ** ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has ** Expr.iTable<0 then assume a table number given by iTab. @@ -115856,6 +119849,9 @@ SQLITE_PRIVATE int sqlite3ExprImpliesExpr( ){ return 1; } + if( sqlite3ExprIsIIF(pParse->db, pE1) ){ + return sqlite3ExprImpliesExpr(pParse,pE1->x.pList->a[0].pExpr,pE2,iTab); + } return 0; } @@ -116323,7 +120319,9 @@ static void findOrCreateAggInfoColumn( ){ struct AggInfo_col *pCol; int k; + int mxTerm = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; + assert( mxTerm <= SMXV(i16) ); assert( pAggInfo->iFirstReg==0 ); pCol = pAggInfo->aCol; for(k=0; k<pAggInfo->nColumn; k++, pCol++){ @@ -116341,6 +120339,10 @@ static void findOrCreateAggInfoColumn( assert( pParse->db->mallocFailed ); return; } + if( k>mxTerm ){ + sqlite3ErrorMsg(pParse, "more than %d aggregate terms", mxTerm); + k = mxTerm; + } pCol = &pAggInfo->aCol[k]; assert( ExprUseYTab(pExpr) ); pCol->pTab = pExpr->y.pTab; @@ -116374,6 +120376,7 @@ static void findOrCreateAggInfoColumn( if( pExpr->op==TK_COLUMN ){ pExpr->op = TK_AGG_COLUMN; } + assert( k <= SMXV(pExpr->iAgg) ); pExpr->iAgg = (i16)k; } @@ -116406,7 +120409,10 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ if( pIEpr==0 ) break; if( NEVER(!ExprUseYTab(pExpr)) ) break; for(i=0; i<pSrcList->nSrc; i++){ - if( pSrcList->a[0].iCursor==pIEpr->iDataCur ) break; + if( pSrcList->a[i].iCursor==pIEpr->iDataCur ){ + testcase( i>0 ); + break; + } } if( i>=pSrcList->nSrc ) break; if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */ @@ -116458,13 +120464,19 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ ** function that is already in the pAggInfo structure */ struct AggInfo_func *pItem = pAggInfo->aFunc; + int mxTerm = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; + assert( mxTerm <= SMXV(i16) ); for(i=0; i<pAggInfo->nFunc; i++, pItem++){ if( NEVER(pItem->pFExpr==pExpr) ) break; if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){ break; } } - if( i>=pAggInfo->nFunc ){ + if( i>mxTerm ){ + sqlite3ErrorMsg(pParse, "more than %d aggregate terms", mxTerm); + i = mxTerm; + assert( i<pAggInfo->nFunc ); + }else if( i>=pAggInfo->nFunc ){ /* pExpr is original. Make a new entry in pAggInfo->aFunc[] */ u8 enc = ENC(pParse->db); @@ -116495,7 +120507,7 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ if( pOBList->nExpr==1 && nArg==1 && sqlite3ExprCompare(0,pOBList->a[0].pExpr, - pExpr->x.pList->a[0].pExpr,0)==0 + pExpr->x.pList->a[0].pExpr,-1)==0 ){ pItem->bOBPayload = 0; pItem->bOBUnique = ExprHasProperty(pExpr, EP_Distinct); @@ -116518,6 +120530,7 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ */ assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); ExprSetVVAProperty(pExpr, EP_NoReduce); + assert( i <= SMXV(pExpr->iAgg) ); pExpr->iAgg = (i16)i; pExpr->pAggInfo = pAggInfo; return WRC_Prune; @@ -116582,6 +120595,13 @@ SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){ */ SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ if( iReg ){ +#ifdef SQLITE_DEBUG + /* Verify that iReg is not already on the unused register list */ + int kk; + for(kk=0; kk<pParse->nTempReg; kk++){ + assert( pParse->aTempReg[kk]!=iReg ); + } +#endif sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0); if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){ pParse->aTempReg[pParse->nTempReg++] = iReg; @@ -116999,6 +121019,30 @@ static void sqlite3ErrorIfNotEmpty( ); } +/* +** zCol is a column name used in an ALTER TABLE DROP, ADD or RENAME COLUMN +** operation. zOp identifies the specific operation - "drop", "add", "rename +** to" or "rename from". pTab is the table being altered. +** +** If pTab has a rowid and zCol is a rowid alias, then SQLITE_ERROR is +** returned and an error message left in pParse. Or, if zCol is not an alias +** for "rowid" or pTab is not an intkey table, then SQLITE_OK is returned. +*/ +static int isRowidAlias( + Parse *pParse, + Table *pTab, + const char *zCol, + const char *zOp +){ + if( HasRowid(pTab) && sqlite3IsRowid(zCol) ){ + sqlite3ErrorMsg(pParse, "cannot %s rowid alias: %s", zOp, zCol); + return SQLITE_ERROR; + } + return SQLITE_OK; +} + + + /* ** This function is called after an "ALTER TABLE ... ADD" statement ** has been parsed. Argument pColDef contains the text of the new @@ -117044,9 +121088,9 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ #endif - /* Check that the new column is not specified as PRIMARY KEY or UNIQUE. - ** If there is a NOT NULL constraint, then the default value for the - ** column must not be NULL. + /* Check that the new column is not specified as PRIMARY KEY or UNIQUE, + ** or a rowid alias. If there is a NOT NULL constraint, then the default + ** value for the column must not be NULL. */ if( pCol->colFlags & COLFLAG_PRIMKEY ){ sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column"); @@ -117057,6 +121101,7 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ "Cannot add a UNIQUE column"); return; } + if( isRowidAlias(pParse, pTab, pCol->zCnName, "add") ) return; if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){ /* If the default value for the new column was specified with a ** literal NULL, then set pDflt to 0. This simplifies checking @@ -117145,6 +121190,7 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0) || (pTab->tabFlags & TF_Strict)!=0 ){ + pParse->colNamesSet = 1; sqlite3NestedParse(pParse, "SELECT CASE WHEN quick_check GLOB 'CHECK*'" " THEN raise(ABORT,'CHECK constraint failed')" @@ -117188,7 +121234,7 @@ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ /* Look up the table being altered. */ assert( pParse->pNewTable==0 ); assert( sqlite3BtreeHoldsAllMutexes(db) ); - if( db->mallocFailed ) goto exit_begin_add_column; + if( NEVER(db->mallocFailed) ) goto exit_begin_add_column; pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); if( !pTab ) goto exit_begin_add_column; @@ -117228,13 +121274,13 @@ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ assert( pNew->nCol>0 ); nAlloc = (((pNew->nCol-1)/8)*8)+8; assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 ); - pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc); + pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*(u32)nAlloc); pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName); if( !pNew->aCol || !pNew->zName ){ assert( db->mallocFailed ); goto exit_begin_add_column; } - memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol); + memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*(size_t)pNew->nCol); for(i=0; i<pNew->nCol; i++){ Column *pCol = &pNew->aCol[i]; pCol->zCnName = sqlite3DbStrDup(db, pCol->zCnName); @@ -117260,7 +121306,7 @@ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ ** Or, if pTab is not a view or virtual table, zero is returned. */ #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) -static int isRealTable(Parse *pParse, Table *pTab, int bDrop){ +static int isRealTable(Parse *pParse, Table *pTab, int iOp){ const char *zType = 0; #ifndef SQLITE_OMIT_VIEW if( IsView(pTab) ){ @@ -117273,9 +121319,12 @@ static int isRealTable(Parse *pParse, Table *pTab, int bDrop){ } #endif if( zType ){ + const char *azMsg[] = { + "rename columns of", "drop column from", "edit constraints of" + }; + assert( iOp>=0 && iOp<ArraySize(azMsg) ); sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"", - (bDrop ? "drop column from" : "rename columns of"), - zType, pTab->zName + azMsg[iOp], zType, pTab->zName ); return 1; } @@ -117329,10 +121378,8 @@ SQLITE_PRIVATE void sqlite3AlterRenameColumn( ** altered. Set iCol to be the index of the column being renamed */ zOld = sqlite3NameFromToken(db, pOld); if( !zOld ) goto exit_rename_column; - for(iCol=0; iCol<pTab->nCol; iCol++){ - if( 0==sqlite3StrICmp(pTab->aCol[iCol].zCnName, zOld) ) break; - } - if( iCol==pTab->nCol ){ + iCol = sqlite3ColumnIndex(pTab, zOld); + if( iCol<0 ){ sqlite3ErrorMsg(pParse, "no such column: \"%T\"", pOld); goto exit_rename_column; } @@ -117348,6 +121395,8 @@ SQLITE_PRIVATE void sqlite3AlterRenameColumn( sqlite3MayAbort(pParse); zNew = sqlite3NameFromToken(db, pNew); if( !zNew ) goto exit_rename_column; + if( isRowidAlias(pParse, pTab, zOld, "rename from") ) goto exit_rename_column; + if( isRowidAlias(pParse, pTab, zNew, "rename to") ) goto exit_rename_column; assert( pNew->n>0 ); bQuote = sqlite3Isquote(pNew->z[0]); sqlite3NestedParse(pParse, @@ -117748,6 +121797,25 @@ static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){ return pBest; } +/* +** Set the error message of the context passed as the first argument to +** the result of formatting zFmt using printf() style formatting. +*/ +static void errorMPrintf(sqlite3_context *pCtx, const char *zFmt, ...){ + sqlite3 *db = sqlite3_context_db_handle(pCtx); + char *zErr = 0; + va_list ap; + va_start(ap, zFmt); + zErr = sqlite3VMPrintf(db, zFmt, ap); + va_end(ap); + if( zErr ){ + sqlite3_result_error(pCtx, zErr, -1); + sqlite3DbFree(db, zErr); + }else{ + sqlite3_result_error_nomem(pCtx); + } +} + /* ** An error occurred while parsing or otherwise processing a database ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an @@ -117835,6 +121903,7 @@ static int renameParseSql( int bTemp /* True if SQL is from temp schema */ ){ int rc; + u64 flags; sqlite3ParseObjectInit(p, db); if( zSql==0 ){ @@ -117843,11 +121912,21 @@ static int renameParseSql( if( sqlite3StrNICmp(zSql,"CREATE ",7)!=0 ){ return SQLITE_CORRUPT_BKPT; } - db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb); + if( bTemp ){ + db->init.iDb = 1; + }else{ + int iDb = sqlite3FindDbName(db, zDb); + assert( iDb>=0 && iDb<=0xff ); + db->init.iDb = (u8)iDb; + } p->eParseMode = PARSE_MODE_RENAME; p->db = db; p->nQueryLoop = 1; + flags = db->flags; + testcase( (db->flags & SQLITE_Comments)==0 && strstr(zSql," /* ")!=0 ); + db->flags |= SQLITE_Comments; rc = sqlite3RunParser(p, zSql); + db->flags = flags; if( db->mallocFailed ) rc = SQLITE_NOMEM; if( rc==SQLITE_OK && NEVER(p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0) @@ -117910,10 +121989,11 @@ static int renameEditSql( nQuot = sqlite3Strlen30(zQuot)-1; } - assert( nQuot>=nNew ); - zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1); + assert( nQuot>=nNew && nSql>=0 && nNew>=0 ); + zOut = sqlite3DbMallocZero(db, (u64)nSql + pRename->nList*(u64)nQuot + 1); }else{ - zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3); + assert( nSql>0 ); + zOut = (char*)sqlite3DbMallocZero(db, (2*(u64)nSql + 1) * 3); if( zOut ){ zBuf1 = &zOut[nSql*2+1]; zBuf2 = &zOut[nSql*4+2]; @@ -117925,16 +122005,17 @@ static int renameEditSql( ** with the new column name, or with single-quoted versions of themselves. ** All that remains is to construct and return the edited SQL string. */ if( zOut ){ - int nOut = nSql; - memcpy(zOut, zSql, nSql); + i64 nOut = nSql; + assert( nSql>0 ); + memcpy(zOut, zSql, (size_t)nSql); while( pRename->pList ){ int iOff; /* Offset of token to replace in zOut */ - u32 nReplace; + i64 nReplace; const char *zReplace; RenameToken *pBest = renameColumnTokenNext(pRename); if( zNew ){ - if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){ + if( bQuote==0 && sqlite3IsIdChar(*(u8*)pBest->t.z) ){ nReplace = nNew; zReplace = zNew; }else{ @@ -117952,14 +122033,15 @@ static int renameEditSql( memcpy(zBuf1, pBest->t.z, pBest->t.n); zBuf1[pBest->t.n] = 0; sqlite3Dequote(zBuf1); - sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1, + assert( nSql < 0x15555554 /* otherwise malloc would have failed */ ); + sqlite3_snprintf((int)(nSql*2), zBuf2, "%Q%s", zBuf1, pBest->t.z[pBest->t.n]=='\'' ? " " : "" ); zReplace = zBuf2; nReplace = sqlite3Strlen30(zReplace); } - iOff = pBest->t.z - zSql; + iOff = (int)(pBest->t.z - zSql); if( pBest->t.n!=nReplace ){ memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n], nOut - (iOff + pBest->t.n) @@ -117985,11 +122067,12 @@ static int renameEditSql( ** Set all pEList->a[].fg.eEName fields in the expression-list to val. */ static void renameSetENames(ExprList *pEList, int val){ + assert( val==ENAME_NAME || val==ENAME_TAB || val==ENAME_SPAN ); if( pEList ){ int i; for(i=0; i<pEList->nExpr; i++){ assert( val==ENAME_NAME || pEList->a[i].fg.eEName==ENAME_NAME ); - pEList->a[i].fg.eEName = val; + pEList->a[i].fg.eEName = val&0x3; } } } @@ -118030,8 +122113,8 @@ static int renameResolveTrigger(Parse *pParse){ sqlite3SelectPrep(pParse, pStep->pSelect, &sNC); if( pParse->nErr ) rc = pParse->rc; } - if( rc==SQLITE_OK && pStep->zTarget ){ - SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep); + if( rc==SQLITE_OK && pStep->pSrc ){ + SrcList *pSrc = sqlite3SrcListDup(db, pStep->pSrc, 0); if( pSrc ){ Select *pSel = sqlite3SelectNew( pParse, pStep->pExprList, pSrc, 0, 0, 0, 0, 0, 0 @@ -118059,10 +122142,10 @@ static int renameResolveTrigger(Parse *pParse){ pSel->pSrc = 0; sqlite3SelectDelete(db, pSel); } - if( pStep->pFrom ){ + if( ALWAYS(pStep->pSrc) ){ int i; - for(i=0; i<pStep->pFrom->nSrc && rc==SQLITE_OK; i++){ - SrcItem *p = &pStep->pFrom->a[i]; + for(i=0; i<pStep->pSrc->nSrc && rc==SQLITE_OK; i++){ + SrcItem *p = &pStep->pSrc->a[i]; if( p->fg.isSubquery ){ assert( p->u4.pSubq!=0 ); sqlite3SelectPrep(pParse, p->u4.pSubq->pSelect, 0); @@ -118131,13 +122214,13 @@ static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){ sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere); sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere); } - if( pStep->pFrom ){ + if( pStep->pSrc ){ int i; - SrcList *pFrom = pStep->pFrom; - for(i=0; i<pFrom->nSrc; i++){ - if( pFrom->a[i].fg.isSubquery ){ - assert( pFrom->a[i].u4.pSubq!=0 ); - sqlite3WalkSelect(pWalker, pFrom->a[i].u4.pSubq->pSelect); + SrcList *pSrc = pStep->pSrc; + for(i=0; i<pSrc->nSrc; i++){ + if( pSrc->a[i].fg.isSubquery ){ + assert( pSrc->a[i].u4.pSubq!=0 ); + sqlite3WalkSelect(pWalker, pSrc->a[i].u4.pSubq->pSelect); } } } @@ -118246,7 +122329,7 @@ static void renameColumnFunc( if( sParse.pNewTable ){ if( IsView(sParse.pNewTable) ){ Select *pSelect = sParse.pNewTable->u.view.pSelect; - pSelect->selFlags &= ~SF_View; + pSelect->selFlags &= ~(u32)SF_View; sParse.rc = SQLITE_OK; sqlite3SelectPrep(&sParse, pSelect, 0); rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc); @@ -118308,8 +122391,8 @@ static void renameColumnFunc( if( rc!=SQLITE_OK ) goto renameColumnFunc_done; for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){ - if( pStep->zTarget ){ - Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb); + if( pStep->pSrc ){ + Table *pTarget = sqlite3LocateTableItem(&sParse, 0, &pStep->pSrc->a[0]); if( pTarget==pTab ){ if( pStep->pUpsert ){ ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet; @@ -118321,7 +122404,6 @@ static void renameColumnFunc( } } - /* Find tokens to edit in UPDATE OF clause */ if( sParse.pTriggerTab==pTab ){ renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld); @@ -118464,7 +122546,7 @@ static void renameTableFunc( sNC.pParse = &sParse; assert( pSelect->selFlags & SF_View ); - pSelect->selFlags &= ~SF_View; + pSelect->selFlags &= ~(u32)SF_View; sqlite3SelectPrep(&sParse, pTab->u.view.pSelect, &sNC); if( sParse.nErr ){ rc = sParse.rc; @@ -118523,13 +122605,10 @@ static void renameTableFunc( if( rc==SQLITE_OK ){ renameWalkTrigger(&sWalker, pTrigger); for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){ - if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){ - renameTokenFind(&sParse, &sCtx, pStep->zTarget); - } - if( pStep->pFrom ){ + if( pStep->pSrc ){ int i; - for(i=0; i<pStep->pFrom->nSrc; i++){ - SrcItem *pItem = &pStep->pFrom->a[i]; + for(i=0; i<pStep->pSrc->nSrc; i++){ + SrcItem *pItem = &pStep->pSrc->a[i]; if( 0==sqlite3_stricmp(pItem->zName, zOld) ){ renameTokenFind(&sParse, &sCtx, pItem->zName); } @@ -118637,7 +122716,7 @@ static void renameQuotefixFunc( if( sParse.pNewTable ){ if( IsView(sParse.pNewTable) ){ Select *pSelect = sParse.pNewTable->u.view.pSelect; - pSelect->selFlags &= ~SF_View; + pSelect->selFlags &= ~(u32)SF_View; sParse.rc = SQLITE_OK; sqlite3SelectPrep(&sParse, pSelect, 0); rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc); @@ -118736,10 +122815,10 @@ static void renameTableTest( if( zDb && zInput ){ int rc; Parse sParse; - int flags = db->flags; + u64 flags = db->flags; if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL); rc = renameParseSql(&sParse, zDb, db, zInput, bTemp); - db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL)); + db->flags = flags; if( rc==SQLITE_OK ){ if( isLegacy==0 && sParse.pNewTable && IsView(sParse.pNewTable) ){ NameContext sNC; @@ -118776,6 +122855,57 @@ static void renameTableTest( #endif } + +/* +** Return the number of bytes until the end of the next non-whitespace and +** non-comment token. For the purpose of this function, a "(" token includes +** all of the bytes through and including the matching ")", or until the +** first illegal token, whichever comes first. +** +** Write the token type into *piToken. +** +** The value returned is the number of bytes in the token itself plus +** the number of bytes of leading whitespace and comments skipped plus +** all bytes through the next matching ")" if the token is TK_LP. +** +** Example: (Note: '.' used in place of '*' in the example z[] text) +** +** ,--------- *piToken := TK_RP +** v +** z[] = " /.comment./ --comment\n (two three four) five" +** | | +** |<-------------------------------------->| +** | +** `--- return value +*/ +static int getConstraintToken(const u8 *z, int *piToken){ + int iOff = 0; + int t = 0; + do { + iOff += sqlite3GetToken(&z[iOff], &t); + }while( t==TK_SPACE || t==TK_COMMENT ); + + *piToken = t; + + if( t==TK_LP ){ + int nNest = 1; + while( nNest>0 ){ + iOff += sqlite3GetToken(&z[iOff], &t); + if( t==TK_LP ){ + nNest++; + }else if( t==TK_RP ){ + t = TK_LP; + nNest--; + }else if( t==TK_ILLEGAL ){ + break; + } + } + } + + *piToken = t; + return iOff; +} + /* ** The implementation of internal UDF sqlite_drop_column(). ** @@ -118820,15 +122950,24 @@ static void dropColumnFunc( goto drop_column_done; } - pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zCnName); if( iCol<pTab->nCol-1 ){ RenameToken *pEnd; + pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zCnName); pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zCnName); zEnd = (const char*)pEnd->t.z; }else{ + int eTok; assert( IsOrdinaryTable(pTab) ); + assert( iCol!=0 ); + /* Point pCol->t.z at the "," immediately preceding the definition of + ** the column being dropped. To do this, start at the name of the + ** previous column, and tokenize until the next ",". */ + pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol-1].zCnName); + do { + pCol->t.z += getConstraintToken((const u8*)pCol->t.z, &eTok); + }while( eTok!=TK_COMMA ); + pCol->t.z--; zEnd = (const char*)&zSql[pTab->u.tab.addColOffset]; - while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--; } zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd); @@ -118884,6 +123023,7 @@ SQLITE_PRIVATE void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, const T sqlite3ErrorMsg(pParse, "no such column: \"%T\"", pName); goto exit_drop_column; } + if( isRowidAlias(pParse, pTab, zCol, "drop") ) goto exit_drop_column; /* Do not allow the user to drop a PRIMARY KEY column or a column ** constrained by a UNIQUE constraint. */ @@ -118997,6 +123137,684 @@ SQLITE_PRIVATE void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, const T sqlite3SrcListDelete(db, pSrc); } +/* +** Return the number of bytes of leading whitespace/comments in string z[]. +*/ +static int getWhitespace(const u8 *z){ + int nRet = 0; + while( 1 ){ + int t = 0; + int n = sqlite3GetToken(&z[nRet], &t); + if( t!=TK_SPACE && t!=TK_COMMENT ) break; + nRet += n; + } + return nRet; +} + + +/* +** Argument z points into the body of a constraint - specifically the +** second token of the constraint definition. For a named constraint, +** z points to the second token of the constraint definition. For an +** unnamed NOT NULL constraint, z points to the first byte past the NOT +** keyword. +** +** Argument eTok may be the token value of the first token of the constraint +** (e.g. TK_CHECK or TK_REFERENCES) or zero. If it is either TK_REFERENCES +** or TK_FOREIGN, special parsing is enabled to find the end of the foreign-key +** constraint definition. +** +** Return the number of bytes until the end of the constraint. +*/ +static int getConstraint(const u8 *z, int eTok){ + int iOff = 0; + int t = 0; + +#ifndef SQLITE_OMIT_FOREIGN_KEY + if( eTok==TK_FOREIGN ){ + /* For a FOREIGN KEY constraint, use getConstraint() to parse everything + ** up to the REFERENCES keyword. Then getConstraintToken() to consume + ** the TK_REFERENCES token itself. Then fall through to the special + ** handling for TK_REFERENCES below. */ + iOff = getConstraint(z, 0); + iOff += getConstraintToken(&z[iOff], &eTok); + } + + if( eTok==TK_REFERENCES ){ + /* REFERENCES is followed by a table name. Gobble this up here in + ** case the table name is a fallback token like TK_GENERATED. */ + iOff += getConstraintToken(&z[iOff], &t); + } +#endif + + /* Now, the current constraint proceeds until the next occurence of one + ** of the following tokens: + ** + ** CONSTRAINT, PRIMARY, NOT, UNIQUE, CHECK, DEFAULT, + ** COLLATE, REFERENCES, FOREIGN, GENERATED, AS, RP, or COMMA + ** + ** Also exit the loop if ILLEGAL turns up. + */ + while( 1 ){ + int n = getConstraintToken(&z[iOff], &t); + if( t==TK_CONSTRAINT || t==TK_PRIMARY || t==TK_NOT || t==TK_UNIQUE + || t==TK_CHECK || t==TK_DEFAULT || t==TK_COLLATE || t==TK_REFERENCES + || t==TK_FOREIGN || t==TK_RP || t==TK_COMMA || t==TK_ILLEGAL + || t==TK_AS || t==TK_GENERATED + ){ + break; + } + iOff += n; + } + + return iOff; +} + +/* +** Compare two constraint names. +** +** Summary: *pRes := zQuote != zCmp +** +** Details: +** Compare the (possibly quoted) constraint name zQuote[0..nQuote-1] +** against zCmp[]. Write zero into *pRes if they are the same and +** non-zero if they differ. Normally return SQLITE_OK, except if there +** is an OOM, set the OOM error condition on ctx and return SQLITE_NOMEM. +*/ +static int quotedCompare( + sqlite3_context *ctx, /* Function context on which to report errors */ + int t, /* Token type */ + const u8 *zQuote, /* Possibly quoted text. Not zero-terminated. */ + int nQuote, /* Length of zQuote in bytes */ + const u8 *zCmp, /* Zero-terminated, unquoted name to compare against */ + int *pRes /* OUT: Set to 0 if equal, non-zero if unequal */ +){ + char *zCopy = 0; /* De-quoted, zero-terminated copy of zQuote[] */ + + if( t==TK_ILLEGAL ){ + *pRes = 1; + return SQLITE_OK; + } + zCopy = sqlite3MallocZero(nQuote+1); + if( zCopy==0 ){ + sqlite3_result_error_nomem(ctx); + return SQLITE_NOMEM_BKPT; + } + memcpy(zCopy, zQuote, nQuote); + sqlite3Dequote(zCopy); + *pRes = sqlite3_stricmp((const char*)zCopy, (const char*)zCmp); + sqlite3_free(zCopy); + return SQLITE_OK; +} + +/* +** zSql[] is a CREATE TABLE statement, supposedly. Find the offset +** into zSql[] of the first character past the first "(" and write +** that offset into *piOff and return SQLITE_OK. Or, if not found, +** set the SQLITE_CORRUPT error code and return SQLITE_ERROR. +*/ +static int skipCreateTable(sqlite3_context *ctx, const u8 *zSql, int *piOff){ + int iOff = 0; + + if( zSql==0 ) return SQLITE_ERROR; + + /* Jump past the "CREATE TABLE" bit. */ + while( 1 ){ + int t = 0; + iOff += sqlite3GetToken(&zSql[iOff], &t); + if( t==TK_LP ) break; + if( t==TK_ILLEGAL ){ + sqlite3_result_error_code(ctx, SQLITE_CORRUPT_BKPT); + return SQLITE_ERROR; + } + } + + *piOff = iOff; + return SQLITE_OK; +} + +/* +** Internal SQL function sqlite3_drop_constraint(): Given an input +** CREATE TABLE statement, return a revised CREATE TABLE statement +** with a constraint removed. Two forms, depending on the datatype +** of argv[2]: +** +** sqlite_drop_constraint(SQL, INT) -- Omit NOT NULL from the INT-th column +** sqlite_drop_constraint(SQL, TEXT) -- OMIT constraint with name TEXT +** +** In the first case, the left-most column is 0. +*/ +static void dropConstraintFunc( + sqlite3_context *ctx, + int NotUsed, + sqlite3_value **argv +){ + const u8 *zSql = sqlite3_value_text(argv[0]); + const u8 *zCons = 0; + int iNotNull = -1; + int ii; + int iOff = 0; + int iStart = 0; + int iEnd = 0; + char *zNew = 0; + int t = 0; + sqlite3 *db; + UNUSED_PARAMETER(NotUsed); + + if( zSql==0 ) return; + + /* Jump past the "CREATE TABLE" bit. */ + if( skipCreateTable(ctx, zSql, &iOff) ) return; + + if( sqlite3_value_type(argv[1])==SQLITE_INTEGER ){ + iNotNull = sqlite3_value_int(argv[1]); + }else{ + zCons = sqlite3_value_text(argv[1]); + } + + /* Search for the named constraint within column definitions. */ + for(ii=0; iEnd==0; ii++){ + + /* Now parse the column or table constraint definition. Search + ** for the token CONSTRAINT if this is a DROP CONSTRAINT command, or + ** NOT in the right column if this is a DROP NOT NULL. */ + while( 1 ){ + iStart = iOff; + iOff += getConstraintToken(&zSql[iOff], &t); + if( t==TK_CONSTRAINT && (zCons || iNotNull==ii) ){ + /* Check if this is the constraint we are searching for. */ + int nTok = 0; + int cmp = 1; + + /* Skip past any whitespace. */ + iOff += getWhitespace(&zSql[iOff]); + + /* Compare the next token - which may be quoted - with the name of + ** the constraint being dropped. */ + nTok = getConstraintToken(&zSql[iOff], &t); + if( zCons ){ + if( quotedCompare(ctx, t, &zSql[iOff], nTok, zCons, &cmp) ) return; + } + iOff += nTok; + + /* The next token is usually the first token of the constraint + ** definition. This is enough to tell the type of the constraint - + ** TK_NOT means it is a NOT NULL, TK_CHECK a CHECK constraint etc. + ** + ** There is also the chance that the next token is TK_CONSTRAINT + ** (or TK_DEFAULT or TK_COLLATE), for example if a table has been + ** created as follows: + ** + ** CREATE TABLE t1(cols, CONSTRAINT one CONSTRAINT two NOT NULL); + ** + ** In this case, allow the "CONSTRAINT one" bit to be dropped by + ** this command if that is what is requested, or to advance to + ** the next iteration of the loop with &zSql[iOff] still pointing + ** to the CONSTRAINT keyword. */ + nTok = getConstraintToken(&zSql[iOff], &t); + if( t==TK_CONSTRAINT || t==TK_DEFAULT || t==TK_COLLATE + || t==TK_COMMA || t==TK_RP || t==TK_GENERATED || t==TK_AS + ){ + t = TK_CHECK; + }else{ + iOff += nTok; + iOff += getConstraint(&zSql[iOff], t); + } + + if( cmp==0 || (iNotNull>=0 && t==TK_NOT) ){ + if( t!=TK_NOT && t!=TK_CHECK && t!=TK_REFERENCES && t!=TK_FOREIGN ){ + errorMPrintf(ctx, "constraint may not be dropped: %s", zCons); + return; + } + iEnd = iOff; + break; + } + + }else if( t==TK_NOT && iNotNull==ii ){ + iEnd = iOff + getConstraint(&zSql[iOff], 0); + break; + }else if( t==TK_RP || t==TK_ILLEGAL ){ + iEnd = -1; + break; + }else if( t==TK_COMMA ){ + break; + } + } + } + + /* If the constraint has not been found it is an error. */ + if( iEnd<=0 ){ + if( zCons ){ + errorMPrintf(ctx, "no such constraint: %s", zCons); + }else{ + /* SQLite follows postgres in that a DROP NOT NULL on a column that is + ** not NOT NULL is not an error. So just return the original SQL here. */ + sqlite3_result_text(ctx, (const char*)zSql, -1, SQLITE_TRANSIENT); + } + }else{ + + /* Figure out if an extra space should be inserted after the constraint + ** is removed. And if an additional comma preceding the constraint + ** should be removed. */ + const char *zSpace = " "; + iEnd += getWhitespace(&zSql[iEnd]); + sqlite3GetToken(&zSql[iEnd], &t); + if( t==TK_RP || t==TK_COMMA ){ + zSpace = ""; + if( zSql[iStart-1]==',' ) iStart--; + } + + db = sqlite3_context_db_handle(ctx); + zNew = sqlite3MPrintf(db, "%.*s%s%s", iStart, zSql, zSpace, &zSql[iEnd]); + sqlite3_result_text(ctx, zNew, -1, SQLITE_DYNAMIC); + } +} + +/* +** Internal SQL function: +** +** sqlite_add_constraint(SQL, CONSTRAINT-TEXT, ICOL) +** +** SQL is a CREATE TABLE statement. Return a modified version of +** SQL that adds CONSTRAINT-TEXT at the end of the ICOL-th column +** definition. (The left-most column defintion is 0.) +*/ +static void addConstraintFunc( + sqlite3_context *ctx, + int NotUsed, + sqlite3_value **argv +){ + const u8 *zSql = sqlite3_value_text(argv[0]); + const char *zCons = (const char*)sqlite3_value_text(argv[1]); + int iCol = sqlite3_value_int(argv[2]); + int iOff = 0; + int ii; + sqlite3_str *pNew; + int t = 0; + UNUSED_PARAMETER(NotUsed); + + if( skipCreateTable(ctx, zSql, &iOff) ) return; + + for(ii=0; ii<=iCol || (iCol<0 && t!=TK_RP); ii++){ + iOff += getConstraintToken(&zSql[iOff], &t); + while( 1 ){ + int nTok = getConstraintToken(&zSql[iOff], &t); + if( t==TK_COMMA || t==TK_RP ) break; + if( t==TK_ILLEGAL ){ + sqlite3_result_error_code(ctx, SQLITE_CORRUPT_BKPT); + return; + } + iOff += nTok; + } + } + + iOff += getWhitespace(&zSql[iOff]); + + pNew = sqlite3_str_new(sqlite3_context_db_handle(ctx)); + sqlite3_str_append(pNew, (const char*)zSql, iOff); + if( iCol<0 ) sqlite3_str_append(pNew, ",", 1); + sqlite3_str_appendf(pNew, " %s%s", zCons, &zSql[iOff]); + sqlite3_result_str(ctx, pNew, SQLITE_FINISH); +} + +/* +** Find a column named pCol in table pTab. If successful, set output +** parameter *piCol to the index of the column in the table and return +** SQLITE_OK. Otherwise, set *piCol to -1 and return an SQLite error +** code. +*/ +static int alterFindCol(Parse *pParse, Table *pTab, Token *pCol, int *piCol){ + sqlite3 *db = pParse->db; + char *zName = sqlite3NameFromToken(db, pCol); + int rc = SQLITE_NOMEM; + int iCol = -1; + + if( zName ){ + iCol = sqlite3ColumnIndex(pTab, zName); + if( iCol<0 ){ + sqlite3ErrorMsg(pParse, "no such column: %s", zName); + rc = SQLITE_ERROR; + }else{ + rc = SQLITE_OK; + } + } + +#ifndef SQLITE_OMIT_AUTHORIZATION + if( rc==SQLITE_OK ){ + const char *zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName; + const char *zCol = pTab->aCol[iCol].zCnName; + if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, zCol) ){ + pTab = 0; + } + } +#endif + + sqlite3DbFree(db, zName); + *piCol = iCol; + return rc; +} + + +/* +** Find the table named by the first entry in source list pSrc. If successful, +** return a pointer to the Table structure and set output variable (*pzDb) +** to point to the name of the database containin the table (i.e. "main", +** "temp" or the name of an attached database). +** +** If the table cannot be located, return NULL. The value of the two output +** parameters is undefined in this case. +*/ +static Table *alterFindTable( + Parse *pParse, /* Parsing context */ + SrcList *pSrc, /* Name of the table to look for */ + int *piDb, /* OUT: write the iDb here */ + const char **pzDb, /* OUT: write name of schema here */ + int bAuth /* Do ALTER TABLE authorization checks if true */ +){ + sqlite3 *db = pParse->db; + Table *pTab = 0; + assert( sqlite3BtreeHoldsAllMutexes(db) ); + pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); + if( pTab ){ + int iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + *pzDb = db->aDb[iDb].zDbSName; + *piDb = iDb; + + if( SQLITE_OK!=isRealTable(pParse, pTab, 2) + || SQLITE_OK!=isAlterableTable(pParse, pTab) + ){ + pTab = 0; + } + } +#ifndef SQLITE_OMIT_AUTHORIZATION + if( pTab && bAuth ){ + if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, *pzDb, pTab->zName, 0) ){ + pTab = 0; + } + } +#endif + sqlite3SrcListDelete(db, pSrc); + return pTab; +} + +/* +** Generate bytecode for one of: +** +** (1) ALTER TABLE pSrc DROP CONSTRAINT pCons +** (2) ALTER TABLE pSrc ALTER pCol DROP NOT NULL +** +** One of pCons and pCol must be NULL and the other non-null. +*/ +SQLITE_PRIVATE void sqlite3AlterDropConstraint( + Parse *pParse, /* Parsing context */ + SrcList *pSrc, /* The table being altered */ + Token *pCons, /* Name of the constraint to drop */ + Token *pCol /* Name of the column from which to remove the NOT NULL */ +){ + sqlite3 *db = pParse->db; + Table *pTab = 0; + int iDb = 0; + const char *zDb = 0; + char *zArg = 0; + + assert( (pCol==0)!=(pCons==0) ); + assert( pSrc->nSrc==1 ); + pTab = alterFindTable(pParse, pSrc, &iDb, &zDb, pCons!=0); + if( !pTab ) return; + + if( pCons ){ + char *z = sqlite3NameFromToken(db, pCons); + zArg = sqlite3MPrintf(db, "%Q", z); + sqlite3DbFree(db, z); + }else{ + int iCol; + if( alterFindCol(pParse, pTab, pCol, &iCol) ) return; + zArg = sqlite3MPrintf(db, "%d", iCol); + } + + /* Edit the SQL for the named table. */ + sqlite3NestedParse(pParse, + "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET " + "sql = sqlite_drop_constraint(sql, %s) " + "WHERE type='table' AND tbl_name=%Q COLLATE nocase" + , zDb, zArg, pTab->zName + ); + sqlite3DbFree(db, zArg); + + /* Finally, reload the database schema. */ + renameReloadSchema(pParse, iDb, INITFLAG_AlterDropCons); +} + +/* +** The implementation of SQL function sqlite_fail(MSG). This takes a single +** argument, and returns it as an error message with the error code set to +** SQLITE_CONSTRAINT. +*/ +static void failConstraintFunc( + sqlite3_context *ctx, + int NotUsed, + sqlite3_value **argv +){ + const char *zText = (const char*)sqlite3_value_text(argv[0]); + int err = sqlite3_value_int(argv[1]); + (void)NotUsed; + sqlite3_result_error(ctx, zText, -1); + sqlite3_result_error_code(ctx, err); +} + +/* +** Buffer pCons, which is nCons bytes in size, contains the text of a +** NOT NULL or CHECK constraint that will be inserted into a CREATE TABLE +** statement. If successful, this function returns the size of the buffer in +** bytes not including any trailing whitespace or "--" style comments. Or, +** if an OOM occurs, it returns 0 and sets db->mallocFailed to true. +** +** C-style comments at the end are preserved. "--" style comments are +** removed because the comment terminator might be \000, and we are about +** to insert the pCons[] text into the middle of a larger string, and that +** will have the effect of removing the comment terminator and messing up +** the syntax. +*/ +static int alterRtrimConstraint( + sqlite3 *db, /* used to record OOM error */ + const char *pCons, /* Buffer containing constraint */ + int nCons /* Size of pCons in bytes */ +){ + u8 *zTmp = (u8*)sqlite3MPrintf(db, "%.*s", nCons, pCons); + int iOff = 0; + int iEnd = 0; + + if( zTmp==0 ) return 0; + + while( 1 ){ + int t = 0; + int nToken = sqlite3GetToken(&zTmp[iOff], &t); + if( t==TK_ILLEGAL ) break; + if( t!=TK_SPACE && (t!=TK_COMMENT || zTmp[iOff]!='-') ){ + iEnd = iOff+nToken; + } + iOff += nToken; + } + + sqlite3DbFree(db, zTmp); + return iEnd; +} + +/* +** Prepare a statement of the form: +** +** ALTER TABLE pSrc ALTER pCol SET NOT NULL +*/ +SQLITE_PRIVATE void sqlite3AlterSetNotNull( + Parse *pParse, /* Parsing context */ + SrcList *pSrc, /* Name of the table being altered */ + Token *pCol, /* Name of the column to add a NOT NULL constraint to */ + Token *pFirst /* The NOT token of the NOT NULL constraint text */ +){ + Table *pTab = 0; + int iCol = 0; + int iDb = 0; + const char *zDb = 0; + const char *pCons = 0; + int nCons = 0; + + /* Look up the table being altered. */ + assert( pSrc->nSrc==1 ); + pTab = alterFindTable(pParse, pSrc, &iDb, &zDb, 0); + if( !pTab ) return; + + /* Find the column being altered. */ + if( alterFindCol(pParse, pTab, pCol, &iCol) ){ + return; + } + + /* Find the length in bytes of the constraint definition */ + pCons = pFirst->z; + nCons = alterRtrimConstraint(pParse->db, pCons, pParse->sLastToken.z - pCons); + + /* Search for a constraint violation. Throw an exception if one is found. */ + sqlite3NestedParse(pParse, + "SELECT sqlite_fail('constraint failed', %d) " + "FROM %Q.%Q AS x WHERE x.%.*s IS NULL", + SQLITE_CONSTRAINT, zDb, pTab->zName, (int)pCol->n, pCol->z + ); + + /* Edit the SQL for the named table. */ + sqlite3NestedParse(pParse, + "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET " + "sql = sqlite_add_constraint(sqlite_drop_constraint(sql, %d), %.*Q, %d) " + "WHERE type='table' AND tbl_name=%Q COLLATE nocase" + , zDb, iCol, nCons, pCons, iCol, pTab->zName + ); + + /* Finally, reload the database schema. */ + renameReloadSchema(pParse, iDb, INITFLAG_AlterDropCons); +} + +/* +** Implementation of internal SQL function: +** +** sqlite_find_constraint(SQL, CONSTRAINT-NAME) +** +** This function returns true if the SQL passed as the first argument is a +** CREATE TABLE that contains a constraint with the name CONSTRAINT-NAME, +** or false otherwise. +*/ +static void findConstraintFunc( + sqlite3_context *ctx, + int NotUsed, + sqlite3_value **argv +){ + const u8 *zSql = 0; + const u8 *zCons = 0; + int iOff = 0; + int t = 0; + + (void)NotUsed; + zSql = sqlite3_value_text(argv[0]); + zCons = sqlite3_value_text(argv[1]); + + if( zSql==0 || zCons==0 ) return; + while( t!=TK_LP && t!=TK_ILLEGAL ){ + iOff += sqlite3GetToken(&zSql[iOff], &t); + } + + while( 1 ){ + iOff += getConstraintToken(&zSql[iOff], &t); + if( t==TK_CONSTRAINT ){ + int nTok = 0; + int cmp = 0; + iOff += getWhitespace(&zSql[iOff]); + nTok = getConstraintToken(&zSql[iOff], &t); + if( quotedCompare(ctx, t, &zSql[iOff], nTok, zCons, &cmp) ) return; + if( cmp==0 ){ + sqlite3_result_int(ctx, 1); + return; + } + }else if( t==TK_ILLEGAL ){ + break; + } + } + + sqlite3_result_int(ctx, 0); +} + +/* +** Generate bytecode to implement: +** +** ALTER TABLE pSrc ADD [CONSTRAINT pName] CHECK(pExpr) +** +** Any "ON CONFLICT" text that occurs after the "CHECK(...)", up +** until pParse->sLastToken, is included as part of the new constraint. +*/ +SQLITE_PRIVATE void sqlite3AlterAddConstraint( + Parse *pParse, /* Parse context */ + SrcList *pSrc, /* Table to add constraint to */ + Token *pFirst, /* First token of new constraint */ + Token *pName, /* Name of new constraint. NULL if name omitted. */ + const char *zExpr, /* Text of CHECK expression */ + int nExpr, /* Size of pExpr in bytes */ + Expr *pExpr /* The parsed CHECK expression */ +){ + Table *pTab = 0; /* Table identified by pSrc */ + int iDb = 0; /* Which schema does pTab live in */ + const char *zDb = 0; /* Name of the schema in which pTab lives */ + const char *pCons = 0; /* Text of the constraint */ + int nCons; /* Bytes of text to use from pCons[] */ + int rc; /* Result from error checking pExpr */ + + /* Look up the table being altered. */ + assert( pSrc->nSrc==1 ); + pTab = alterFindTable(pParse, pSrc, &iDb, &zDb, 1); + if( !pTab ){ + sqlite3ExprDelete(pParse->db, pExpr); + return; + } + + /* Verify that the new CHECK constraint does not contain any + ** internal-use-only function. Forum post 2026-05-10T01:11:28Z + */ + rc = sqlite3ResolveSelfReference(pParse, pTab, NC_IsCheck, pExpr, 0); + sqlite3ExprDelete(pParse->db, pExpr); + if( rc ) return; + + /* If this new constraint has a name, check that it is not a duplicate of + ** an existing constraint. It is an error if it is. */ + if( pName ){ + char *zName = sqlite3NameFromToken(pParse->db, pName); + + sqlite3NestedParse(pParse, + "SELECT sqlite_fail('constraint %q already exists', %d) " + "FROM \"%w\"." LEGACY_SCHEMA_TABLE " " + "WHERE type='table' AND tbl_name=%Q COLLATE nocase " + "AND sqlite_find_constraint(sql, %Q)", + zName, SQLITE_ERROR, zDb, pTab->zName, zName + ); + sqlite3DbFree(pParse->db, zName); + } + + /* Search for a constraint violation. Throw an exception if one is found. */ + sqlite3NestedParse(pParse, + "SELECT sqlite_fail('constraint failed', %d) " + "FROM %Q.%Q WHERE (%.*s) IS FALSE", + SQLITE_CONSTRAINT, zDb, pTab->zName, nExpr, zExpr + ); + + /* Edit the SQL for the named table. */ + pCons = pFirst->z; + nCons = alterRtrimConstraint(pParse->db, pCons, pParse->sLastToken.z - pCons); + + sqlite3NestedParse(pParse, + "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET " + "sql = sqlite_add_constraint(sql, %.*Q, -1) " + "WHERE type='table' AND tbl_name=%Q COLLATE nocase" + , zDb, nCons, pCons, pTab->zName + ); + + /* Finally, reload the database schema. */ + renameReloadSchema(pParse, iDb, INITFLAG_AlterDropCons); +} + /* ** Register built-in functions used to help implement ALTER TABLE */ @@ -119007,6 +123825,10 @@ SQLITE_PRIVATE void sqlite3AlterFunctions(void){ INTERNAL_FUNCTION(sqlite_rename_test, 7, renameTableTest), INTERNAL_FUNCTION(sqlite_drop_column, 3, dropColumnFunc), INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc), + INTERNAL_FUNCTION(sqlite_drop_constraint,2, dropConstraintFunc), + INTERNAL_FUNCTION(sqlite_fail, 2, failConstraintFunc), + INTERNAL_FUNCTION(sqlite_add_constraint, 3, addConstraintFunc), + INTERNAL_FUNCTION(sqlite_find_constraint,2, findConstraintFunc), }; sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs)); } @@ -119231,7 +124053,8 @@ static void openStatTable( sqlite3NestedParse(pParse, "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols ); - aRoot[i] = (u32)pParse->regRoot; + assert( pParse->isCreate || pParse->nErr ); + aRoot[i] = (u32)pParse->u1.cr.regRoot; aCreateTbl[i] = OPFLAG_P2ISREG; } }else{ @@ -119422,7 +124245,7 @@ static void statInit( int nCol; /* Number of columns in index being sampled */ int nKeyCol; /* Number of key columns */ int nColUp; /* nCol rounded up for alignment */ - int n; /* Bytes of space to allocate */ + i64 n; /* Bytes of space to allocate */ sqlite3 *db = sqlite3_context_db_handle(context); /* Database connection */ #ifdef SQLITE_ENABLE_STAT4 /* Maximum number of samples. 0 if STAT4 data is not collected */ @@ -119458,7 +124281,7 @@ static void statInit( p->db = db; p->nEst = sqlite3_value_int64(argv[2]); p->nRow = 0; - p->nLimit = sqlite3_value_int64(argv[3]); + p->nLimit = sqlite3_value_int(argv[3]); p->nCol = nCol; p->nKeyCol = nKeyCol; p->nSkipAhead = 0; @@ -119891,7 +124714,7 @@ static void statGet( assert( p->current.anEq[i] || p->nRow==0 ); #endif } - sqlite3ResultStrAccum(context, &sStat); + sqlite3_result_str(context, &sStat, SQLITE_XFER); } #ifdef SQLITE_ENABLE_STAT4 else if( eCall==STAT_GET_ROWID ){ @@ -119928,7 +124751,7 @@ static void statGet( sqlite3_str_appendf(&sStat, "%llu ", (u64)aCnt[i]); } if( sStat.nChar ) sStat.nChar--; - sqlite3ResultStrAccum(context, &sStat); + sqlite3_result_str(context, &sStat, SQLITE_XFER); } #endif /* SQLITE_ENABLE_STAT4 */ #ifndef SQLITE_DEBUG @@ -120591,16 +125414,6 @@ static void decodeIntArray( while( z[0]!=0 && z[0]!=' ' ) z++; while( z[0]==' ' ) z++; } - - /* Set the bLowQual flag if the peak number of rows obtained - ** from a full equality match is so large that a full table scan - ** seems likely to be faster than using the index. - */ - if( aLog[0] > 66 /* Index has more than 100 rows */ - && aLog[0] <= aLog[nOut-1] /* And only a single value seen */ - ){ - pIndex->bLowQual = 1; - } } } @@ -120839,9 +125652,9 @@ static int loadStatTbl( } pIdx->nSampleCol = nIdxCol; pIdx->mxSample = nSample; - nByte = ROUND8(sizeof(IndexSample) * nSample); - nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample; - nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */ + nByte = ROUND8(sizeof64(IndexSample) * nSample); + nByte += sizeof64(tRowcnt) * nIdxCol * 3 * nSample; + nByte += nIdxCol * sizeof64(tRowcnt); /* Space for Index.aAvgEq[] */ pIdx->aSample = sqlite3DbMallocZero(db, nByte); if( pIdx->aSample==0 ){ @@ -120849,7 +125662,7 @@ static int loadStatTbl( return SQLITE_NOMEM_BKPT; } pPtr = (u8*)pIdx->aSample; - pPtr += ROUND8(nSample*sizeof(pIdx->aSample[0])); + pPtr += ROUND8(nSample*sizeof64(pIdx->aSample[0])); pSpace = (tRowcnt*)pPtr; assert( EIGHT_BYTE_ALIGNMENT( pSpace ) ); pIdx->aAvgEq = pSpace; pSpace += nIdxCol; @@ -121096,6 +125909,23 @@ SQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName){ ); } +/* +** If any TEMP triggers reference schema pSchema, move those triggers to +** reference the TEMP schema itself. +*/ +static void detachTempTriggers(sqlite3 *db, Schema *pSchema){ + HashElem *pEntry; + assert( db->aDb[1].pSchema ); + pEntry = sqliteHashFirst(&db->aDb[1].pSchema->trigHash); + while( pEntry ){ + Trigger *pTrig = (Trigger*)sqliteHashData(pEntry); + if( pTrig->pTabSchema==pSchema ){ + pTrig->pTabSchema = pTrig->pSchema; + } + pEntry = sqliteHashNext(pEntry); + } +} + /* ** An SQL user-function registered to do the work of an ATTACH statement. The ** three arguments to the function come directly from an attach statement: @@ -121146,6 +125976,16 @@ static void attachFunc( ** from sqlite3_deserialize() to close database db->init.iDb and ** reopen it as a MemDB */ Btree *pNewBt = 0; + + pNew = &db->aDb[db->init.iDb]; + assert( pNew->pBt!=0 ); + if( sqlite3BtreeTxnState(pNew->pBt)!=SQLITE_TXN_NONE + || sqlite3BtreeIsInBackup(pNew->pBt) + ){ + rc = SQLITE_BUSY; + goto attach_error; + } + pVfs = sqlite3_vfs_find("memdb"); if( pVfs==0 ) return; rc = sqlite3BtreeOpen(pVfs, "x\0", db, &pNewBt, 0, SQLITE_OPEN_MAIN_DB); @@ -121155,10 +125995,16 @@ static void attachFunc( /* Both the Btree and the new Schema were allocated successfully. ** Close the old db and update the aDb[] slot with the new memdb ** values. */ - pNew = &db->aDb[db->init.iDb]; - if( ALWAYS(pNew->pBt) ) sqlite3BtreeClose(pNew->pBt); + detachTempTriggers(db, pNew->pSchema); + sqlite3BtreeClose(pNew->pBt); pNew->pBt = pNewBt; pNew->pSchema = pNewSchema; + if( db->init.iDb==0 ){ + /* Clear all eponymous virtual table instances, as they are holding + ** pointers to the schema object just freed by sqlite3BtreeClose() */ + sqlite3VtabEponymousTableClearAll(db); + } + sqlite3ExpirePreparedStatements(db, 1); }else{ sqlite3BtreeClose(pNewBt); rc = SQLITE_NOMEM; @@ -121196,7 +126042,7 @@ static void attachFunc( if( aNew==0 ) return; memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2); }else{ - aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) ); + aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(1+(i64)db->nDb)); if( aNew==0 ) return; } db->aDb = aNew; @@ -121215,6 +126061,12 @@ static void attachFunc( sqlite3_free(zErr); return; } + if( (db->flags & SQLITE_AttachWrite)==0 ){ + flags &= ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE); + flags |= SQLITE_OPEN_READONLY; + }else if( (db->flags & SQLITE_AttachCreate)==0 ){ + flags &= ~SQLITE_OPEN_CREATE; + } assert( pVfs ); flags |= SQLITE_OPEN_MAIN_DB; rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags); @@ -121261,21 +126113,19 @@ static void attachFunc( sqlite3BtreeEnterAll(db); db->init.iDb = 0; db->mDbFlags &= ~(DBFLAG_SchemaKnownOk); +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + if( db->setlkFlags & SQLITE_SETLK_BLOCK_ON_CONNECT ){ + int val = 1; + sqlite3_file *fd = sqlite3PagerFile(sqlite3BtreePager(pNew->pBt)); + sqlite3OsFileControlHint(fd, SQLITE_FCNTL_BLOCK_ON_CONNECT, &val); + } +#endif if( !REOPEN_AS_MEMDB(db) ){ rc = sqlite3Init(db, &zErrDyn); } sqlite3BtreeLeaveAll(db); assert( zErrDyn==0 || rc!=SQLITE_OK ); } -#ifdef SQLITE_USER_AUTHENTICATION - if( rc==SQLITE_OK && !REOPEN_AS_MEMDB(db) ){ - u8 newAuth = 0; - rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth); - if( newAuth<db->auth.authLevel ){ - rc = SQLITE_AUTH_USER; - } - } -#endif if( rc ){ if( ALWAYS(!REOPEN_AS_MEMDB(db)) ){ int iDb = db->nDb - 1; @@ -121326,7 +126176,6 @@ static void detachFunc( sqlite3 *db = sqlite3_context_db_handle(context); int i; Db *pDb = 0; - HashElem *pEntry; char zErr[128]; UNUSED_PARAMETER(NotUsed); @@ -121353,18 +126202,7 @@ static void detachFunc( goto detach_error; } - /* If any TEMP triggers reference the schema being detached, move those - ** triggers to reference the TEMP schema itself. */ - assert( db->aDb[1].pSchema ); - pEntry = sqliteHashFirst(&db->aDb[1].pSchema->trigHash); - while( pEntry ){ - Trigger *pTrig = (Trigger*)sqliteHashData(pEntry); - if( pTrig->pTabSchema==pDb->pSchema ){ - pTrig->pTabSchema = pTrig->pSchema; - } - pEntry = sqliteHashNext(pEntry); - } - + detachTempTriggers(db, pDb->pSchema); sqlite3BtreeClose(pDb->pBt); pDb->pBt = 0; pDb->pSchema = 0; @@ -121632,7 +126470,7 @@ SQLITE_PRIVATE int sqlite3FixTriggerStep( if( sqlite3WalkSelect(&pFix->w, pStep->pSelect) || sqlite3WalkExpr(&pFix->w, pStep->pWhere) || sqlite3WalkExprList(&pFix->w, pStep->pExprList) - || sqlite3FixSrcList(pFix, pStep->pFrom) + || sqlite3FixSrcList(pFix, pStep->pSrc) ){ return 1; } @@ -121739,7 +126577,7 @@ SQLITE_API int sqlite3_set_authorizer( sqlite3_mutex_enter(db->mutex); db->xAuth = (sqlite3_xauth)xAuth; db->pAuthArg = pArg; - if( db->xAuth ) sqlite3ExpirePreparedStatements(db, 1); + sqlite3ExpirePreparedStatements(db, 1); sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } @@ -121773,11 +126611,7 @@ SQLITE_PRIVATE int sqlite3AuthReadCol( int rc; /* Auth callback return code */ if( db->init.busy ) return SQLITE_OK; - rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext -#ifdef SQLITE_USER_AUTHENTICATION - ,db->auth.zAuthUser -#endif - ); + rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext); if( rc==SQLITE_DENY ){ char *z = sqlite3_mprintf("%s.%s", zTab, zCol); if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z); @@ -121854,8 +126688,14 @@ SQLITE_PRIVATE void sqlite3AuthRead( ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY ** is returned, then the error count and error message in pParse are ** modified appropriately. +** +** Divided into two routines. realAuthCheck() does the work. The +** sqlite3AuthCheck() routine is usually a fast no-op but invokes +** realAuthCheck() (and spends time doing some stack pushes and pops +** as a result) in the uncommon case where an authorization check is +** actually needed. */ -SQLITE_PRIVATE int sqlite3AuthCheck( +static int SQLITE_NOINLINE realAuthCheck( Parse *pParse, int code, const char *zArg1, @@ -121869,7 +126709,7 @@ SQLITE_PRIVATE int sqlite3AuthCheck( ** or if the parser is being invoked from within sqlite3_declare_vtab. */ assert( !IN_RENAME_OBJECT || db->xAuth==0 ); - if( db->xAuth==0 || db->init.busy || IN_SPECIAL_PARSE ){ + if( IN_SPECIAL_PARSE ){ return SQLITE_OK; } @@ -121884,11 +126724,7 @@ SQLITE_PRIVATE int sqlite3AuthCheck( testcase( zArg3==0 ); testcase( pParse->zAuthContext==0 ); - rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext -#ifdef SQLITE_USER_AUTHENTICATION - ,db->auth.zAuthUser -#endif - ); + rc = db->xAuth(db->pAuthArg,code,zArg1,zArg2,zArg3,pParse->zAuthContext); if( rc==SQLITE_DENY ){ sqlite3ErrorMsg(pParse, "not authorized"); pParse->rc = SQLITE_AUTH; @@ -121898,6 +126734,19 @@ SQLITE_PRIVATE int sqlite3AuthCheck( } return rc; } +SQLITE_PRIVATE int sqlite3AuthCheck( + Parse *pParse, + int code, + const char *zArg1, + const char *zArg2, + const char *zArg3 +){ + if( pParse->db->xAuth!=0 && pParse->db->init.busy==0 ){ + return realAuthCheck(pParse,code,zArg1,zArg2,zArg3); + }else{ + return SQLITE_OK; + } +} /* ** Push an authorization context. After this routine is called, the @@ -122000,7 +126849,9 @@ static SQLITE_NOINLINE void lockTable( } } + assert( pToplevel->nTableLock < 0x7fff0000 ); nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1); + if( pToplevel->nTableLock==0 ) pToplevel->aTableLock = 0; pToplevel->aTableLock = sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes); if( pToplevel->aTableLock ){ @@ -122100,10 +126951,12 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort)); if( v ){ if( pParse->bReturning ){ - Returning *pReturning = pParse->u1.pReturning; + Returning *pReturning; int addrRewind; int reg; + assert( !pParse->isCreate ); + pReturning = pParse->u1.d.pReturning; if( pReturning->nRetCol ){ sqlite3VdbeAddOp0(v, OP_FkCheck); addrRewind = @@ -122121,17 +126974,6 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ } sqlite3VdbeAddOp0(v, OP_Halt); -#if SQLITE_USER_AUTHENTICATION && !defined(SQLITE_OMIT_SHARED_CACHE) - if( pParse->nTableLock>0 && db->init.busy==0 ){ - sqlite3UserAuthInit(db); - if( db->auth.authLevel<UAUTH_User ){ - sqlite3ErrorMsg(pParse, "user not authenticated"); - pParse->rc = SQLITE_AUTH_USER; - return; - } - } -#endif - /* The cookie mask contains one bit for each database file open. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are ** set for each database that is used. Generate code to start a @@ -122176,7 +127018,7 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ /* Initialize any AUTOINCREMENT data structures required. */ - if( pParse->pAinc ) sqlite3AutoincrementBegin(pParse); + if( pParse->usesAinc ) sqlite3AutoincrementBegin(pParse); /* Code constant expressions that were factored out of inner loops. */ @@ -122190,7 +127032,9 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ } if( pParse->bReturning ){ - Returning *pRet = pParse->u1.pReturning; + Returning *pRet; + assert( !pParse->isCreate ); + pRet = pParse->u1.d.pReturning; if( pRet->nRetCol ){ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol); } @@ -122207,7 +127051,7 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ if( pParse->nErr==0 ){ /* A minimum of one cursor is required if autoincrement is used * See ticket [a696379c1f08866] */ - assert( pParse->pAinc==0 || pParse->nTab>0 ); + assert( pParse->usesAinc==0 || pParse->nTab>0 ); sqlite3VdbeMakeReady(v, pParse); pParse->rc = SQLITE_DONE; }else{ @@ -122260,16 +127104,6 @@ SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ pParse->nested--; } -#if SQLITE_USER_AUTHENTICATION -/* -** Return TRUE if zTable is the name of the system table that stores the -** list of users and their access credentials. -*/ -SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){ - return sqlite3_stricmp(zTable, "sqlite_user")==0; -} -#endif - /* ** Locate the in-memory structure that describes a particular database ** table given the name of that table and (optionally) the name of the @@ -122288,13 +127122,6 @@ SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const cha /* All mutexes are required for schema access. Make sure we hold them. */ assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) ); -#if SQLITE_USER_AUTHENTICATION - /* Only the admin user is allowed to know that the sqlite_user table - ** exists */ - if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){ - return 0; - } -#endif if( zDatabase ){ for(i=0; i<db->nDb; i++){ if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break; @@ -122388,6 +127215,16 @@ SQLITE_PRIVATE Table *sqlite3LocateTable( if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){ pMod = sqlite3PragmaVtabRegister(db, zName); } +#ifndef SQLITE_OMIT_JSON + if( pMod==0 && sqlite3_strnicmp(zName, "json", 4)==0 ){ + pMod = sqlite3JsonVtabRegister(db, zName); + } +#endif +#ifdef SQLITE_ENABLE_CARRAY + if( pMod==0 && sqlite3_stricmp(zName, "carray")==0 ){ + pMod = sqlite3CarrayRegister(db); + } +#endif if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){ testcase( pMod->pEpoTab==0 ); return pMod->pEpoTab; @@ -122431,6 +127268,7 @@ SQLITE_PRIVATE Table *sqlite3LocateTableItem( const char *zDb; if( p->fg.fixedSchema ){ int iDb = sqlite3SchemaToIndex(pParse->db, p->u4.pSchema); + assert( iDb>=0 && iDb<pParse->db->nDb ); zDb = pParse->db->aDb[iDb].zDbSName; }else{ assert( !p->fg.isSubquery ); @@ -122582,6 +127420,7 @@ SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){ for(i=0; i<db->nDb; i++){ if( DbHasProperty(db, i, DB_ResetWanted) ){ sqlite3SchemaClear(db->aDb[i].pSchema); + db->mDbFlags &= ~DBFLAG_SchemaKnownOk; } } } @@ -122645,10 +127484,41 @@ SQLITE_PRIVATE void sqlite3ColumnSetExpr( } } +#ifndef SQLITE_OMIT_AUTHORIZATION +/* +** If the expression contains any TK_FUNCTION, send it to the authorizer +** and if the authorization fails then raise an error. +*/ +static int authFunctions(Walker *pWalker, Expr *p){ + if( p->op==TK_FUNCTION ){ + Parse *pParse = pWalker->pParse; + int rc = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, p->u.zToken, 0); + if( rc ){ + sqlite3ErrorMsg(pParse, "not authorized to use function: %#T", p); + return WRC_Abort; + } + } + return WRC_Continue; +} +static void sqlite3FuncAuth(Parse *pParse, Expr *pExpr){ + Walker w; + memset(&w, 0, sizeof(w)); + w.xExprCallback = authFunctions; + w.pParse = pParse; + sqlite3WalkExpr(&w,pExpr); +} +#endif /* SQLITE_OMIT_AUTHORIZATION */ + /* ** Return the expression associated with a column. The expression might be ** the DEFAULT clause or the AS clause of a generated column. ** Return NULL if the column has no associated expression. +** +** There are two variants of this routine. sqlite3ColumnExpr() just +** returns the expression with no side effects. sqlite3ColumnExprAuth() +** takes the extra step of invoking the authorizer (if one is defined) +** and raising an error if the returned expression uses any unauthorized +** SQL function. */ SQLITE_PRIVATE Expr *sqlite3ColumnExpr(Table *pTab, Column *pCol){ if( pCol->iDflt==0 ) return 0; @@ -122657,6 +127527,28 @@ SQLITE_PRIVATE Expr *sqlite3ColumnExpr(Table *pTab, Column *pCol){ if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0; return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr; } +SQLITE_PRIVATE Expr *sqlite3ColumnExprAuth(Table *pTab, Column *pCol, Parse *pParse){ + Expr *pExpr = sqlite3ColumnExpr(pTab,pCol); +#ifndef SQLITE_OMIT_AUTHORIZATION + if( pParse->db->xAuth!=0 ){ + sqlite3FuncAuth(pParse, pExpr); + } +#endif + return pExpr; +} + +/* +** Suppress false-positive warning message generated with -O3 in GCC +** on the second call to sqlite3Strlen30() in the sqlite3ColumnSetColl() +** function below. See the forum thread beginning on 2026-05-10T01:11:22Z. +** +** See also the "pop" pragma to undo this warning suppression immediately +** after the function. +*/ +#if defined(__GNUC__) && __GNUC__>=11 +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wstringop-overread" +#endif /* ** Set the collating sequence name for a column. @@ -122683,6 +127575,11 @@ SQLITE_PRIVATE void sqlite3ColumnSetColl( } } +/* Undo the false-positive warning suppression above. */ +#if defined(__GNUC__) && __GNUC__>=11 +# pragma GCC diagnostic pop +#endif + /* ** Return the collating sequence name for a column */ @@ -123022,10 +127919,16 @@ SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){ ** find the (first) offset of that column in index pIdx. Or return -1 ** if column iCol is not used in index pIdx. */ -SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){ +SQLITE_PRIVATE int sqlite3TableColumnToIndex(Index *pIdx, int iCol){ int i; + i16 iCol16; + assert( iCol>=(-1) && iCol<=SQLITE_MAX_COLUMN ); + assert( pIdx->nColumn<=SQLITE_MAX_COLUMN*2 ); + iCol16 = iCol; for(i=0; i<pIdx->nColumn; i++){ - if( iCol==pIdx->aiColumn[i] ) return i; + if( iCol16==pIdx->aiColumn[i] ){ + return i; + } } return -1; } @@ -123279,8 +128182,9 @@ SQLITE_PRIVATE void sqlite3StartTable( /* If the file format and encoding in the database have not been set, ** set them now. */ - reg1 = pParse->regRowid = ++pParse->nMem; - reg2 = pParse->regRoot = ++pParse->nMem; + assert( pParse->isCreate ); + reg1 = pParse->u1.cr.regRowid = ++pParse->nMem; + reg2 = pParse->u1.cr.regRoot = ++pParse->nMem; reg3 = ++pParse->nMem; sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT); sqlite3VdbeUsesBtree(v, iDb); @@ -123295,8 +128199,8 @@ SQLITE_PRIVATE void sqlite3StartTable( ** The record created does not contain anything yet. It will be replaced ** by the real entry in code generated at sqlite3EndTable(). ** - ** The rowid for the new entry is left in register pParse->regRowid. - ** The root page number of the new table is left in reg pParse->regRoot. + ** The rowid for the new entry is left in register pParse->u1.cr.regRowid. + ** The root page of the new table is left in reg pParse->u1.cr.regRoot. ** The rowid and root page number values are needed by the code that ** sqlite3EndTable will generate. */ @@ -123307,7 +128211,7 @@ SQLITE_PRIVATE void sqlite3StartTable( #endif { assert( !pParse->bReturning ); - pParse->u1.addrCrTab = + pParse->u1.cr.addrCrTab = sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY); } sqlite3OpenSchemaTable(pParse, iDb); @@ -123316,6 +128220,9 @@ SQLITE_PRIVATE void sqlite3StartTable( sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); sqlite3VdbeAddOp0(v, OP_Close); + }else if( db->init.imposterTable ){ + pTable->tabFlags |= TF_Imposter; + if( db->init.imposterTable>=2 ) pTable->tabFlags |= TF_Readonly; } /* Normal (non-error) return. */ @@ -123385,7 +128292,8 @@ SQLITE_PRIVATE void sqlite3AddReturning(Parse *pParse, ExprList *pList){ sqlite3ExprListDelete(db, pList); return; } - pParse->u1.pReturning = pRet; + assert( !pParse->isCreate ); + pParse->u1.d.pReturning = pRet; pRet->pParse = pParse; pRet->pReturnEL = pList; sqlite3ParserAddCleanup(pParse, sqlite3DeleteReturning, pRet); @@ -123427,7 +128335,6 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){ char *zType; Column *pCol; sqlite3 *db = pParse->db; - u8 hName; Column *aNew; u8 eType = COLTYPE_CUSTOM; u8 szEst = 1; @@ -123481,13 +128388,10 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){ memcpy(z, sName.z, sName.n); z[sName.n] = 0; sqlite3Dequote(z); - hName = sqlite3StrIHash(z); - for(i=0; i<p->nCol; i++){ - if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zCnName)==0 ){ - sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); - sqlite3DbFree(db, z); - return; - } + if( p->nCol && sqlite3ColumnIndex(p, z)>=0 ){ + sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); + sqlite3DbFree(db, z); + return; } aNew = sqlite3DbRealloc(db,p->aCol,((i64)p->nCol+1)*sizeof(p->aCol[0])); if( aNew==0 ){ @@ -123498,7 +128402,7 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){ pCol = &p->aCol[p->nCol]; memset(pCol, 0, sizeof(p->aCol[0])); pCol->zCnName = z; - pCol->hName = hName; + pCol->hName = sqlite3StrIHash(z); sqlite3ColumnPropertiesFromName(p, pCol); if( sType.n==0 ){ @@ -123522,9 +128426,14 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){ pCol->affinity = sqlite3AffinityType(zType, pCol); pCol->colFlags |= COLFLAG_HASTYPE; } + if( p->nCol<=0xff ){ + u8 h = pCol->hName % sizeof(p->aHx); + p->aHx[h] = p->nCol; + } p->nCol++; p->nNVCol++; - pParse->constraintName.n = 0; + assert( pParse->isCreate ); + pParse->u1.cr.constraintName.n = 0; } /* @@ -123693,6 +128602,13 @@ SQLITE_PRIVATE void sqlite3AddDefaultValue( pDfltExpr = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE); sqlite3DbFree(db, x.u.zToken); sqlite3ColumnSetExpr(pParse, p, pCol, pDfltExpr); +#ifndef SQLITE_OMIT_AUTHORIZATION + /* Reject unauthorized functions from DEFAULT clauses */ + if( db->init.busy==0 && db->xAuth!=0 ){ + sqlite3FuncAuth(pParse, pExpr); + } +#endif /* SQLITE_OMIT_AUTHORIZER */ + } } if( IN_RENAME_OBJECT ){ @@ -123788,15 +128704,11 @@ SQLITE_PRIVATE void sqlite3AddPrimaryKey( assert( pCExpr!=0 ); sqlite3StringToId(pCExpr); if( pCExpr->op==TK_ID ){ - const char *zCName; assert( !ExprHasProperty(pCExpr, EP_IntValue) ); - zCName = pCExpr->u.zToken; - for(iCol=0; iCol<pTab->nCol; iCol++){ - if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zCnName)==0 ){ - pCol = &pTab->aCol[iCol]; - makeColumnPartOfPrimaryKey(pParse, pCol); - break; - } + iCol = sqlite3ColumnIndex(pTab, pCExpr->u.zToken); + if( iCol>=0 ){ + pCol = &pTab->aCol[iCol]; + makeColumnPartOfPrimaryKey(pParse, pCol); } } } @@ -123848,8 +128760,10 @@ SQLITE_PRIVATE void sqlite3AddCheckConstraint( && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt) ){ pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr); - if( pParse->constraintName.n ){ - sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1); + assert( pParse->isCreate ); + if( pParse->u1.cr.constraintName.n ){ + sqlite3ExprListSetName(pParse, pTab->pCheck, + &pParse->u1.cr.constraintName, 1); }else{ Token t; for(zStart++; sqlite3Isspace(zStart[0]); zStart++){} @@ -123994,8 +128908,8 @@ SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){ ** The estimate is conservative. It might be larger that what is ** really needed. */ -static int identLength(const char *z){ - int n; +static i64 identLength(const char *z){ + i64 n; for(n=0; *z; n++, z++){ if( *z=='"' ){ n++; } } @@ -124044,7 +128958,8 @@ static void identPut(char *z, int *pIdx, char *zSignedIdent){ ** from sqliteMalloc() and must be freed by the calling function. */ static char *createTableStmt(sqlite3 *db, Table *p){ - int i, k, n; + int i, k, len; + i64 n; char *zStmt; char *zSep, *zSep2, *zEnd; Column *pCol; @@ -124068,8 +128983,9 @@ static char *createTableStmt(sqlite3 *db, Table *p){ sqlite3OomFault(db); return 0; } - sqlite3_snprintf(n, zStmt, "CREATE TABLE "); - k = sqlite3Strlen30(zStmt); + assert( n>14 && n<=0x7fffffff ); + memcpy(zStmt, "CREATE TABLE ", 13); + k = 13; identPut(zStmt, &k, p->zName); zStmt[k++] = '('; for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){ @@ -124081,13 +128997,15 @@ static char *createTableStmt(sqlite3 *db, Table *p){ /* SQLITE_AFF_REAL */ " REAL", /* SQLITE_AFF_FLEXNUM */ " NUM", }; - int len; const char *zType; - sqlite3_snprintf(n-k, &zStmt[k], zSep); - k += sqlite3Strlen30(&zStmt[k]); + len = sqlite3Strlen30(zSep); + assert( k+len<n ); + memcpy(&zStmt[k], zSep, len); + k += len; zSep = zSep2; identPut(zStmt, &k, pCol->zCnName); + assert( k<n ); assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 ); assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) ); testcase( pCol->affinity==SQLITE_AFF_BLOB ); @@ -124102,11 +129020,14 @@ static char *createTableStmt(sqlite3 *db, Table *p){ assert( pCol->affinity==SQLITE_AFF_BLOB || pCol->affinity==SQLITE_AFF_FLEXNUM || pCol->affinity==sqlite3AffinityType(zType, 0) ); + assert( k+len<n ); memcpy(&zStmt[k], zType, len); k += len; assert( k<=n ); } - sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd); + len = sqlite3Strlen30(zEnd); + assert( k+len<n ); + memcpy(&zStmt[k], zEnd, len+1); return zStmt; } @@ -124114,12 +129035,17 @@ static char *createTableStmt(sqlite3 *db, Table *p){ ** Resize an Index object to hold N columns total. Return SQLITE_OK ** on success and SQLITE_NOMEM on an OOM error. */ -static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ +static int resizeIndexObject(Parse *pParse, Index *pIdx, int N){ char *zExtra; - int nByte; + u64 nByte; + sqlite3 *db; if( pIdx->nColumn>=N ) return SQLITE_OK; + db = pParse->db; + assert( N>0 ); + assert( N <= SQLITE_MAX_COLUMN*2 /* tag-20250221-1 */ ); + testcase( N==2*pParse->db->aLimit[SQLITE_LIMIT_COLUMN] ); assert( pIdx->isResized==0 ); - nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N; + nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*(u64)N; zExtra = sqlite3DbMallocZero(db, nByte); if( zExtra==0 ) return SQLITE_NOMEM_BKPT; memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn); @@ -124133,11 +129059,28 @@ static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){ zExtra += sizeof(i16)*N; memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn); pIdx->aSortOrder = (u8*)zExtra; - pIdx->nColumn = N; + pIdx->nColumn = (u16)N; /* See tag-20250221-1 above for proof of safety */ pIdx->isResized = 1; return SQLITE_OK; } +/* +** Return true if the index pIdx can support a Bloom filter on its +** first N columns. Specifically, return true if all of the first N +** columns have the BINARY collating sequence or no collating sequence +** at all, and return false if there are any non-BINARY collating +** seqeuences on any of the first N columns. tag-202607231411 +*/ +SQLITE_PRIVATE int sqlite3IndexBloomable(const Index *pIdx, int N){ + int i; + assert( pIdx!=0 ); + assert( N <= pIdx->nColumn ); + for(i=0; i<N; i++){ + if( sqlite3StrICmp(pIdx->azColl[i],"BINARY")!=0 ) return 0; + } + return 1; +} + /* ** Estimate the total row width for a table. */ @@ -124299,9 +129242,9 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ ** into BTREE_BLOBKEY. */ assert( !pParse->bReturning ); - if( pParse->u1.addrCrTab ){ + if( pParse->u1.cr.addrCrTab ){ assert( v ); - sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY); + sqlite3VdbeChangeP3(v, pParse->u1.cr.addrCrTab, BTREE_BLOBKEY); } /* Locate the PRIMARY KEY index. Or, if this table was originally @@ -124387,14 +129330,14 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ pIdx->nColumn = pIdx->nKeyCol; continue; } - if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return; + if( resizeIndexObject(pParse, pIdx, pIdx->nKeyCol+n) ) return; for(i=0, j=pIdx->nKeyCol; i<nPk; i++){ if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){ testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ); pIdx->aiColumn[j] = pPk->aiColumn[i]; pIdx->azColl[j] = pPk->azColl[i]; if( pPk->aSortOrder[i] ){ - /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */ + /* See ticket https://sqlite.org/src/info/bba7b69f9849b5bf */ pIdx->bAscKeyBug = 1; } j++; @@ -124411,14 +129354,15 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){ if( !hasColumn(pPk->aiColumn, nPk, i) && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++; } - if( resizeIndexObject(db, pPk, nPk+nExtra) ) return; + if( resizeIndexObject(pParse, pPk, nPk+nExtra) ) return; for(i=0, j=nPk; i<pTab->nCol; i++){ if( !hasColumn(pPk->aiColumn, j, i) && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){ + const char *zColl = sqlite3ColumnColl(&pTab->aCol[i]); assert( j<pPk->nColumn ); pPk->aiColumn[j] = i; - pPk->azColl[j] = sqlite3StrBINARY; + pPk->azColl[j] = zColl ? zColl : sqlite3StrBINARY; j++; } } @@ -124488,18 +129432,16 @@ SQLITE_PRIVATE void sqlite3MarkAllShadowTablesOf(sqlite3 *db, Table *pTab){ /* ** Return true if zName is a shadow table name in the current database ** connection. -** -** zName is temporarily modified while this routine is running, but is -** restored to its original value prior to this routine returning. */ SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName){ - char *zTail; /* Pointer to the last "_" in zName */ + const char *zTail; /* Pointer to the last "_" in zName */ Table *pTab; /* Table that zName is a shadow of */ + char *zCopy; /* Transient copy of zName after last "_" */ zTail = strrchr(zName, '_'); if( zTail==0 ) return 0; - *zTail = 0; - pTab = sqlite3FindTable(db, zName, 0); - *zTail = '_'; + zCopy = sqlite3DbStrNDup(db, zName, (int)(zTail-zName)); + pTab = zCopy ? sqlite3FindTable(db, zCopy, 0) : 0; + sqlite3DbFree(db, zCopy); if( pTab==0 ) return 0; if( !IsVirtual(pTab) ) return 0; return sqlite3IsShadowTableOf(db, pTab, zName); @@ -124533,7 +129475,6 @@ static void markExprListImmutable(ExprList *pList){ #define markExprListImmutable(X) /* no-op */ #endif /* SQLITE_DEBUG */ - /* ** This routine is called to report the final ")" that terminates ** a CREATE TABLE statement. @@ -124652,6 +129593,7 @@ SQLITE_PRIVATE void sqlite3EndTable( convertToWithoutRowidTable(pParse, p); } iDb = sqlite3SchemaToIndex(db, p->pSchema); + assert( iDb>=0 && iDb<=db->nDb ); #ifndef SQLITE_OMIT_CHECK /* Resolve names in all CHECK constraint expressions. @@ -124741,7 +129683,7 @@ SQLITE_PRIVATE void sqlite3EndTable( /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT ** statement to populate the new table. The root-page number for the - ** new table is in register pParse->regRoot. + ** new table is in register pParse->u1.cr.regRoot. ** ** Once the SELECT has been coded by sqlite3Select(), it is in a ** suitable state to query for the column names and types to be used @@ -124772,7 +129714,8 @@ SQLITE_PRIVATE void sqlite3EndTable( regRec = ++pParse->nMem; regRowid = ++pParse->nMem; sqlite3MayAbort(pParse); - sqlite3VdbeAddOp3(v, OP_OpenWrite, iCsr, pParse->regRoot, iDb); + assert( pParse->isCreate ); + sqlite3VdbeAddOp3(v, OP_OpenWrite, iCsr, pParse->u1.cr.regRoot, iDb); sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG); addrTop = sqlite3VdbeCurrentAddr(v) + 1; sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop); @@ -124817,6 +129760,7 @@ SQLITE_PRIVATE void sqlite3EndTable( ** schema table. We just need to update that slot with all ** the information we've collected. */ + assert( pParse->isCreate ); sqlite3NestedParse(pParse, "UPDATE %Q." LEGACY_SCHEMA_TABLE " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q" @@ -124825,9 +129769,9 @@ SQLITE_PRIVATE void sqlite3EndTable( zType, p->zName, p->zName, - pParse->regRoot, + pParse->u1.cr.regRoot, zStmt, - pParse->regRowid + pParse->u1.cr.regRowid ); sqlite3DbFree(db, zStmt); sqlite3ChangeCookie(pParse, iDb); @@ -124945,6 +129889,7 @@ SQLITE_PRIVATE void sqlite3CreateView( sqlite3TwoPartName(pParse, pName1, pName2, &pName); iDb = sqlite3SchemaToIndex(db, p->pSchema); + assert( iDb>=0 && iDb<db->nDb ); sqlite3FixInit(&sFix, pParse, iDb, "view", pName); if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail; @@ -125567,7 +130512,7 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey( }else{ nCol = pFromCol->nExpr; } - nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1; + nByte = SZ_FKEY(nCol) + pTo->n + 1; if( pToCol ){ for(i=0; i<pToCol->nExpr; i++){ nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1; @@ -125769,7 +130714,7 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables ** with DESC primary keys, since those indexes have there keys in ** a different order from the main table. - ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf + ** See ticket: https://sqlite.org/src/info/bba7b69f9849b5bf */ sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx); } @@ -125793,13 +130738,14 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ */ SQLITE_PRIVATE Index *sqlite3AllocateIndexObject( sqlite3 *db, /* Database connection */ - i16 nCol, /* Total number of columns in the index */ + int nCol, /* Total number of columns in the index */ int nExtra, /* Number of bytes of extra space to alloc */ char **ppExtra /* Pointer to the "extra" space */ ){ Index *p; /* Allocated index object */ - int nByte; /* Bytes of space for Index object + arrays */ + i64 nByte; /* Bytes of space for Index object + arrays */ + assert( nCol <= 2*db->aLimit[SQLITE_LIMIT_COLUMN] ); nByte = ROUND8(sizeof(Index)) + /* Index structure */ ROUND8(sizeof(char*)*nCol) + /* Index.azColl */ ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */ @@ -125812,8 +130758,9 @@ SQLITE_PRIVATE Index *sqlite3AllocateIndexObject( p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1); p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol; p->aSortOrder = (u8*)pExtra; - p->nColumn = nCol; - p->nKeyCol = nCol - 1; + assert( nCol>0 ); + p->nColumn = (u16)nCol; + p->nKeyCol = (u16)(nCol - 1); *ppExtra = ((char*)p) + nByte; } return p; @@ -125953,9 +130900,6 @@ SQLITE_PRIVATE void sqlite3CreateIndex( if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 && db->init.busy==0 && pTblName!=0 -#if SQLITE_USER_AUTHENTICATION - && sqlite3UserAuthTable(pTab->zName)==0 -#endif ){ sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName); goto exit_create_index; @@ -126003,8 +130947,9 @@ SQLITE_PRIVATE void sqlite3CreateIndex( if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){ if( !ifNotExist ){ sqlite3ErrorMsg(pParse, "index %s already exists", zName); + }else if( db->init.busy ){ + sqlite3ErrorMsg(pParse,""); /* corruptSchema() will do the error */ }else{ - assert( !db->init.busy ); sqlite3CodeVerifySchema(pParse, iDb); sqlite3ForceNotReadOnly(pParse); } @@ -126542,6 +131487,7 @@ SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists goto exit_drop_index; } iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); + assert( iDb>=0 && iDb<db->nDb ); #ifndef SQLITE_OMIT_AUTHORIZATION { int code = SQLITE_DROP_INDEX; @@ -126627,12 +131573,11 @@ SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token * sqlite3 *db = pParse->db; int i; if( pList==0 ){ - pList = sqlite3DbMallocZero(db, sizeof(IdList) ); + pList = sqlite3DbMallocZero(db, SZ_IDLIST(1)); if( pList==0 ) return 0; }else{ IdList *pNew; - pNew = sqlite3DbRealloc(db, pList, - sizeof(IdList) + pList->nId*sizeof(pList->a)); + pNew = sqlite3DbRealloc(db, pList, SZ_IDLIST(pList->nId+1)); if( pNew==0 ){ sqlite3IdListDelete(db, pList); return 0; @@ -126654,7 +131599,6 @@ SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){ int i; assert( db!=0 ); if( pList==0 ) return; - assert( pList->eU4!=EU4_EXPR ); /* EU4_EXPR mode is not currently used */ for(i=0; i<pList->nId; i++){ sqlite3DbFree(db, pList->a[i].zName); } @@ -126732,8 +131676,7 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge( return 0; } if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST; - pNew = sqlite3DbRealloc(db, pSrc, - sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); + pNew = sqlite3DbRealloc(db, pSrc, SZ_SRCLIST(nAlloc)); if( pNew==0 ){ assert( db->mallocFailed ); return 0; @@ -126808,7 +131751,7 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListAppend( assert( pParse->db!=0 ); db = pParse->db; if( pList==0 ){ - pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) ); + pList = sqlite3DbMallocRawNN(pParse->db, SZ_SRCLIST(1)); if( pList==0 ) return 0; pList->nAlloc = 1; pList->nSrc = 1; @@ -127075,16 +132018,22 @@ SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pI ** are deleted by this function. */ SQLITE_PRIVATE SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){ - assert( p1 && p1->nSrc==1 ); + assert( p1 ); + assert( p2 || pParse->nErr ); + assert( p2==0 || p2->nSrc>=1 ); + testcase( p1->nSrc==0 ); if( p2 ){ - SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1); + int nOld = p1->nSrc; + SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, nOld); if( pNew==0 ){ sqlite3SrcListDelete(pParse->db, p2); }else{ p1 = pNew; - memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem)); + memcpy(&p1->a[nOld], p2->a, p2->nSrc*sizeof(SrcItem)); + assert( nOld==1 || (p2->a[0].fg.jointype & JT_LTORJ)==0 ); + assert( p1->nSrc>=1 ); + p1->a[0].fg.jointype |= (JT_LTORJ & p2->a[0].fg.jointype); sqlite3DbFree(pParse->db, p2); - p1->a[0].fg.jointype |= (JT_LTORJ & p1->a[1].fg.jointype); } } return p1; @@ -127436,8 +132385,7 @@ SQLITE_PRIVATE void sqlite3RowidConstraint( } /* -** Check to see if pIndex uses the collating sequence pColl. Return -** true if it does and false if it does not. +** Return true if any column of pIndex uses the zColl collation */ #ifndef SQLITE_OMIT_REINDEX static int collationMatch(const char *zColl, Index *pIndex){ @@ -127445,8 +132393,8 @@ static int collationMatch(const char *zColl, Index *pIndex){ assert( zColl!=0 ); for(i=0; i<pIndex->nColumn; i++){ const char *z = pIndex->azColl[i]; - assert( z!=0 || pIndex->aiColumn[i]<0 ); - if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){ + assert( z!=0 ); + if( 0==sqlite3StrICmp(z, zColl) ){ return 1; } } @@ -127454,73 +132402,39 @@ static int collationMatch(const char *zColl, Index *pIndex){ } #endif -/* -** Recompute all indices of pTab that use the collating sequence pColl. -** If pColl==0 then recompute all indices of pTab. -*/ -#ifndef SQLITE_OMIT_REINDEX -static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){ - if( !IsVirtual(pTab) ){ - Index *pIndex; /* An index associated with pTab */ - - for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ - if( zColl==0 || collationMatch(zColl, pIndex) ){ - int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - sqlite3BeginWriteOperation(pParse, 0, iDb); - sqlite3RefillIndex(pParse, pIndex, -1); - } - } - } -} -#endif - -/* -** Recompute all indices of all tables in all databases where the -** indices use the collating sequence pColl. If pColl==0 then recompute -** all indices everywhere. -*/ -#ifndef SQLITE_OMIT_REINDEX -static void reindexDatabases(Parse *pParse, char const *zColl){ - Db *pDb; /* A single database */ - int iDb; /* The database index number */ - sqlite3 *db = pParse->db; /* The database connection */ - HashElem *k; /* For looping over tables in pDb */ - Table *pTab; /* A table in the database */ - - assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */ - for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ - assert( pDb!=0 ); - for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ - pTab = (Table*)sqliteHashData(k); - reindexTable(pParse, pTab, zColl); - } - } -} -#endif - /* ** Generate code for the REINDEX command. ** ** REINDEX -- 1 ** REINDEX <collation> -- 2 -** REINDEX ?<database>.?<tablename> -- 3 -** REINDEX ?<database>.?<indexname> -- 4 +** REINDEX ?<database>.?<indexname> -- 3 +** REINDEX ?<database>.?<tablename> -- 4 +** REINDEX EXPRESSIONS -- 5 ** -** Form 1 causes all indices in all attached databases to be rebuilt. -** Form 2 rebuilds all indices in all databases that use the named +** Form 1 causes all indexes in all attached databases to be rebuilt. +** Form 2 rebuilds all indexes in all databases that use the named ** collating function. Forms 3 and 4 rebuild the named index or all -** indices associated with the named table. +** indexes associated with the named table, respectively. Form 5 +** rebuilds all expression indexes in addition to all collations, +** indexes, or tables named "EXPRESSIONS". +** +** If the name is ambiguous such that it matches two or more of +** forms 2 through 5, then rebuild the union of all matching indexes, +** taken care to avoid rebuilding the same index more than once. */ #ifndef SQLITE_OMIT_REINDEX SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ - CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */ - char *z; /* Name of a table or index */ - const char *zDb; /* Name of the database */ - Table *pTab; /* A table in the database */ - Index *pIndex; /* An index associated with pTab */ - int iDb; /* The database index number */ + char *z = 0; /* Name of a table or index or collation */ + const char *zDb = 0; /* Name of the database */ + int iReDb = -1; /* The database index number */ sqlite3 *db = pParse->db; /* The database connection */ Token *pObjName; /* Name of the table or index to be reindexed */ + int bMatch = 0; /* At least one name match */ + const char *zColl = 0; /* Rebuild indexes using this collation */ + Table *pReTab = 0; /* Rebuild all indexes of this table */ + Index *pReIndex = 0; /* Rebuild this index */ + int isExprIdx = 0; /* Rebuild all expression indexes */ + int bAll = 0; /* Rebuild all indexes */ /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ @@ -127529,41 +132443,66 @@ SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){ } if( pName1==0 ){ - reindexDatabases(pParse, 0); - return; + /* rebuild all indexes */ + bMatch = 1; + bAll = 1; }else if( NEVER(pName2==0) || pName2->z==0 ){ - char *zColl; assert( pName1->z ); - zColl = sqlite3NameFromToken(pParse->db, pName1); - if( !zColl ) return; - pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); - if( pColl ){ - reindexDatabases(pParse, zColl); - sqlite3DbFree(db, zColl); - return; + z = sqlite3NameFromToken(pParse->db, pName1); + if( z==0 ) return; + }else{ + iReDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); + if( iReDb<0 ) return; + z = sqlite3NameFromToken(db, pObjName); + if( z==0 ) return; + zDb = db->aDb[iReDb].zDbSName; + } + if( !bAll ){ + if( zDb==0 && sqlite3StrICmp(z, "expressions")==0 ){ + isExprIdx = 1; + bMatch = 1; + } + if( zDb==0 && sqlite3FindCollSeq(db, ENC(db), z, 0)!=0 ){ + zColl = z; + bMatch = 1; + } + if( zColl==0 && (pReTab = sqlite3FindTable(db, z, zDb))!=0 ){ + bMatch = 1; + } + if( zColl==0 && (pReIndex = sqlite3FindIndex(db, z, zDb))!=0 ){ + bMatch = 1; } - sqlite3DbFree(db, zColl); } - iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName); - if( iDb<0 ) return; - z = sqlite3NameFromToken(db, pObjName); - if( z==0 ) return; - zDb = pName2->n ? db->aDb[iDb].zDbSName : 0; - pTab = sqlite3FindTable(db, z, zDb); - if( pTab ){ - reindexTable(pParse, pTab, 0); - sqlite3DbFree(db, z); - return; + if( bMatch ){ + int iDb; + HashElem *k; + Table *pTab; + Index *pIdx; + Db *pDb; + for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){ + assert( pDb!=0 ); + if( iReDb>=0 && iReDb!=iDb ) continue; + for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){ + pTab = (Table*)sqliteHashData(k); + if( IsVirtual(pTab) ) continue; + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + if( bAll + || pTab==pReTab + || pIdx==pReIndex + || (isExprIdx && pIdx->bHasExpr) + || (zColl!=0 && collationMatch(zColl,pIdx)) + ){ + sqlite3BeginWriteOperation(pParse, 0, iDb); + sqlite3RefillIndex(pParse, pIdx, -1); + } + } /* End loop over indexes of pTab */ + } /* End loop over tables of iDb */ + } /* End loop over databases */ + }else{ + sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); } - pIndex = sqlite3FindIndex(db, z, zDb); sqlite3DbFree(db, z); - if( pIndex ){ - iDb = sqlite3SchemaToIndex(db, pIndex->pTable->pSchema); - sqlite3BeginWriteOperation(pParse, 0, iDb); - sqlite3RefillIndex(pParse, pIndex, -1); - return; - } - sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed"); + return; } #endif @@ -127595,14 +132534,19 @@ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){ } if( pParse->nErr ){ assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ ); - if( pIdx->bNoQuery==0 ){ + if( pIdx->bNoQuery==0 + && sqlite3HashFind(&pIdx->pSchema->idxHash, pIdx->zName) + ){ /* Deactivate the index because it contains an unknown collating ** sequence. The only way to reactive the index is to reload the ** schema. Adding the missing collating sequence later does not ** reactive the index. The application had the chance to register ** the missing index using the collation-needed callback. For ** simplicity, SQLite will not give the application a second chance. - */ + ** + ** Except, do not do this if the index is not in the schema hash + ** table. In this case the index is currently being constructed + ** by a CREATE INDEX statement, and retrying will not help. */ pIdx->bNoQuery = 1; pParse->rc = SQLITE_ERROR_RETRY; } @@ -127694,10 +132638,9 @@ SQLITE_PRIVATE With *sqlite3WithAdd( } if( pWith ){ - sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); - pNew = sqlite3DbRealloc(db, pWith, nByte); + pNew = sqlite3DbRealloc(db, pWith, SZ_WITH(pWith->nCte+1)); }else{ - pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); + pNew = sqlite3DbMallocZero(db, SZ_WITH(1)); } assert( (pNew!=0 && zName!=0) || db->mallocFailed ); @@ -128035,12 +132978,18 @@ static int matchQuality( u8 enc /* Desired text encoding */ ){ int match; - assert( p->nArg>=-1 ); + assert( p->nArg>=(-4) && p->nArg!=(-2) ); + assert( nArg>=(-2) ); /* Wrong number of arguments means "no match" */ if( p->nArg!=nArg ){ - if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH; + if( nArg==(-2) ) return p->xSFunc==0 ? 0 : FUNC_PERFECT_MATCH; if( p->nArg>=0 ) return 0; + /* Special p->nArg values available to built-in functions only: + ** -3 1 or more arguments required + ** -4 2 or more arguments required + */ + if( p->nArg<(-2) && nArg<(-2-p->nArg) ) return 0; } /* Give a better score to a function with a specific number of arguments @@ -128234,6 +133183,7 @@ SQLITE_PRIVATE void sqlite3SchemaClear(void *p){ for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){ sqlite3DeleteTrigger(&xdb, (Trigger*)sqliteHashData(pElem)); } + sqlite3HashClear(&temp2); sqlite3HashInit(&pSchema->tblHash); for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){ @@ -128362,7 +133312,7 @@ static int vtabIsReadOnly(Parse *pParse, Table *pTab){ ** * Only allow DELETE, INSERT, or UPDATE of non-SQLITE_VTAB_INNOCUOUS ** virtual tables if PRAGMA trusted_schema=ON. */ - if( pParse->pToplevel!=0 + if( (pParse->pToplevel!=0 || (pParse->prepFlags & SQLITE_PREPARE_FROM_DDL)) && pTab->u.vtab.p->eVtabRisk > ((pParse->db->flags & SQLITE_TrustedSchema)!=0) ){ @@ -129191,6 +134141,7 @@ SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete( v = pParse->pVdbe; pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ + int p3 = 0; assert( iIdxCur+i!=iDataCur || pPk==pIdx ); if( aRegIdx!=0 && aRegIdx[i]==0 ) continue; if( pIdx==pPk ) continue; @@ -129198,9 +134149,12 @@ SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete( VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName)); r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1, &iPartIdxLabel, pPrior, r1); - sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1, - pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn); - sqlite3VdbeChangeP5(v, 1); /* Cause IdxDelete to error if no entry found */ + if( pIdx->bHasExpr && aRegIdx ){ + p3 = aRegIdx[i]; + } + sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1, p3); + sqlite3VdbeChangeP4(v, -1, (const char*)pIdx, P4_INDEX); + sqlite3VdbeChangeP5(v, pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn); sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel); pPrior = pIdx; } @@ -129439,13 +134393,17 @@ static void lengthFunc( case SQLITE_TEXT: { const unsigned char *z = sqlite3_value_text(argv[0]); const unsigned char *z0; - unsigned char c; if( z==0 ) return; z0 = z; - while( (c = *z)!=0 ){ - z++; - if( c>=0xc0 ){ - while( (*z & 0xc0)==0x80 ){ z++; z0++; } + while( 1 /*exit-by-break*/ ){ + /* vvvvvv---- See tag-20260418-01 */ + if( (u8)(z[0]-1)<(0x80-1) ){ + z++; + }else if( z[0]==0 ){ + break; + }else{ + z++; + while( (z[0]&0xc0)==0x80 ){ z++; z0++; } } } sqlite3_result_int(context, (int)(z-z0)); @@ -129625,7 +134583,6 @@ static void printfFunc( PrintfArguments x; StrAccum str; const char *zFormat; - int n; sqlite3 *db = sqlite3_context_db_handle(context); if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){ @@ -129635,9 +134592,7 @@ static void printfFunc( sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); str.printfFlags = SQLITE_PRINTF_SQLFUNC; sqlite3_str_appendf(&str, zFormat, &x); - n = str.nChar; - sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n, - SQLITE_DYNAMIC); + sqlite3_result_str(context, &str, SQLITE_XFER); } } @@ -129663,16 +134618,10 @@ static void substrFunc( int len; int p0type; i64 p1, p2; - int negP2 = 0; assert( argc==3 || argc==2 ); - if( sqlite3_value_type(argv[1])==SQLITE_NULL - || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL) - ){ - return; - } p0type = sqlite3_value_type(argv[0]); - p1 = sqlite3_value_int(argv[1]); + p1 = sqlite3_value_int64(argv[1]); if( p0type==SQLITE_BLOB ){ len = sqlite3_value_bytes(argv[0]); z = sqlite3_value_blob(argv[0]); @@ -129688,28 +134637,31 @@ static void substrFunc( } } } -#ifdef SQLITE_SUBSTR_COMPATIBILITY - /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as - ** as substr(X,1,N) - it returns the first N characters of X. This - ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8] - ** from 2009-02-02 for compatibility of applications that exploited the - ** old buggy behavior. */ - if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */ -#endif if( argc==3 ){ - p2 = sqlite3_value_int(argv[2]); - if( p2<0 ){ - p2 = -p2; - negP2 = 1; - } + p2 = sqlite3_value_int64(argv[2]); + if( p2==0 && sqlite3_value_type(argv[2])==SQLITE_NULL ) return; }else{ - p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH]; + p2 = LARGEST_INT64; + } + if( p1==0 ){ +#ifdef SQLITE_SUBSTR_COMPATIBILITY + /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as + ** as substr(X,1,N) - it returns the first N characters of X. This + ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8] + ** from 2009-02-02 for compatibility of applications that exploited the + ** old buggy behavior. */ + p1 = 1; /* <rdar://problem/6778339> */ +#endif + if( sqlite3_value_type(argv[1])==SQLITE_NULL ) return; } if( p1<0 ){ p1 += len; if( p1<0 ){ - p2 += p1; - if( p2<0 ) p2 = 0; + if( p2<0 ){ + p2 = 0; + }else{ + p2 += p1; + } p1 = 0; } }else if( p1>0 ){ @@ -129717,28 +134669,44 @@ static void substrFunc( }else if( p2>0 ){ p2--; } - if( negP2 ){ - p1 -= p2; - if( p1<0 ){ - p2 += p1; - p1 = 0; + if( p2<0 ){ + if( p2<-p1 ){ + p2 = p1; + }else{ + p2 = -p2; } + p1 -= p2; } assert( p1>=0 && p2>=0 ); if( p0type!=SQLITE_BLOB ){ - while( *z && p1 ){ - SQLITE_SKIP_UTF8(z); - p1--; + for( ; p1>0; p1--){ + /* vvvvvv---- See tag-20260418-01 */ + if( (u8)(z[0]-1)<(0x80-1) ){ + z++; + }else if( z[0]==0 ){ + break; + }else{ + do{ z++; }while( (z[0]&0xc0)==0x80 ); + } } - for(z2=z; *z2 && p2; p2--){ - SQLITE_SKIP_UTF8(z2); + for(z2=z; p2>0; p2--){ + /* vvvvvv---- See tag-20260418-01 */ + if( (u8)(z2[0]-1)<(0x80-1) ){ + z2++; + }else if( z2[0]==0 ){ + break; + }else{ + do{ z2++; }while( (z2[0]&0xc0)==0x80 ); + } } sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT, SQLITE_UTF8); }else{ - if( p1+p2>len ){ + if( p1>=len ){ + p1 = p2 = 0; + }else if( p2>len-p1 ){ p2 = len-p1; - if( p2<0 ) p2 = 0; + assert( p2>0 ); } sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT); } @@ -129749,13 +134717,13 @@ static void substrFunc( */ #ifndef SQLITE_OMIT_FLOATING_POINT static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ - int n = 0; + i64 n = 0; double r; char *zBuf; assert( argc==1 || argc==2 ); if( argc==2 ){ if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return; - n = sqlite3_value_int(argv[1]); + n = sqlite3_value_int64(argv[1]); if( n>30 ) n = 30; if( n<0 ) n = 0; } @@ -129770,12 +134738,12 @@ static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ }else if( n==0 ){ r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5))); }else{ - zBuf = sqlite3_mprintf("%!.*f",n,r); + zBuf = sqlite3_mprintf("%!.*f",(int)n,r); if( zBuf==0 ){ sqlite3_result_error_nomem(context); return; } - sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8); + sqlite3AtoF(zBuf, &r); sqlite3_free(zBuf); } sqlite3_result_double(context, r); @@ -129794,7 +134762,7 @@ static void *contextMalloc(sqlite3_context *context, i64 nByte){ sqlite3 *db = sqlite3_context_db_handle(context); assert( nByte>0 ); testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] ); - testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); + testcase( nByte==(i64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ sqlite3_result_error_toobig(context); z = 0; @@ -130399,7 +135367,7 @@ static const char hexdigits[] = { ** Append to pStr text that is the SQL literal representation of the ** value contained in pValue. */ -SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){ +SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue, int bEscape){ /* As currently implemented, the string must be initially empty. ** we might relax this requirement in the future, but that will ** require enhancements to the implementation. */ @@ -130407,18 +135375,11 @@ SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){ switch( sqlite3_value_type(pValue) ){ case SQLITE_FLOAT: { - double r1, r2; - const char *zVal; - r1 = sqlite3_value_double(pValue); - sqlite3_str_appendf(pStr, "%!0.15g", r1); - zVal = sqlite3_str_value(pStr); - if( zVal ){ - sqlite3AtoF(zVal, &r2, pStr->nChar, SQLITE_UTF8); - if( r1!=r2 ){ - sqlite3_str_reset(pStr); - sqlite3_str_appendf(pStr, "%!0.20e", r1); - } - } + /* ,--- Show infinity as 9.0e+999 + ** | + ** | ,--- 17 precision guarantees round-trip + ** v v */ + sqlite3_str_appendf(pStr, "%!0.17g", sqlite3_value_double(pValue)); break; } case SQLITE_INTEGER: { @@ -130447,7 +135408,7 @@ SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){ } case SQLITE_TEXT: { const unsigned char *zArg = sqlite3_value_text(pValue); - sqlite3_str_appendf(pStr, "%Q", zArg); + sqlite3_str_appendf(pStr, bEscape ? "%#Q" : "%Q", zArg); break; } default: { @@ -130458,6 +135419,105 @@ SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){ } } +/* +** Return true if z[] begins with N hexadecimal digits, and write +** a decoding of those digits into *pVal. Or return false if any +** one of the first N characters in z[] is not a hexadecimal digit. +*/ +static int isNHex(const char *z, int N, u32 *pVal){ + int i; + u32 v = 0; + for(i=0; i<N; i++){ + if( !sqlite3Isxdigit(z[i]) ) return 0; + v = (v<<4) + sqlite3HexToInt(z[i]); + } + *pVal = v; + return 1; +} + +/* +** Implementation of the UNISTR() function. +** +** This is intended to be a work-alike of the UNISTR() function in +** PostgreSQL. Quoting from the PG documentation (PostgreSQL 17 - +** scraped on 2025-02-22): +** +** Evaluate escaped Unicode characters in the argument. Unicode +** characters can be specified as \XXXX (4 hexadecimal digits), +** \+XXXXXX (6 hexadecimal digits), \uXXXX (4 hexadecimal digits), +** or \UXXXXXXXX (8 hexadecimal digits). To specify a backslash, +** write two backslashes. All other characters are taken literally. +*/ +static void unistrFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + char *zOut; + const char *zIn; + int nIn; + int i, j, n; + u32 v; + + assert( argc==1 ); + UNUSED_PARAMETER( argc ); + zIn = (const char*)sqlite3_value_text(argv[0]); + if( zIn==0 ) return; + nIn = sqlite3_value_bytes(argv[0]); + zOut = sqlite3_malloc64(nIn+1); + if( zOut==0 ){ + sqlite3_result_error_nomem(context); + return; + } + i = j = 0; + while( i<nIn ){ + const char *z = strchr(&zIn[i],'\\'); + if( z==0 ){ + n = nIn - i; + memmove(&zOut[j], &zIn[i], n); + j += n; + break; + } + n = z - &zIn[i]; + if( n>0 ){ + memmove(&zOut[j], &zIn[i], n); + j += n; + i += n; + } + if( zIn[i+1]=='\\' ){ + i += 2; + zOut[j++] = '\\'; + }else if( sqlite3Isxdigit(zIn[i+1]) ){ + if( !isNHex(&zIn[i+1], 4, &v) ) goto unistr_error; + i += 5; + j += sqlite3AppendOneUtf8Character(&zOut[j], v); + }else if( zIn[i+1]=='+' ){ + if( !isNHex(&zIn[i+2], 6, &v) ) goto unistr_error; + i += 8; + j += sqlite3AppendOneUtf8Character(&zOut[j], v); + }else if( zIn[i+1]=='u' ){ + if( !isNHex(&zIn[i+2], 4, &v) ) goto unistr_error; + i += 6; + j += sqlite3AppendOneUtf8Character(&zOut[j], v); + }else if( zIn[i+1]=='U' ){ + if( !isNHex(&zIn[i+2], 8, &v) ) goto unistr_error; + i += 10; + j += sqlite3AppendOneUtf8Character(&zOut[j], v); + }else{ + goto unistr_error; + } + } + zOut[j] = 0; + sqlite3_result_text64(context, zOut, j, sqlite3_free, SQLITE_UTF8_ZT); + return; + +unistr_error: + sqlite3_free(zOut); + sqlite3_result_error(context, "invalid Unicode escape", -1); + return; +} + + /* ** Implementation of the QUOTE() function. ** @@ -130467,6 +135527,10 @@ SQLITE_PRIVATE void sqlite3QuoteValue(StrAccum *pStr, sqlite3_value *pValue){ ** as needed. BLOBs are encoded as hexadecimal literals. Strings with ** embedded NUL characters cannot be represented as string literals in SQL ** and hence the returned string literal is truncated prior to the first NUL. +** +** If sqlite3_user_data() is non-zero, then the UNISTR_QUOTE() function is +** implemented instead. The difference is that UNISTR_QUOTE() uses the +** UNISTR() function to escape control characters. */ static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ sqlite3_str str; @@ -130474,13 +135538,8 @@ static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ assert( argc==1 ); UNUSED_PARAMETER(argc); sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); - sqlite3QuoteValue(&str,argv[0]); - sqlite3_result_text(context, sqlite3StrAccumFinish(&str), str.nChar, - SQLITE_DYNAMIC); - if( str.accError!=SQLITE_OK ){ - sqlite3_result_null(context); - sqlite3_result_error_code(context, str.accError); - } + sqlite3QuoteValue(&str,argv[0],SQLITE_PTR_TO_INT(sqlite3_user_data(context))); + sqlite3_result_str(context, &str, SQLITE_XFER); } /* @@ -130537,7 +135596,7 @@ static void charFunc( } \ } *zOut = 0; - sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8); + sqlite3_result_text64(context, (char*)z, zOut-z,sqlite3_free,SQLITE_UTF8_ZT); } /* @@ -130566,7 +135625,7 @@ static void hexFunc( } *z = 0; sqlite3_result_text64(context, zHex, (u64)(z-zHex), - sqlite3_free, SQLITE_UTF8); + sqlite3_free, SQLITE_UTF8_ZT); } } @@ -130700,7 +135759,7 @@ static void replaceFunc( int nRep; /* Size of zRep */ i64 nOut; /* Maximum size of zOut */ int loopLimit; /* Last zStr[] that might match zPattern[] */ - int i, j; /* Loop counters */ + i64 i, j; /* Loop counters */ unsigned cntExpand; /* Number zOut expansions */ sqlite3 *db = sqlite3_context_db_handle(context); @@ -130729,7 +135788,7 @@ static void replaceFunc( assert( zRep==sqlite3_value_text(argv[2]) ); nOut = nStr + 1; assert( nOut<SQLITE_MAX_LENGTH ); - zOut = contextMalloc(context, (i64)nOut); + zOut = contextMalloc(context, nOut); if( zOut==0 ){ return; } @@ -130873,13 +135932,14 @@ static void concatFuncCore( int nSep, const char *zSep ){ - i64 j, k, n = 0; + i64 j, n = 0; int i; + int bNotNull = 0; /* True after at least NOT NULL argument seen */ char *z; for(i=0; i<argc; i++){ n += sqlite3_value_bytes(argv[i]); } - n += (argc-1)*nSep; + n += (argc-1)*(i64)nSep; z = sqlite3_malloc64(n+1); if( z==0 ){ sqlite3_result_error_nomem(context); @@ -130887,22 +135947,23 @@ static void concatFuncCore( } j = 0; for(i=0; i<argc; i++){ - k = sqlite3_value_bytes(argv[i]); - if( k>0 ){ + if( sqlite3_value_type(argv[i])!=SQLITE_NULL ){ + int k = sqlite3_value_bytes(argv[i]); const char *v = (const char*)sqlite3_value_text(argv[i]); if( v!=0 ){ - if( j>0 && nSep>0 ){ + if( bNotNull && nSep>0 ){ memcpy(&z[j], zSep, nSep); j += nSep; } memcpy(&z[j], v, k); j += k; + bNotNull = 1; } } } z[j] = 0; assert( j<=n ); - sqlite3_result_text64(context, z, j, sqlite3_free, SQLITE_UTF8); + sqlite3_result_text64(context, z, j, sqlite3_free, SQLITE_UTF8_ZT); } /* @@ -131019,6 +136080,21 @@ static void soundexFunc( } #endif /* SQLITE_SOUNDEX */ +#if defined(SQLITE_DEBUG) || defined(SQLITE_BUILTIN_OOM_FUNCTION) +/* +** This SQL function just invokes sqlite3OomFault() and then returns +** NULL. Used for testing only. +*/ +static void oomFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + sqlite3 *db = sqlite3_context_db_handle(context); + sqlite3OomFault(db); +} +#endif /* SQLITE_DEBUG || SQLITE_BUILTIN_OOM_FUNCTION */ + #ifndef SQLITE_OMIT_LOAD_EXTENSION /* ** A function that loads a shared-library extension then returns NULL. @@ -131125,7 +136201,7 @@ static void kahanBabuskaNeumaierInit( ** that it returns NULL if it sums over no inputs. TOTAL returns ** 0.0 in that case. In addition, TOTAL always returns a float where ** SUM might return an integer if it never encounters a floating point -** value. TOTAL never fails, but SUM might through an exception if +** value. TOTAL never fails, but SUM might throw an exception if ** it overflows an integer. */ static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){ @@ -131177,8 +136253,16 @@ static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){ assert( p->cnt>0 ); p->cnt--; if( !p->approx ){ - p->iSum -= sqlite3_value_int64(argv[0]); - }else if( type==SQLITE_INTEGER ){ + i64 x = p->iSum; + if( sqlite3SubInt64(&x, sqlite3_value_int64(argv[0]))==0 ){ + p->iSum = x; + return; + } + p->ovrfl = 1; + p->approx = 1; + kahanBabuskaNeumaierInit(p, p->iSum); + } + if( type==SQLITE_INTEGER ){ i64 iVal = sqlite3_value_int64(argv[0]); if( iVal!=SMALLEST_INT64 ){ kahanBabuskaNeumaierStepInt64(p, -iVal); @@ -131503,7 +136587,7 @@ static void groupConcatFinalize(sqlite3_context *context){ GroupConcatCtx *pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0); if( pGCC ){ - sqlite3ResultStrAccum(context, &pGCC->str); + sqlite3_result_str(context, &pGCC->str, SQLITE_XFER); #ifndef SQLITE_OMIT_WINDOWFUNC sqlite3_free(pGCC->pnSepLengths); #endif @@ -131513,18 +136597,8 @@ static void groupConcatFinalize(sqlite3_context *context){ static void groupConcatValue(sqlite3_context *context){ GroupConcatCtx *pGCC = (GroupConcatCtx*)sqlite3_aggregate_context(context, 0); - if( pGCC ){ - StrAccum *pAccum = &pGCC->str; - if( pAccum->accError==SQLITE_TOOBIG ){ - sqlite3_result_error_toobig(context); - }else if( pAccum->accError==SQLITE_NOMEM ){ - sqlite3_result_error_nomem(context); - }else if( pGCC->nAccum>0 && pAccum->nChar==0 ){ - sqlite3_result_text(context, "", 1, SQLITE_STATIC); - }else{ - const char *zText = sqlite3_str_value(pAccum); - sqlite3_result_text(context, zText, pAccum->nChar, SQLITE_TRANSIENT); - } + if( pGCC && pGCC->nAccum>0 ){ + sqlite3_result_str(context, &pGCC->str, SQLITE_COPY); } } #else @@ -131565,6 +136639,8 @@ SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive) sqlite3CreateFunc(db, "like", nArg, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0); pDef = sqlite3FindFunction(db, "like", nArg, SQLITE_UTF8, 0); + assert( pDef!=0 ); /* The sqlite3CreateFunc() call above cannot fail + ** because the "like" SQL-function already exists */ pDef->funcFlags |= flags; pDef->funcFlags &= ~SQLITE_FUNC_UNSAFE; } @@ -131839,6 +136915,598 @@ static void signFunc( sqlite3_result_int(context, x<0.0 ? -1 : x>0.0 ? +1 : 0); } +#if defined(SQLITE_ENABLE_PERCENTILE) +/*********************************************************************** +** This section implements the percentile(Y,P) SQL function and similar. +** Requirements: +** +** (1) The percentile(Y,P) function is an aggregate function taking +** exactly two arguments. +** +** (2) If the P argument to percentile(Y,P) is not the same for every +** row in the aggregate then an error is thrown. The word "same" +** in the previous sentence means that the value differ by less +** than 0.001. +** +** (3) If the P argument to percentile(Y,P) evaluates to anything other +** than a number in the range of 0.0 to 100.0 inclusive then an +** error is thrown. +** +** (4) If any Y argument to percentile(Y,P) evaluates to a value that +** is not NULL and is not numeric then an error is thrown. +** +** (5) If any Y argument to percentile(Y,P) evaluates to plus or minus +** infinity then an error is thrown. (SQLite always interprets NaN +** values as NULL.) +** +** (6) Both Y and P in percentile(Y,P) can be arbitrary expressions, +** including CASE WHEN expressions. +** +** (7) The percentile(Y,P) aggregate is able to handle inputs of at least +** one million (1,000,000) rows. +** +** (8) If there are no non-NULL values for Y, then percentile(Y,P) +** returns NULL. +** +** (9) If there is exactly one non-NULL value for Y, the percentile(Y,P) +** returns the one Y value. +** +** (10) If there N non-NULL values of Y where N is two or more and +** the Y values are ordered from least to greatest and a graph is +** drawn from 0 to N-1 such that the height of the graph at J is +** the J-th Y value and such that straight lines are drawn between +** adjacent Y values, then the percentile(Y,P) function returns +** the height of the graph at P*(N-1)/100. +** +** (11) The percentile(Y,P) function always returns either a floating +** point number or NULL. +** +** (12) The percentile(Y,P) is implemented as a single C99 source-code +** file that compiles into a shared-library or DLL that can be loaded +** into SQLite using the sqlite3_load_extension() interface. +** +** (13) A separate median(Y) function is the equivalent percentile(Y,50). +** +** (14) A separate percentile_cont(Y,P) function is equivalent to +** percentile(Y,P/100.0). In other words, the fraction value in +** the second argument is in the range of 0 to 1 instead of 0 to 100. +** +** (15) A separate percentile_disc(Y,P) function is like +** percentile_cont(Y,P) except that instead of returning the weighted +** average of the nearest two input values, it returns the next lower +** value. So the percentile_disc(Y,P) will always return a value +** that was one of the inputs. +** +** (16) All of median(), percentile(Y,P), percentile_cont(Y,P) and +** percentile_disc(Y,P) can be used as window functions. +** +** Differences from standard SQL: +** +** * The percentile_cont(X,P) function is equivalent to the following in +** standard SQL: +** +** (percentile_cont(P) WITHIN GROUP (ORDER BY X)) +** +** The SQLite syntax is much more compact. The standard SQL syntax +** is also supported if SQLite is compiled with the +** -DSQLITE_ENABLE_ORDERED_SET_AGGREGATES option. +** +** * No median(X) function exists in the SQL standard. App developers +** are expected to write "percentile_cont(0.5)WITHIN GROUP(ORDER BY X)". +** +** * No percentile(Y,P) function exists in the SQL standard. Instead of +** percential(Y,P), developers must write this: +** "percentile_cont(P/100.0) WITHIN GROUP (ORDER BY Y)". Note that +** the fraction parameter to percentile() goes from 0 to 100 whereas +** the fraction parameter in SQL standard percentile_cont() goes from +** 0 to 1. +** +** Implementation notes as of 2024-08-31: +** +** * The regular aggregate-function versions of these routines work +** by accumulating all values in an array of doubles, then sorting +** that array using quicksort before computing the answer. Thus +** the runtime is O(NlogN) where N is the number of rows of input. +** +** * For the window-function versions of these routines, the array of +** inputs is sorted as soon as the first value is computed. Thereafter, +** the array is kept in sorted order using an insert-sort. This +** results in O(N*K) performance where K is the size of the window. +** One can imagine alternative implementations that give O(N*logN*logK) +** performance, but they require more complex logic and data structures. +** The developers have elected to keep the asymptotically slower +** algorithm for now, for simplicity, under the theory that window +** functions are seldom used and when they are, the window size K is +** often small. The developers might revisit that decision later, +** should the need arise. +*/ + +/* The following object is the group context for a single percentile() +** aggregate. Remember all input Y values until the very end. +** Those values are accumulated in the Percentile.a[] array. +*/ +typedef struct Percentile Percentile; +struct Percentile { + u64 nAlloc; /* Number of slots allocated for a[] */ + u64 nUsed; /* Number of slots actually used in a[] */ + char bSorted; /* True if a[] is already in sorted order */ + char bKeepSorted; /* True if advantageous to keep a[] sorted */ + char bPctValid; /* True if rPct is valid */ + double rPct; /* Fraction. 0.0 to 1.0 */ + double *a; /* Array of Y values */ +}; + +/* +** Return TRUE if the input floating-point number is an infinity. +*/ +static int percentIsInfinity(double r){ + sqlite3_uint64 u; + assert( sizeof(u)==sizeof(r) ); + memcpy(&u, &r, sizeof(u)); + return ((u>>52)&0x7ff)==0x7ff; +} + +/* +** Return TRUE if two doubles differ by 0.001 or less. +*/ +static int percentSameValue(double a, double b){ + a -= b; + return a>=-0.001 && a<=0.001; +} + +/* +** Search p (which must have p->bSorted) looking for an entry with +** value y. Return the index of that entry. +** +** If bExact is true, return -1 if the entry is not found. +** +** If bExact is false, return the index at which a new entry with +** value y should be insert in order to keep the values in sorted +** order. The smallest return value in this case will be 0, and +** the largest return value will be p->nUsed. +*/ +static i64 percentBinarySearch(Percentile *p, double y, int bExact){ + i64 iFirst = 0; /* First element of search range */ + i64 iLast = (i64)p->nUsed - 1; /* Last element of search range */ + while( iLast>=iFirst ){ + i64 iMid = (iFirst+iLast)/2; + double x = p->a[iMid]; + if( x<y ){ + iFirst = iMid + 1; + }else if( x>y ){ + iLast = iMid - 1; + }else{ + return iMid; + } + } + if( bExact ) return -1; + return iFirst; +} + +/* +** Generate an error for a percentile function. +** +** The error format string must have exactly one occurrence of "%%s()" +** (with two '%' characters). That substring will be replaced by the name +** of the function. +*/ +static void percentError(sqlite3_context *pCtx, const char *zFormat, ...){ + char *zMsg1; + char *zMsg2; + va_list ap; + + va_start(ap, zFormat); + zMsg1 = sqlite3_vmprintf(zFormat, ap); + va_end(ap); + zMsg2 = zMsg1 ? sqlite3_mprintf(zMsg1, sqlite3VdbeFuncName(pCtx)) : 0; + sqlite3_result_error(pCtx, zMsg2, -1); + sqlite3_free(zMsg1); + sqlite3_free(zMsg2); +} + +/* +** The "step" function for percentile(Y,P) is called once for each +** input row. +*/ +static void percentStep(sqlite3_context *pCtx, int argc, sqlite3_value **argv){ + Percentile *p; + double rPct; + int eType; + double y; + assert( argc==2 || argc==1 ); + + if( argc==1 ){ + /* Requirement 13: median(Y) is the same as percentile(Y,50). */ + rPct = 0.5; + }else{ + /* P must be a number between 0 and 100 for percentile() or between + ** 0.0 and 1.0 for percentile_cont() and percentile_disc(). + ** + ** The user-data is an integer which is 10 times the upper bound. + */ + double mxFrac = (SQLITE_PTR_TO_INT(sqlite3_user_data(pCtx))&2)? 100.0 : 1.0; + eType = sqlite3_value_numeric_type(argv[1]); + rPct = sqlite3_value_double(argv[1])/mxFrac; + if( (eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT) + || rPct<0.0 || rPct>1.0 + ){ + percentError(pCtx, "the fraction argument to %%s()" + " is not between 0.0 and %.1f", + (double)mxFrac); + return; + } + } + + /* Allocate the session context. */ + p = (Percentile*)sqlite3_aggregate_context(pCtx, sizeof(*p)); + if( p==0 ) return; + + /* Remember the P value. Throw an error if the P value is different + ** from any prior row, per Requirement (2). */ + if( !p->bPctValid ){ + p->rPct = rPct; + p->bPctValid = 1; + }else if( !percentSameValue(p->rPct,rPct) ){ + percentError(pCtx, "the fraction argument to %%s()" + " is not the same for all input rows"); + return; + } + + /* Ignore rows for which Y is NULL */ + eType = sqlite3_value_type(argv[0]); + if( eType==SQLITE_NULL ) return; + + /* If not NULL, then Y must be numeric. Otherwise throw an error. + ** Requirement 4 */ + if( eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT ){ + percentError(pCtx, "input to %%s() is not numeric"); + return; + } + + /* Throw an error if the Y value is infinity or NaN */ + y = sqlite3_value_double(argv[0]); + if( percentIsInfinity(y) ){ + percentError(pCtx, "Inf input to %%s()"); + return; + } + + /* Allocate and store the Y */ + if( p->nUsed>=p->nAlloc ){ + u64 n = p->nAlloc*2 + 250; + double *a = sqlite3_realloc64(p->a, sizeof(double)*n); + if( a==0 ){ + sqlite3_free(p->a); + memset(p, 0, sizeof(*p)); + sqlite3_result_error_nomem(pCtx); + return; + } + p->nAlloc = n; + p->a = a; + } + if( p->nUsed==0 ){ + p->a[p->nUsed++] = y; + p->bSorted = 1; + }else if( !p->bSorted || y>=p->a[p->nUsed-1] ){ + p->a[p->nUsed++] = y; + }else if( p->bKeepSorted ){ + i64 i; + i = percentBinarySearch(p, y, 0); + if( i<(int)p->nUsed ){ + memmove(&p->a[i+1], &p->a[i], (p->nUsed-i)*sizeof(p->a[0])); + } + p->a[i] = y; + p->nUsed++; + }else{ + p->a[p->nUsed++] = y; + p->bSorted = 0; + } +} + +/* +** Interchange two doubles. +*/ +#define SWAP_DOUBLE(X,Y) {double ttt=(X);(X)=(Y);(Y)=ttt;} + +/* +** Sort an array of doubles. +** +** Algorithm: quicksort +** +** This is implemented separately rather than using the qsort() routine +** from the standard library because: +** +** (1) To avoid a dependency on qsort() +** (2) To avoid the function call to the comparison routine for each +** comparison. +** +** If parameter iReq is non-negative, then the caller will only access +** elements a[iReq] and a[iReq+1] (if it exists) of the sorted array and +** so it is not necessary to position any other elements. Or if iReq is +** negative, then the final array must be fully sorted. +*/ +static void percentSort( + double *a, /* Array to sort */ + unsigned int n, /* Number of elements in array a[] */ + int iReq /* Element caller cares about (or -ve) */ +){ + int iLt; /* Entries before a[iLt] are less than or equal to rPivot */ + int iGt; /* Entries a[iGt] and after are greater or equal to rPivot */ + int i; /* Loop counter */ + double rPivot; /* The pivot value */ + + assert( n>=2 ); + do{ + /* Put the first, middle, and last elements in sorted order. + ** After doing so, return immediately if the array contains + ** three or fewer elements as there is nothing more to do. + */ + if( a[0]>a[n-1] ){ + SWAP_DOUBLE(a[0],a[n-1]) + } + if( n==2 ) return; + iGt = n-1; + i = n/2; + if( a[0]>a[i] ){ + SWAP_DOUBLE(a[0],a[i]) + }else if( a[i]>a[iGt] ){ + SWAP_DOUBLE(a[i],a[iGt]) + } + if( n==3 ) return; + + /* Take the value of the middle element as the pivot. Shuffle + ** values around so that all elements less than the pivot come + ** before all elements greater than the pivot. + */ + rPivot = a[i]; + iLt = i = 1; + do{ + if( a[i]<rPivot ){ + if( i>iLt ) SWAP_DOUBLE(a[i],a[iLt]) + iLt++; + i++; + }else if( a[i]>rPivot ){ + do{ + iGt--; + }while( iGt>i && a[iGt]>rPivot ); + SWAP_DOUBLE(a[i],a[iGt]) + }else{ + i++; + } + }while( i<iGt ); + + assert( iLt>0 && iLt<iGt && (unsigned)iGt<n ); + testcase( iGt>iLt+1 ); + assert( a[iLt]==rPivot ); + assert( a[iLt-1]<=rPivot ); + assert( a[iGt]>=rPivot ); + assert( a[iLt+1]>=rPivot ); + + if( iReq>=0 ){ + /* In this case, the only elements that the caller requires sorted into + ** the correct positions are elements a[iReq] and a[iReq+1]. At this + ** point we know that element a[iLt] is in the correct position and + ** all elements smaller than a[iLt] are in the left-hand partition. + ** So if (iReq<iLt), then it is only necessary to sort the left + ** partition. + ** + ** If (iReq>=iLt), then elements iReq and iReq+1 are either in the + ** right partition or the equal partition (elements for which + ** iLt<=iElem<iGt). Therefore it is always sufficient to sort only + ** the right partition in this case. */ + if( iReq<iLt ){ + n = iLt; + }else{ + a += iGt; + n -= iGt; + iReq = MAX(0, iReq-iGt); + } + }else{ + /* Recurse on the smaller partition only. The smaller partition + ** will hold n/2 or fewer entries, which assures that the stack + ** depth will not exceed O(log(n)), even for pathological cases. + ** Loop without recursion for the larger partition. */ + if( iLt>(int)(n/2) ){ + if( n-iGt>=2 ) percentSort(a+iGt, n-iGt, -1); + n = iLt; + }else{ + if( iLt>=2 ) percentSort(a, iLt, -1); + a += iGt; + n -= iGt; + } + } + }while( n>=2 ); +} + +/* +** The "inverse" function for percentile(Y,P) is called to remove a +** row that was previously inserted by "step". +*/ +static void percentInverse(sqlite3_context *pCtx,int argc,sqlite3_value **argv){ + Percentile *p; + int eType; + double y; + i64 i; + assert( argc==2 || argc==1 ); + + /* Allocate the session context. */ + p = (Percentile*)sqlite3_aggregate_context(pCtx, sizeof(*p)); + assert( p!=0 ); + + /* Ignore rows for which Y is NULL */ + eType = sqlite3_value_type(argv[0]); + if( eType==SQLITE_NULL ) return; + + /* If not NULL, then Y must be numeric. Otherwise throw an error. + ** Requirement 4 */ + if( eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT ){ + return; + } + + /* Ignore the Y value if it is infinity or NaN */ + y = sqlite3_value_double(argv[0]); + if( percentIsInfinity(y) ){ + return; + } + if( p->bSorted==0 ){ + assert( p->nUsed>1 ); + percentSort(p->a, p->nUsed, -1); + p->bSorted = 1; + } + p->bKeepSorted = 1; + + /* Find and remove the row */ + i = percentBinarySearch(p, y, 1); + if( i>=0 ){ + p->nUsed--; + if( i<(int)p->nUsed ){ + memmove(&p->a[i], &p->a[i+1], (p->nUsed - i)*sizeof(p->a[0])); + } + } +} + +/* +** Compute the final output of percentile(). Clean up all allocated +** memory if and only if bIsFinal is true. +*/ +static void percentCompute(sqlite3_context *pCtx, int bIsFinal){ + Percentile *p; + int settings = SQLITE_PTR_TO_INT(sqlite3_user_data(pCtx))&1; /* Discrete? */ + unsigned i1, i2; + double v1, v2; + double ix, vx; + p = (Percentile*)sqlite3_aggregate_context(pCtx, 0); + if( p==0 ) return; + if( p->a==0 ) return; + if( p->nUsed ){ + ix = p->rPct*(p->nUsed-1); + i1 = (unsigned)ix; + if( p->bSorted==0 ){ + /* In cases where bIsFinal is non-zero, setting Percentile.bSorted + ** after the percentSort() call here is not technically correct, as + ** the array is not fully sorted. But in this case the object will be + ** freed below anyway, so it doesn't matter. */ + assert( p->nUsed>1 ); + percentSort(p->a, p->nUsed, (bIsFinal ? (int)i1 : -1)); + p->bSorted = 1; + } + if( settings & 1 ){ + vx = p->a[i1]; + }else{ + i2 = ix==(double)i1 || i1==p->nUsed-1 ? i1 : i1+1; + v1 = p->a[i1]; + v2 = p->a[i2]; + vx = v1 + (v2-v1)*(ix-i1); + } + sqlite3_result_double(pCtx, vx); + } + if( bIsFinal ){ + sqlite3_free(p->a); + memset(p, 0, sizeof(*p)); + }else{ + p->bKeepSorted = 1; + } +} +static void percentFinal(sqlite3_context *pCtx){ + percentCompute(pCtx, 1); +} +static void percentValue(sqlite3_context *pCtx){ + percentCompute(pCtx, 0); +} +/****** End of percentile family of functions ******/ +#endif /* SQLITE_ENABLE_PERCENTILE */ + +#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT) +/* +** Implementation of sqlite_filestat(SCHEMA). +** +** Return JSON text that describes low-level debug/diagnostic information +** about the sqlite3_file object associated with SCHEMA. +*/ +static void filestatFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + sqlite3 *db = sqlite3_context_db_handle(context); + const char *zDbName; + sqlite3_str *pStr; + Btree *pBtree; + + zDbName = (const char*)sqlite3_value_text(argv[0]); + pBtree = sqlite3DbNameToBtree(db, zDbName); + if( pBtree ){ + Pager *pPager; + sqlite3_file *fd; + int rc; + sqlite3BtreeEnter(pBtree); + pPager = sqlite3BtreePager(pBtree); + assert( pPager!=0 ); + fd = sqlite3PagerFile(pPager); + pStr = sqlite3_str_new(db); + if( sqlite3_str_errcode(pStr) ){ + sqlite3_result_error_nomem(context); + }else{ + sqlite3_str_append(pStr, "{\"db\":", 6); + rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_FILESTAT, pStr); + if( rc ) sqlite3_str_append(pStr, "null", 4); + fd = sqlite3PagerJrnlFile(pPager); + if( fd && fd->pMethods!=0 ){ + sqlite3_str_appendall(pStr, ",\"journal\":"); + rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_FILESTAT, pStr); + if( rc ) sqlite3_str_append(pStr, "null", 4); + } + sqlite3_str_append(pStr, "}", 1); + sqlite3_result_str(context, pStr, SQLITE_FINISH); + } + sqlite3BtreeLeave(pBtree); + }else{ + sqlite3_result_text(context, "{}", 2, SQLITE_STATIC); + } +} +#endif /* SQLITE_DEBUG || SQLITE_ENABLE_FILESTAT */ + +#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_WALSTAT) +/* +** Implementation of sqlite_walstat(SCHEMA). +** +** Return JSON text that describes the current state of a WAL file. +** This function is for debugging and analysis only. It is not part +** of production builds. This function is not part of the SQLite API +** and is likely to change or be removed in future versions of SQLite. +*/ +static void walstatFunc( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + sqlite3 *db = sqlite3_context_db_handle(context); + const char *zDbName; + sqlite3_str *pStr; + Btree *pBtree; + + zDbName = (const char*)sqlite3_value_text(argv[0]); + pBtree = sqlite3DbNameToBtree(db, zDbName); + if( pBtree ){ + Pager *pPager; + sqlite3BtreeEnter(pBtree); + pPager = sqlite3BtreePager(pBtree); + assert( pPager!=0 ); + pStr = sqlite3_str_new(db); + if( sqlite3_str_errcode(pStr) ){ + sqlite3_result_error_nomem(context); + }else{ + sqlite3_str_append(pStr, "{", 1); + sqlite3PagerWalStat(pPager, pStr); + sqlite3_str_append(pStr, "}", 1); + sqlite3_result_str(context, pStr, SQLITE_FINISH); + } + sqlite3BtreeLeave(pBtree); + }else{ + sqlite3_result_text(context, "{}", 2, SQLITE_STATIC); + } +} +#endif /* SQLITE_DEBUG || SQLITE_ENABLE_WALSTAT */ + #ifdef SQLITE_DEBUG /* ** Implementation of fpdecode(x,y,z) function. @@ -131919,7 +137587,7 @@ static void parseuriFunc( flgs = (unsigned int)sqlite3_value_int(argv[1]); rc = sqlite3ParseUri(zVfs, zUri, &flgs, &pVfs, &zFile, &zErr); pResult = sqlite3_str_new(0); - if( pResult ){ + if( !sqlite3_str_errcode(pResult) ){ int i; sqlite3_str_appendf(pResult, "rc=%d", rc); sqlite3_str_appendf(pResult, ", flags=0x%x", flgs); @@ -131946,8 +137614,8 @@ static void parseuriFunc( } } } - sqlite3_result_text(ctx, sqlite3_str_finish(pResult), -1, sqlite3_free); } + sqlite3_result_str(ctx, pResult, SQLITE_FINISH); sqlite3_free_filename(zFile); sqlite3_free(zErr); } @@ -131987,9 +137655,6 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ SFUNCTION(load_extension, 1, 0, 0, loadExt ), SFUNCTION(load_extension, 2, 0, 0, loadExt ), #endif -#if SQLITE_USER_AUTHENTICATION - FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ), -#endif #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ), DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ), @@ -131999,6 +137664,10 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ INLINE_FUNC(likely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY), #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC INLINE_FUNC(sqlite_offset, 1, INLINEFUNC_sqlite_offset, 0 ), +#endif +#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_FILESTAT) + FUNCTION(sqlite_filestat, 1, 0, 0, filestatFunc ), + FUNCTION(sqlite_walstat, 1, 0, 0, walstatFunc ), #endif FUNCTION(ltrim, 1, 1, 0, trimFunc ), FUNCTION(ltrim, 2, 1, 0, trimFunc ), @@ -132006,12 +137675,10 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ FUNCTION(rtrim, 2, 2, 0, trimFunc ), FUNCTION(trim, 1, 3, 0, trimFunc ), FUNCTION(trim, 2, 3, 0, trimFunc ), - FUNCTION(min, -1, 0, 1, minmaxFunc ), - FUNCTION(min, 0, 0, 1, 0 ), + FUNCTION(min, -3, 0, 1, minmaxFunc ), WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0, SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ), - FUNCTION(max, -1, 1, 1, minmaxFunc ), - FUNCTION(max, 0, 1, 1, 0 ), + FUNCTION(max, -3, 1, 1, minmaxFunc ), WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0, SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER ), FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF), @@ -132029,6 +137696,9 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ FUNCTION(fpdecode, 3, 0, 0, fpdecodeFunc ), FUNCTION(parseuri, -1, 0, 0, parseuriFunc ), #endif +#if defined(SQLITE_DEBUG) || defined(SQLITE_BUILTIN_OOM_FUNCTION) + FUNCTION(oom, -1, 0, 0, oomFunc ), +#endif #ifndef SQLITE_OMIT_FLOATING_POINT FUNCTION(round, 1, 0, 0, roundFunc ), FUNCTION(round, 2, 0, 0, roundFunc ), @@ -132038,19 +137708,18 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ FUNCTION(hex, 1, 0, 0, hexFunc ), FUNCTION(unhex, 1, 0, 0, unhexFunc ), FUNCTION(unhex, 2, 0, 0, unhexFunc ), - FUNCTION(concat, -1, 0, 0, concatFunc ), - FUNCTION(concat, 0, 0, 0, 0 ), - FUNCTION(concat_ws, -1, 0, 0, concatwsFunc ), - FUNCTION(concat_ws, 0, 0, 0, 0 ), - FUNCTION(concat_ws, 1, 0, 0, 0 ), + FUNCTION(concat, -3, 0, 0, concatFunc ), + FUNCTION(concat_ws, -4, 0, 0, concatwsFunc ), INLINE_FUNC(ifnull, 2, INLINEFUNC_coalesce, 0 ), VFUNCTION(random, 0, 0, 0, randomFunc ), VFUNCTION(randomblob, 1, 0, 0, randomBlob ), FUNCTION(nullif, 2, 0, 1, nullifFunc ), DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ), DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ), - FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ), + SFUNCTION(sqlite_log, 2, 0, 0, errlogFunc ), + FUNCTION(unistr, 1, 0, 0, unistrFunc ), FUNCTION(quote, 1, 0, 0, quoteFunc ), + FUNCTION(unistr_quote, 1, 1, 0, quoteFunc ), VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid), VFUNCTION(changes, 0, 0, 0, changes ), VFUNCTION(total_changes, 0, 0, 0, total_changes ), @@ -132075,6 +137744,21 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ WAGGREGATE(string_agg, 2, 0, 0, groupConcatStep, groupConcatFinalize, groupConcatValue, groupConcatInverse, 0), +#ifdef SQLITE_ENABLE_PERCENTILE + WAGGREGATE(median, 1, 0,0, percentStep, + percentFinal, percentValue, percentInverse, + SQLITE_INNOCUOUS|SQLITE_SELFORDER1), + WAGGREGATE(percentile, 2, 0x2,0, percentStep, + percentFinal, percentValue, percentInverse, + SQLITE_INNOCUOUS|SQLITE_SELFORDER1), + WAGGREGATE(percentile_cont, 2, 0,0, percentStep, + percentFinal, percentValue, percentInverse, + SQLITE_INNOCUOUS|SQLITE_SELFORDER1), + WAGGREGATE(percentile_disc, 2, 0x1,0, percentStep, + percentFinal, percentValue, percentInverse, + SQLITE_INNOCUOUS|SQLITE_SELFORDER1), +#endif /* SQLITE_ENABLE_PERCENTILE */ + LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), #ifdef SQLITE_CASE_SENSITIVE_LIKE LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), @@ -132086,8 +137770,6 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION FUNCTION(unknown, -1, 0, 0, unknownFunc ), #endif - FUNCTION(coalesce, 1, 0, 0, 0 ), - FUNCTION(coalesce, 0, 0, 0, 0 ), #ifdef SQLITE_ENABLE_MATH_FUNCTIONS MFUNCTION(ceil, 1, xCeil, ceilingFunc ), MFUNCTION(ceiling, 1, xCeil, ceilingFunc ), @@ -132125,8 +137807,9 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){ MFUNCTION(pi, 0, 0, piFunc ), #endif /* SQLITE_ENABLE_MATH_FUNCTIONS */ FUNCTION(sign, 1, 0, 0, signFunc ), - INLINE_FUNC(coalesce, -1, INLINEFUNC_coalesce, 0 ), - INLINE_FUNC(iif, 3, INLINEFUNC_iif, 0 ), + INLINE_FUNC(coalesce, -4, INLINEFUNC_coalesce, 0 ), + INLINE_FUNC(iif, -4, INLINEFUNC_iif, 0 ), + INLINE_FUNC(if, -4, INLINEFUNC_iif, 0 ), }; #ifndef SQLITE_OMIT_ALTERTABLE sqlite3AlterFunctions(); @@ -132846,6 +138529,7 @@ SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){ static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){ if( p ){ TriggerStep *pStep = p->step_list; + sqlite3SrcListDelete(dbMem, pStep->pSrc); sqlite3ExprDelete(dbMem, pStep->pWhere); sqlite3ExprListDelete(dbMem, pStep->pExprList); sqlite3SelectDelete(dbMem, pStep->pSelect); @@ -133065,6 +138749,7 @@ SQLITE_PRIVATE void sqlite3FkCheck( if( !IsOrdinaryTable(pTab) ) return; iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + assert( iDb>=00 && iDb<db->nDb ); zDb = db->aDb[iDb].zDbSName; /* Loop through all the foreign key constraints for which pTab is the @@ -133462,7 +139147,7 @@ static Trigger *fkActionTrigger( testcase( pCol->colFlags & COLFLAG_STORED ); pDflt = 0; }else{ - pDflt = sqlite3ColumnExpr(pFKey->pFrom, pCol); + pDflt = sqlite3ColumnExprAuth(pFKey->pFrom, pCol, pParse); } if( pDflt ){ pNew = sqlite3ExprDup(db, pDflt, 0); @@ -133482,7 +139167,6 @@ static Trigger *fkActionTrigger( nFrom = sqlite3Strlen30(zFrom); if( action==OE_Restrict ){ - int iDb = sqlite3SchemaToIndex(db, pTab->pSchema); SrcList *pSrc; Expr *pRaise; @@ -133493,10 +139177,10 @@ static Trigger *fkActionTrigger( } pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); if( pSrc ){ - assert( pSrc->nSrc==1 ); - pSrc->a[0].zName = sqlite3DbStrDup(db, zFrom); - assert( pSrc->a[0].fg.fixedSchema==0 && pSrc->a[0].fg.isSubquery==0 ); - pSrc->a[0].u4.zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName); + SrcItem *pItem = &pSrc->a[0]; + pItem->zName = sqlite3DbStrDup(db, zFrom); + pItem->fg.fixedSchema = 1; + pItem->u4.pSchema = pTab->pSchema; } pSelect = sqlite3SelectNew(pParse, sqlite3ExprListAppend(pParse, 0, pRaise), @@ -133512,14 +139196,17 @@ static Trigger *fkActionTrigger( pTrigger = (Trigger *)sqlite3DbMallocZero(db, sizeof(Trigger) + /* struct Trigger */ - sizeof(TriggerStep) + /* Single step in trigger program */ - nFrom + 1 /* Space for pStep->zTarget */ + sizeof(TriggerStep) /* Single step in trigger program */ ); if( pTrigger ){ pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1]; - pStep->zTarget = (char *)&pStep[1]; - memcpy((char *)pStep->zTarget, zFrom, nFrom); - + pStep->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); + if( pStep->pSrc ){ + SrcItem *pItem = &pStep->pSrc->a[0]; + pItem->zName = sqlite3DbStrNDup(db, zFrom, nFrom); + pItem->u4.pSchema = pTab->pSchema; + pItem->fg.fixedSchema = 1; + } pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE); pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); @@ -133830,12 +139517,15 @@ SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){ ** by one slot and insert a new OP_TypeCheck where the current ** OP_MakeRecord is found */ VdbeOp *pPrev; + int p3; sqlite3VdbeAppendP4(v, pTab, P4_TABLE); pPrev = sqlite3VdbeGetLastOp(v); assert( pPrev!=0 ); assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed ); pPrev->opcode = OP_TypeCheck; - sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, pPrev->p3); + p3 = pPrev->p3; + pPrev->p3 = 0; + sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, p3); }else{ /* Insert an isolated OP_Typecheck */ sqlite3VdbeAddOp2(v, OP_TypeCheck, iReg, pTab->nNVCol); @@ -134075,6 +139765,9 @@ static int autoIncBegin( return 0; } + if( pToplevel->usesAinc==0 ){ + pToplevel->pAinc = 0; + } pInfo = pToplevel->pAinc; while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; } if( pInfo==0 ){ @@ -134084,6 +139777,7 @@ static int autoIncBegin( if( pParse->db->mallocFailed ) return 0; pInfo->pNext = pToplevel->pAinc; pToplevel->pAinc = pInfo; + pToplevel->usesAinc = 1; pInfo->pTab = pTab; pInfo->iDb = iDb; pToplevel->nMem++; /* Register to hold name of table */ @@ -134112,6 +139806,7 @@ SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){ assert( sqlite3IsToplevel(pParse) ); assert( v ); /* We failed long ago if this is not so */ + assert( pParse->usesAinc ); for(p = pParse->pAinc; p; p = p->pNext){ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList autoInc[] = { @@ -134179,6 +139874,7 @@ static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){ sqlite3 *db = pParse->db; assert( v ); + assert( pParse->usesAinc ); for(p = pParse->pAinc; p; p = p->pNext){ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList autoIncEnd[] = { @@ -134211,7 +139907,7 @@ static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){ } } SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){ - if( pParse->pAinc ) autoIncrementEnd(pParse); + if( pParse->usesAinc ) autoIncrementEnd(pParse); } #else /* @@ -134238,25 +139934,13 @@ SQLITE_PRIVATE void sqlite3MultiValuesEnd(Parse *pParse, Select *pVal){ } } -/* -** Return true if all expressions in the expression-list passed as the -** only argument are constant. -*/ -static int exprListIsConstant(Parse *pParse, ExprList *pRow){ - int ii; - for(ii=0; ii<pRow->nExpr; ii++){ - if( 0==sqlite3ExprIsConstant(pParse, pRow->a[ii].pExpr) ) return 0; - } - return 1; -} - /* ** Return true if all expressions in the expression-list passed as the ** only argument are both constant and have no affinity. */ static int exprListIsNoAffinity(Parse *pParse, ExprList *pRow){ int ii; - if( exprListIsConstant(pParse,pRow)==0 ) return 0; + if( sqlite3ExprListIsConstant(pParse, pRow, 0)==0 ) return 0; for(ii=0; ii<pRow->nExpr; ii++){ Expr *pExpr = pRow->a[ii].pExpr; assert( pExpr->op!=TK_RAISE ); @@ -134322,7 +140006,7 @@ SQLITE_PRIVATE Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList if( pParse->bHasWith /* condition (a) above */ || pParse->db->init.busy /* condition (b) above */ - || exprListIsConstant(pParse,pRow)==0 /* condition (c) above */ + || sqlite3ExprListIsConstant(pParse, pRow, 1)==0 /* condition (c) above */ || (pLeft->pSrc->nSrc==0 && exprListIsNoAffinity(pParse,pLeft->pEList)==0) /* condition (d) above */ || IN_SPECIAL_PARSE @@ -134338,7 +140022,7 @@ SQLITE_PRIVATE Select *sqlite3MultiValues(Parse *pParse, Select *pLeft, ExprList f = (f & pLeft->selFlags); } pSelect = sqlite3SelectNew(pParse, pRow, 0, 0, 0, 0, 0, f, 0); - pLeft->selFlags &= ~SF_MultiValue; + pLeft->selFlags &= ~(u32)SF_MultiValue; if( pSelect ){ pSelect->op = TK_ALL; pSelect->pPrior = pLeft; @@ -134572,6 +140256,7 @@ SQLITE_PRIVATE void sqlite3Insert( int regRowid; /* registers holding insert rowid */ int regData; /* register holding first column to insert */ int *aRegIdx = 0; /* One register allocated to each index */ + int *aTabColMap = 0; /* Mapping from pTab columns to pCol entries */ #ifndef SQLITE_OMIT_TRIGGER int isView; /* True if attempting to insert into a view */ @@ -134716,31 +140401,25 @@ SQLITE_PRIVATE void sqlite3Insert( */ bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0; if( pColumn ){ - assert( pColumn->eU4!=EU4_EXPR ); - pColumn->eU4 = EU4_IDX; - for(i=0; i<pColumn->nId; i++){ - pColumn->a[i].u4.idx = -1; - } + aTabColMap = sqlite3DbMallocZero(db, pTab->nCol*sizeof(int)); + if( aTabColMap==0 ) goto insert_cleanup; for(i=0; i<pColumn->nId; i++){ - for(j=0; j<pTab->nCol; j++){ - if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zCnName)==0 ){ - pColumn->a[i].u4.idx = j; - if( i!=j ) bIdListInOrder = 0; - if( j==pTab->iPKey ){ - ipkColumn = i; assert( !withoutRowid ); - } + j = sqlite3ColumnIndex(pTab, pColumn->a[i].zName); + if( j>=0 ){ + if( aTabColMap[j]==0 ) aTabColMap[j] = i+1; + if( i!=j ) bIdListInOrder = 0; + if( j==pTab->iPKey ){ + ipkColumn = i; assert( !withoutRowid ); + } #ifndef SQLITE_OMIT_GENERATED_COLUMNS - if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){ - sqlite3ErrorMsg(pParse, - "cannot INSERT into generated column \"%s\"", - pTab->aCol[j].zCnName); - goto insert_cleanup; - } -#endif - break; + if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){ + sqlite3ErrorMsg(pParse, + "cannot INSERT into generated column \"%s\"", + pTab->aCol[j].zCnName); + goto insert_cleanup; } - } - if( j>=pTab->nCol ){ +#endif + }else{ if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){ ipkColumn = i; bIdListInOrder = 0; @@ -135038,29 +140717,29 @@ SQLITE_PRIVATE void sqlite3Insert( continue; }else if( pColumn==0 ){ /* Hidden columns that are not explicitly named in the INSERT - ** get there default value */ + ** get their default value */ sqlite3ExprCodeFactorable(pParse, - sqlite3ColumnExpr(pTab, &pTab->aCol[i]), + sqlite3ColumnExprAuth(pTab, &pTab->aCol[i], pParse), iRegStore); continue; } } if( pColumn ){ - assert( pColumn->eU4==EU4_IDX ); - for(j=0; j<pColumn->nId && pColumn->a[j].u4.idx!=i; j++){} - if( j>=pColumn->nId ){ + j = aTabColMap[i]; + assert( j>=0 && j<=pColumn->nId ); + if( j==0 ){ /* A column not named in the insert column list gets its ** default value */ sqlite3ExprCodeFactorable(pParse, - sqlite3ColumnExpr(pTab, &pTab->aCol[i]), + sqlite3ColumnExprAuth(pTab, &pTab->aCol[i], pParse), iRegStore); continue; } - k = j; + k = j - 1; }else if( nColumn==0 ){ /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */ sqlite3ExprCodeFactorable(pParse, - sqlite3ColumnExpr(pTab, &pTab->aCol[i]), + sqlite3ColumnExprAuth(pTab, &pTab->aCol[i], pParse), iRegStore); continue; }else{ @@ -135111,6 +140790,7 @@ SQLITE_PRIVATE void sqlite3Insert( sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols); sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v); + sqlite3MayAbort(pParse); } /* Copy the new data already generated. */ @@ -135179,6 +140859,7 @@ SQLITE_PRIVATE void sqlite3Insert( sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v); } sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v); + sqlite3MayAbort(pParse); } }else if( IsVirtual(pTab) || withoutRowid ){ sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); @@ -135301,7 +140982,10 @@ SQLITE_PRIVATE void sqlite3Insert( sqlite3ExprListDelete(db, pList); sqlite3UpsertDelete(db, pUpsert); sqlite3SelectDelete(db, pSelect); - sqlite3IdListDelete(db, pColumn); + if( pColumn ){ + sqlite3IdListDelete(db, pColumn); + sqlite3DbFree(db, aTabColMap); + } if( aRegIdx ) sqlite3DbNNFreeNN(db, aRegIdx); } @@ -135655,7 +141339,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( assert( (pCol->colFlags & COLFLAG_GENERATED)==0 ); nSeenReplace++; sqlite3ExprCodeCopy(pParse, - sqlite3ColumnExpr(pTab, pCol), iReg); + sqlite3ColumnExprAuth(pTab, pCol, pParse), iReg); sqlite3VdbeJumpHere(v, addr1); break; } @@ -135760,7 +141444,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( ** could happen in any order, but they are grouped up front for ** convenience. ** - ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43 + ** 2018-08-14: Ticket https://sqlite.org/src/info/908f001483982c43 ** The order of constraints used to have OE_Update as (2) and OE_Abort ** and so forth as (1). But apparently PostgreSQL checks the OE_Update ** constraint before any others, so it had to be moved. @@ -135868,6 +141552,22 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( pTrigger = 0; regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0); } + if( regTrigCnt ){ + /* At this point regTrigCnt is non-zero if there are DELETE triggers + ** or FK triggers. But we only care about these things if there is + ** a chance that a row will be deleted by an ON CONFLICT REPLACE + ** constraint. So zero regTrigCnt if no such constraint can be found. */ + if( overrideError!=OE_Replace ){ + if( overrideError!=OE_Default ){ + regTrigCnt = 0; + }else if( pkChng==0 || pPk || pTab->keyConf!=OE_Replace ){ + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + if( pIdx->onError==OE_Replace ) break; + } + if( pIdx==0 ) regTrigCnt = 0; + } + } + } if( regTrigCnt ){ /* Replace triggers might exist. Allocate the counter and ** initialize it to zero. */ @@ -135919,9 +141619,13 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( if( onError==OE_Replace /* IPK rule is REPLACE */ && onError!=overrideError /* Rules for other constraints are different */ && pTab->pIndex /* There exist other constraints */ - && !upsertIpkDelay /* IPK check already deferred by UPSERT */ ){ - ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1; + if( upsertIpkDelay ){ + ipkTop = upsertIpkDelay + 1; + upsertIpkDelay = 0; + }else{ + ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1; + } VdbeComment((v, "defer IPK REPLACE until last")); } @@ -136015,11 +141719,11 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( } } sqlite3VdbeResolveLabel(v, addrRowidOk); - if( pUpsert && pUpsertClause!=pUpsert ){ - upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto); - }else if( ipkTop ){ + if( ipkTop ){ ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); sqlite3VdbeJumpHere(v, ipkTop-1); + }else if( pUpsert && pUpsertClause!=pUpsert ){ + upsertIpkReturn = sqlite3VdbeAddOp0(v, OP_Goto); } } @@ -136039,6 +141743,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( int iThisCur; /* Cursor for this UNIQUE index */ int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */ int addrConflictCk; /* First opcode in the conflict check logic */ + int nConflictCk; /* Number of opcodes in conflict check logic */ if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ if( pUpsert ){ @@ -136215,6 +141920,11 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( } } + nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk; + assert( nConflictCk>0 || db->mallocFailed ); + testcase( nConflictCk<=0 ); + testcase( nConflictCk>1 ); + /* Generate code that executes if the new index entry is not unique */ assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update ); @@ -136240,13 +141950,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( break; } default: { - int nConflictCk; /* Number of opcodes in conflict check logic */ - assert( onError==OE_Replace ); - nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk; - assert( nConflictCk>0 || db->mallocFailed ); - testcase( nConflictCk<=0 ); - testcase( nConflictCk>1 ); if( regTrigCnt ){ sqlite3MultiWrite(pParse); nReplaceTrig++; @@ -136260,57 +141964,57 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( if( pTrigger && isUpdate ){ sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur); } - if( regTrigCnt ){ - int addrBypass; /* Jump destination to bypass recheck logic */ + seenReplace = 1; + break; + } + } + if( regTrigCnt ){ + int addrBypass; /* Jump destination to bypass recheck logic */ - sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */ - addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */ - VdbeComment((v, "bypass recheck")); - - /* Here we insert code that will be invoked after all constraint - ** checks have run, if and only if one or more replace triggers - ** fired. */ - sqlite3VdbeResolveLabel(v, lblRecheckOk); - lblRecheckOk = sqlite3VdbeMakeLabel(pParse); - if( pIdx->pPartIdxWhere ){ - /* Bypass the recheck if this partial index is not defined - ** for the current row */ - sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk); - VdbeCoverage(v); - } - /* Copy the constraint check code from above, except change - ** the constraint-ok jump destination to be the address of - ** the next retest block */ - while( nConflictCk>0 ){ - VdbeOp x; /* Conflict check opcode to copy */ - /* The sqlite3VdbeAddOp4() call might reallocate the opcode array. - ** Hence, make a complete copy of the opcode, rather than using - ** a pointer to the opcode. */ - x = *sqlite3VdbeGetOp(v, addrConflictCk); - if( x.opcode!=OP_IdxRowid ){ - int p2; /* New P2 value for copied conflict check opcode */ - const char *zP4; - if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){ - p2 = lblRecheckOk; - }else{ - p2 = x.p2; - } - zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z; - sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type); - sqlite3VdbeChangeP5(v, x.p5); - VdbeCoverageIf(v, p2!=x.p2); - } - nConflictCk--; - addrConflictCk++; - } - /* If the retest fails, issue an abort */ - sqlite3UniqueConstraint(pParse, OE_Abort, pIdx); + sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */ + addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */ + VdbeComment((v, "bypass recheck")); - sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */ + /* Here we insert code that will be invoked after all constraint + ** checks have run, if and only if one or more replace triggers + ** fired. */ + sqlite3VdbeResolveLabel(v, lblRecheckOk); + lblRecheckOk = sqlite3VdbeMakeLabel(pParse); + if( pIdx->pPartIdxWhere ){ + /* Bypass the recheck if this partial index is not defined + ** for the current row */ + sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk); + VdbeCoverage(v); + } + /* Copy the constraint check code from above, except change + ** the constraint-ok jump destination to be the address of + ** the next retest block */ + while( nConflictCk>0 ){ + VdbeOp x; /* Conflict check opcode to copy */ + /* The sqlite3VdbeAddOp4() call might reallocate the opcode array. + ** Hence, make a complete copy of the opcode, rather than using + ** a pointer to the opcode. */ + x = *sqlite3VdbeGetOp(v, addrConflictCk); + if( x.opcode!=OP_IdxRowid || isUpdate ){ + int p2; /* New P2 value for copied conflict check opcode */ + const char *zP4; + if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){ + p2 = lblRecheckOk; + }else{ + p2 = x.p2; + } + zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z; + sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type); + sqlite3VdbeChangeP5(v, x.p5); + VdbeCoverageIf(v, p2!=x.p2); } - seenReplace = 1; - break; + nConflictCk--; + addrConflictCk++; } + /* If the retest fails, issue an abort */ + sqlite3UniqueConstraint(pParse, OE_Abort, pIdx); + + sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */ } sqlite3VdbeResolveLabel(v, addrUniqueOk); if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); @@ -136349,8 +142053,8 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( }else{ sqlite3VdbeGoto(v, addrRecheck); } - sqlite3VdbeResolveLabel(v, lblRecheckOk); } + if( regTrigCnt ) sqlite3VdbeResolveLabel(v, lblRecheckOk); /* Generate the table record */ if( HasRowid(pTab) ){ @@ -136453,7 +142157,10 @@ SQLITE_PRIVATE void sqlite3CompleteInsertion( || pIdx->pNext==0 || pIdx->pNext->onError==OE_Replace ); if( aRegIdx[i]==0 ) continue; - if( pIdx->pPartIdxWhere ){ + if( pIdx->pPartIdxWhere || (update_flags && pIdx->bHasExpr) ){ + /* If this is a partial index, or an UPDATE of an index on an + ** expression, then the record register may be set to NULL to indicate + ** that no record should be inserted into this index. */ sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2); VdbeCoverage(v); } @@ -136628,6 +142335,44 @@ static int xferCompatibleIndex(Index *pDest, Index *pSrc){ return 1; } +/* +** Examine an expression node and abort if it references the ROWID. +** This is a Walker callback used by xferCompatibleCheck() +*/ +static int xferCheckRowid(Walker *pWalk, Expr *pExpr){ + if( pExpr->op==TK_COLUMN && pExpr->iColumn<0 ){ + pWalk->eCode = 1; + return WRC_Abort; + }else{ + return WRC_Continue; + } +} + +/* +** Analyze CHECK constraints on the source and destination tables and +** return true if those CHECK constraints are compatible with the +** xfer-optimization. +** +** * The pDest and pSrc tables must have identical CHECK constraints. +** +** * If the destination table, pDest, does not have an +** INTEGER PRIMARY KEY column, then no CHECK constraint may +** referenced the ROWID. (See forum post 2026-05-11T13:15:57Z) +*/ +static int xferCompatibleCheck(Table *pDest, Table *pSrc){ + if( sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){ + return 0; + } + if( pDest->iPKey<0 ){ + Walker w; + memset(&w, 0, sizeof(w)); + w.xExprCallback = xferCheckRowid; + sqlite3WalkExprList(&w,pDest->pCheck); + if( w.eCode ) return 0; + } + return 1; +} + /* ** Attempt the transfer optimization on INSERTs of the form ** @@ -136754,8 +142499,19 @@ static int xferOptimization( if( pDest->iPKey!=pSrc->iPKey ){ return 0; /* Both tables must have the same INTEGER PRIMARY KEY */ } - if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){ - return 0; /* Cannot feed from a non-strict into a strict table */ + if( (pDest->tabFlags & TF_Strict)!=0 ){ + if( (pSrc->tabFlags & TF_Strict)==0 ){ + return 0; /* Cannot feed from a non-strict into a strict table */ + } + for(i=0; i<pDest->nCol; i++){ + unsigned eDestType = pDest->aCol[i].eCType; + unsigned eSrcType = pSrc->aCol[i].eCType; + if( eDestType==COLTYPE_ANY ) continue; + if( eDestType==eSrcType ) continue; + if( eDestType==COLTYPE_INT && eSrcType==COLTYPE_INTEGER ) continue; + if( eDestType==COLTYPE_INTEGER && eSrcType==COLTYPE_INT ) continue; + return 0; /* Incompatible types in source and destination */ + } } for(i=0; i<pDest->nCol; i++){ Column *pDestCol = &pDest->aCol[i]; @@ -136849,7 +142605,7 @@ static int xferOptimization( #ifndef SQLITE_OMIT_CHECK if( pDest->pCheck && (db->mDbFlags & DBFLAG_Vacuum)==0 - && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) + && !xferCompatibleCheck(pDest,pSrc) ){ return 0; /* Tables have different CHECK constraints. Ticket #2252 */ } @@ -136870,6 +142626,18 @@ static int xferOptimization( if( (db->flags & SQLITE_CountRows)!=0 ){ return 0; /* xfer opt does not play well with PRAGMA count_changes */ } +#ifndef SQLITE_OMIT_AUTHORIZATION + if( db->xAuth ){ + int iDb = sqlite3SchemaToIndex(db, pSrc->pSchema); + if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 0; + for(i=0; i<pSrc->nCol; i++){ + Column *pSrcCol = &pSrc->aCol[i]; + if( sqlite3AuthReadCol(pParse, pSrc->zName, pSrcCol->zCnName, iDb) ){ + return 0; + } + } + } +#endif /* If we get this far, it means that the xfer optimization is at ** least a possibility, though it might only work if the destination @@ -137313,7 +143081,7 @@ struct sqlite3_api_routines { const char * (*libversion)(void); int (*libversion_number)(void); void *(*malloc)(int); - char * (*mprintf)(const char*,...); + char *(SQLITE_CDECL*mprintf)(const char*,...); int (*open)(const char*,sqlite3**); int (*open16)(const void*,sqlite3**); int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); @@ -137334,11 +143102,11 @@ struct sqlite3_api_routines { void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_value)(sqlite3_context*,sqlite3_value*); - void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); + void *(*rollback_hook)(sqlite3*,void(*)(void*),void*); int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*, const char*,const char*),void*); void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); - char * (*xsnprintf)(int,char*,const char*,...); + char *(SQLITE_CDECL*xsnprintf)(int,char*,const char*,...); int (*step)(sqlite3_stmt*); int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*, char const**,char const**,int*,int*,int*); @@ -137402,7 +143170,7 @@ struct sqlite3_api_routines { int (*xthreadsafe)(void); void (*result_zeroblob)(sqlite3_context*,int); void (*result_error_code)(sqlite3_context*,int); - int (*test_control)(int, ...); + int (SQLITE_CDECL*test_control)(int, ...); void (*randomness)(int,void*); sqlite3 *(*context_db_handle)(sqlite3_context*); int (*extended_result_codes)(sqlite3*,int); @@ -137422,11 +143190,11 @@ struct sqlite3_api_routines { void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*), void(*xDestroy)(void*)); - int (*db_config)(sqlite3*,int,...); + int (SQLITE_CDECL*db_config)(sqlite3*,int,...); sqlite3_mutex *(*db_mutex)(sqlite3*); int (*db_status)(sqlite3*,int,int*,int*,int); int (*extended_errcode)(sqlite3*); - void (*log)(int,const char*,...); + void (SQLITE_CDECL*log)(int,const char*,...); sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); const char *(*sourceid)(void); int (*stmt_status)(sqlite3_stmt*,int,int); @@ -137436,7 +143204,7 @@ struct sqlite3_api_routines { int (*wal_checkpoint)(sqlite3*,const char*); void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); int (*blob_reopen)(sqlite3_blob*,sqlite3_int64); - int (*vtab_config)(sqlite3*,int op,...); + int (SQLITE_CDECL*vtab_config)(sqlite3*,int op,...); int (*vtab_on_conflict)(sqlite3*); /* Version 3.7.16 and later */ int (*close_v2)(sqlite3*); @@ -137505,7 +143273,7 @@ struct sqlite3_api_routines { int (*keyword_check)(const char*,int); sqlite3_str *(*str_new)(sqlite3*); char *(*str_finish)(sqlite3_str*); - void (*str_appendf)(sqlite3_str*, const char *zFormat, ...); + void (SQLITE_CDECL*str_appendf)(sqlite3_str*, const char *zFormat, ...); void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list); void (*str_append)(sqlite3_str*, const char *zIn, int N); void (*str_appendall)(sqlite3_str*, const char *zIn); @@ -137570,6 +143338,19 @@ struct sqlite3_api_routines { /* Version 3.44.0 and later */ void *(*get_clientdata)(sqlite3*,const char*); int (*set_clientdata)(sqlite3*, const char*, void*, void(*)(void*)); + /* Version 3.50.0 and later */ + int (*setlk_timeout)(sqlite3*,int,int); + /* Version 3.51.0 and later */ + int (*set_errmsg)(sqlite3*,int,const char*); + int (*db_status64)(sqlite3*,int,sqlite3_int64*,sqlite3_int64*,int); + /* Version 3.52.0 and later */ + void (*str_truncate)(sqlite3_str*,int); + void (*str_free)(sqlite3_str*); + int (*carray_bind)(sqlite3_stmt*,int,void*,int,int,void(*)(void*)); + int (*carray_bind_v2)(sqlite3_stmt*,int,void*,int,int,void(*)(void*),void*); + /* Version 3.54.0 and later */ + sqlite3_int64 (*incomplete)(const char*); + void (*result_str)(sqlite3_context*,sqlite3_str*,int); }; /* @@ -137903,6 +143684,19 @@ typedef int (*sqlite3_loadext_entry)( /* Version 3.44.0 and later */ #define sqlite3_get_clientdata sqlite3_api->get_clientdata #define sqlite3_set_clientdata sqlite3_api->set_clientdata +/* Version 3.50.0 and later */ +#define sqlite3_setlk_timeout sqlite3_api->setlk_timeout +/* Version 3.51.0 and later */ +#define sqlite3_set_errmsg sqlite3_api->set_errmsg +#define sqlite3_db_status64 sqlite3_api->db_status64 +/* Version 3.52.0 and later */ +#define sqlite3_str_truncate sqlite3_api->str_truncate +#define sqlite3_str_free sqlite3_api->str_free +#define sqlite3_carray_bind sqlite3_api->carray_bind +#define sqlite3_carray_bind_v2 sqlite3_api->carray_bind_v2 +/* Version 3.54.0 and later */ +#define sqlite3_incomplete sqlite3_api->incomplete +#define sqlite3_result_str sqlite3_api->result_str #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) @@ -138424,7 +144218,25 @@ static const sqlite3_api_routines sqlite3Apis = { sqlite3_stmt_explain, /* Version 3.44.0 and later */ sqlite3_get_clientdata, - sqlite3_set_clientdata + sqlite3_set_clientdata, + /* Version 3.50.0 and later */ + sqlite3_setlk_timeout, + /* Version 3.51.0 and later */ + sqlite3_set_errmsg, + sqlite3_db_status64, + /* Version 3.52.0 and later */ + sqlite3_str_truncate, + sqlite3_str_free, +#ifdef SQLITE_ENABLE_CARRAY + sqlite3_carray_bind, + sqlite3_carray_bind_v2, +#else + 0, + 0, +#endif + /* Version 3.54.0 and later */ + sqlite3_incomplete, + sqlite3_result_str }; /* True if x is the directory separator character @@ -138526,33 +144338,42 @@ static int sqlite3LoadExtension( ** entry point name "sqlite3_extension_init" was not found, then ** construct an entry point name "sqlite3_X_init" where the X is ** replaced by the lowercase value of every ASCII alphabetic - ** character in the filename after the last "/" upto the first ".", - ** and eliding the first three characters if they are "lib". + ** character in the filename after the last "/" up to the first ".", + ** and skipping the first three characters if they are "lib". ** Examples: ** ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init + ** + ** If that still finds no entry point, repeat a second time but this + ** time include both alphabetic and numeric characters up to the first + ** ".". Example: + ** + ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example5_init */ if( xInit==0 && zProc==0 ){ int iFile, iEntry, c; int ncFile = sqlite3Strlen30(zFile); + int cnt = 0; zAltEntry = sqlite3_malloc64(ncFile+30); if( zAltEntry==0 ){ sqlite3OsDlClose(pVfs, handle); return SQLITE_NOMEM_BKPT; } - memcpy(zAltEntry, "sqlite3_", 8); - for(iFile=ncFile-1; iFile>=0 && !DirSep(zFile[iFile]); iFile--){} - iFile++; - if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3; - for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){ - if( sqlite3Isalpha(c) ){ - zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c]; + do{ + memcpy(zAltEntry, "sqlite3_", 8); + for(iFile=ncFile-1; iFile>=0 && !DirSep(zFile[iFile]); iFile--){} + iFile++; + if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3; + for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){ + if( sqlite3Isalpha(c) || (cnt && sqlite3Isdigit(c)) ){ + zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c]; + } } - } - memcpy(zAltEntry+iEntry, "_init", 6); - zEntry = zAltEntry; - xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry); + memcpy(zAltEntry+iEntry, "_init", 6); + zEntry = zAltEntry; + xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry); + }while( xInit==0 && (++cnt)<2 ); } if( xInit==0 ){ if( pzErrMsg ){ @@ -138946,48 +144767,48 @@ static const char *const pragCName[] = { /* 13 */ "pk", /* 14 */ "hidden", /* table_info reuses 8 */ - /* 15 */ "schema", /* Used by: table_list */ - /* 16 */ "name", + /* 15 */ "name", /* Used by: function_list */ + /* 16 */ "builtin", /* 17 */ "type", - /* 18 */ "ncol", - /* 19 */ "wr", - /* 20 */ "strict", - /* 21 */ "seqno", /* Used by: index_xinfo */ - /* 22 */ "cid", - /* 23 */ "name", - /* 24 */ "desc", - /* 25 */ "coll", - /* 26 */ "key", - /* 27 */ "name", /* Used by: function_list */ - /* 28 */ "builtin", - /* 29 */ "type", - /* 30 */ "enc", - /* 31 */ "narg", - /* 32 */ "flags", - /* 33 */ "tbl", /* Used by: stats */ - /* 34 */ "idx", - /* 35 */ "wdth", - /* 36 */ "hght", - /* 37 */ "flgs", - /* 38 */ "seq", /* Used by: index_list */ - /* 39 */ "name", - /* 40 */ "unique", - /* 41 */ "origin", - /* 42 */ "partial", + /* 18 */ "enc", + /* 19 */ "narg", + /* 20 */ "flags", + /* 21 */ "schema", /* Used by: table_list */ + /* 22 */ "name", + /* 23 */ "type", + /* 24 */ "ncol", + /* 25 */ "wr", + /* 26 */ "strict", + /* 27 */ "seqno", /* Used by: index_xinfo */ + /* 28 */ "cid", + /* 29 */ "name", + /* 30 */ "desc", + /* 31 */ "coll", + /* 32 */ "key", + /* 33 */ "seq", /* Used by: index_list */ + /* 34 */ "name", + /* 35 */ "unique", + /* 36 */ "origin", + /* 37 */ "partial", + /* 38 */ "tbl", /* Used by: stats */ + /* 39 */ "idx", + /* 40 */ "wdth", + /* 41 */ "hght", + /* 42 */ "flgs", /* 43 */ "table", /* Used by: foreign_key_check */ /* 44 */ "rowid", /* 45 */ "parent", /* 46 */ "fkid", - /* index_info reuses 21 */ - /* 47 */ "seq", /* Used by: database_list */ - /* 48 */ "name", - /* 49 */ "file", - /* 50 */ "busy", /* Used by: wal_checkpoint */ - /* 51 */ "log", - /* 52 */ "checkpointed", - /* collation_list reuses 38 */ + /* 47 */ "busy", /* Used by: wal_checkpoint */ + /* 48 */ "log", + /* 49 */ "checkpointed", + /* 50 */ "seq", /* Used by: database_list */ + /* 51 */ "name", + /* 52 */ "file", + /* index_info reuses 27 */ /* 53 */ "database", /* Used by: lock_status */ /* 54 */ "status", + /* collation_list reuses 33 */ /* 55 */ "cache_size", /* Used by: default_cache_size */ /* module_list pragma_list reuses 9 */ /* 56 */ "timeout", /* Used by: busy_timeout */ @@ -139080,7 +144901,7 @@ static const PragmaName aPragmaName[] = { {/* zName: */ "collation_list", /* ePragTyp: */ PragTyp_COLLATION_LIST, /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 38, 2, + /* ColNames: */ 33, 2, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS) @@ -139097,7 +144918,7 @@ static const PragmaName aPragmaName[] = { /* ColNames: */ 0, 0, /* iArg: */ SQLITE_CountRows }, #endif -#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && defined(_WIN32) {/* zName: */ "data_store_directory", /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY, /* ePragFlg: */ PragFlg_NoColumns1, @@ -139115,7 +144936,7 @@ static const PragmaName aPragmaName[] = { {/* zName: */ "database_list", /* ePragTyp: */ PragTyp_DATABASE_LIST, /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 47, 3, + /* ColNames: */ 50, 3, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) @@ -139195,7 +145016,7 @@ static const PragmaName aPragmaName[] = { {/* zName: */ "function_list", /* ePragTyp: */ PragTyp_FUNCTION_LIST, /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 27, 6, + /* ColNames: */ 15, 6, /* iArg: */ 0 }, #endif #endif @@ -139224,17 +145045,17 @@ static const PragmaName aPragmaName[] = { {/* zName: */ "index_info", /* ePragTyp: */ PragTyp_INDEX_INFO, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, - /* ColNames: */ 21, 3, + /* ColNames: */ 27, 3, /* iArg: */ 0 }, {/* zName: */ "index_list", /* ePragTyp: */ PragTyp_INDEX_LIST, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, - /* ColNames: */ 38, 5, + /* ColNames: */ 33, 5, /* iArg: */ 0 }, {/* zName: */ "index_xinfo", /* ePragTyp: */ PragTyp_INDEX_INFO, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, - /* ColNames: */ 21, 6, + /* ColNames: */ 27, 6, /* iArg: */ 1 }, #endif #if !defined(SQLITE_OMIT_INTEGRITY_CHECK) @@ -139413,7 +145234,7 @@ static const PragmaName aPragmaName[] = { {/* zName: */ "stats", /* ePragTyp: */ PragTyp_STATS, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq, - /* ColNames: */ 33, 5, + /* ColNames: */ 38, 5, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) @@ -139432,7 +145253,7 @@ static const PragmaName aPragmaName[] = { {/* zName: */ "table_list", /* ePragTyp: */ PragTyp_TABLE_LIST, /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1, - /* ColNames: */ 15, 6, + /* ColNames: */ 21, 6, /* iArg: */ 0 }, {/* zName: */ "table_xinfo", /* ePragTyp: */ PragTyp_TABLE_INFO, @@ -139509,7 +145330,7 @@ static const PragmaName aPragmaName[] = { {/* zName: */ "wal_checkpoint", /* ePragTyp: */ PragTyp_WAL_CHECKPOINT, /* ePragFlg: */ PragFlg_NeedSchema, - /* ColNames: */ 50, 3, + /* ColNames: */ 47, 3, /* iArg: */ 0 }, #endif #if !defined(SQLITE_OMIT_FLAG_PRAGMAS) @@ -139520,7 +145341,7 @@ static const PragmaName aPragmaName[] = { /* iArg: */ SQLITE_WriteSchema|SQLITE_NoSchemaError }, #endif }; -/* Number of pragmas: 68 on by default, 78 total. */ +/* Number of pragmas: 67 on by default, 78 total. */ /************** End of pragma.h **********************************************/ /************** Continuing where we left off in pragma.c *********************/ @@ -139531,7 +145352,7 @@ static const PragmaName aPragmaName[] = { ** the following macro or to the actual analysis_limit if it is non-zero, ** in order to prevent PRAGMA optimize from running for too long. ** -** The value of 2000 is chosen emperically so that the worst-case run-time +** The value of 2000 is chosen empirically so that the worst-case run-time ** for PRAGMA optimize does not exceed 100 milliseconds against a variety ** of test databases on a RaspberryPI-4 compiled using -Os and without ** -DSQLITE_DEBUG. Of course, your mileage may vary. For the purpose of @@ -139573,7 +145394,7 @@ static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){ /* on no off false yes true extra full */ int i, n; if( sqlite3Isdigit(*z) ){ - return (u8)sqlite3Atoi(z); + return sqlite3Atoi(z)!=0; } n = sqlite3Strlen30(z); for(i=0; i<ArraySize(iLength); i++){ @@ -139710,7 +145531,7 @@ static void setPragmaResultColumnNames( ** Generate code to return a single integer value. */ static void returnSingleInt(Vdbe *v, i64 value){ - sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64); + sqlite3VdbeAddInt64(v, 1, value); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } @@ -139886,6 +145707,22 @@ static int integrityCheckResultRow(Vdbe *v){ return addr; } +/* +** Should table pTab be skipped when doing an integrity_check? +** Return true or false. +** +** If pObjTab is not null, the return true if pTab matches pObjTab. +** +** If pObjTab is null, then return true only if pTab is an imposter table. +*/ +static int tableSkipIntegrityCheck(const Table *pTab, const Table *pObjTab){ + if( pObjTab ){ + return pTab!=pObjTab; + }else{ + return (pTab->tabFlags & TF_Imposter)!=0; + } +} + /* ** Process a pragma statement. ** @@ -140616,7 +146453,13 @@ SQLITE_PRIVATE void sqlite3Pragma( sqlite3ErrorMsg(pParse, "Safety level may not be changed inside a transaction"); }else if( iDb!=1 ){ - int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK; + int iLevel; + if( sqlite3Isdigit(zRight[0]) ){ + iLevel = sqlite3Atoi(zRight); + }else{ + iLevel = getSafetyLevel(zRight,0,1); + } + iLevel = (iLevel+1) & PAGER_SYNCHRONOUS_MASK; if( iLevel==0 ) iLevel = 1; pDb->safety_level = iLevel; pDb->bSyncSet = 1; @@ -140639,12 +146482,6 @@ SQLITE_PRIVATE void sqlite3Pragma( ** in auto-commit mode. */ mask &= ~(SQLITE_ForeignKeys); } -#if SQLITE_USER_AUTHENTICATION - if( db->auth.authLevel==UAUTH_User ){ - /* Do not allow non-admin users to modify the schema arbitrarily */ - mask &= ~(SQLITE_WriteSchema); - } -#endif if( sqlite3GetBoolean(zRight, 0) ){ if( (mask & SQLITE_WriteSchema)==0 @@ -140654,7 +146491,10 @@ SQLITE_PRIVATE void sqlite3Pragma( } }else{ db->flags &= ~mask; - if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0; + if( mask==SQLITE_DeferFKs ){ + db->nDeferredImmCons = 0; + db->nDeferredCons = 0; + } if( (mask & SQLITE_WriteSchema)!=0 && sqlite3_stricmp(zRight, "reset")==0 ){ @@ -140780,7 +146620,8 @@ SQLITE_PRIVATE void sqlite3Pragma( char *zSql = sqlite3MPrintf(db, "SELECT*FROM\"%w\"", pTab->zName); if( zSql ){ sqlite3_stmt *pDummy = 0; - (void)sqlite3_prepare(db, zSql, -1, &pDummy, 0); + (void)sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_DONT_LOG, + &pDummy, 0); (void)sqlite3_finalize(pDummy); sqlite3DbFree(db, zSql); } @@ -141232,10 +147073,9 @@ SQLITE_PRIVATE void sqlite3Pragma( for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); /* Current table */ Index *pIdx; /* An index on pTab */ - int nIdx; /* Number of indexes on pTab */ - if( pObjTab && pObjTab!=pTab ) continue; + if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue; if( HasRowid(pTab) ) cnt++; - for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; } + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ cnt++; } } if( cnt==0 ) continue; if( pObjTab ) cnt++; @@ -141246,7 +147086,7 @@ SQLITE_PRIVATE void sqlite3Pragma( for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx; - if( pObjTab && pObjTab!=pTab ) continue; + if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue; if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum; for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ aRoot[++cnt] = pIdx->tnum; @@ -141261,7 +147101,7 @@ SQLITE_PRIVATE void sqlite3Pragma( /* Do the b-tree integrity checks */ sqlite3VdbeAddOp4(v, OP_IntegrityCk, 1, cnt, 8, (char*)aRoot,P4_INTARRAY); - sqlite3VdbeChangeP5(v, (u8)i); + sqlite3VdbeChangeP5(v, (u16)i); addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName), @@ -141277,7 +147117,7 @@ SQLITE_PRIVATE void sqlite3Pragma( int iTab = 0; Table *pTab = sqliteHashData(x); Index *pIdx; - if( pObjTab && pObjTab!=pTab ) continue; + if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue; if( HasRowid(pTab) ){ iTab = cnt++; }else{ @@ -141313,7 +147153,7 @@ SQLITE_PRIVATE void sqlite3Pragma( int r2; /* Previous key for WITHOUT ROWID tables */ int mxCol; /* Maximum non-virtual column number */ - if( pObjTab && pObjTab!=pTab ) continue; + if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue; if( !IsOrdinaryTable(pTab) ) continue; if( isQuick || HasRowid(pTab) ){ pPk = 0; @@ -141415,8 +147255,8 @@ SQLITE_PRIVATE void sqlite3Pragma( }else{ if( pCol->iDflt ){ sqlite3_value *pDfltValue = 0; - sqlite3ValueFromExpr(db, sqlite3ColumnExpr(pTab,pCol), ENC(db), - pCol->affinity, &pDfltValue); + sqlite3ValueFromExpr(db, sqlite3ColumnExprAuth(pTab,pCol,pParse), + ENC(db), pCol->affinity, &pDfltValue); if( pDfltValue ){ p4 = sqlite3_value_type(pDfltValue); sqlite3ValueFree(pDfltValue); @@ -141548,8 +147388,20 @@ SQLITE_PRIVATE void sqlite3Pragma( pPrior = pIdx; sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */ /* Verify that an index entry exists for the current table row */ - jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1, + sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1, pIdx->nColumn); VdbeCoverage(v); + jmp2 = sqlite3VdbeAddOp3(v, OP_IFindKey, iIdxCur+j, ckUniq, r1); + VdbeCoverage(v); + sqlite3VdbeChangeP4(v, -1, (const char*)pIdx, P4_INDEX); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, + sqlite3MPrintf(db, "index %s stores an imprecise floating-point " + "value for row ", pIdx->zName), + P4_DYNAMIC); + sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3); + integrityCheckResultRow(v); + sqlite3VdbeAddOp2(v, OP_Goto, 0, ckUniq); + + sqlite3VdbeJumpHere(v, jmp2); sqlite3VdbeLoadString(v, 3, "row "); sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3); sqlite3VdbeLoadString(v, 4, " missing from index "); @@ -141557,7 +147409,7 @@ SQLITE_PRIVATE void sqlite3Pragma( jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName); sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); jmp4 = integrityCheckResultRow(v); - sqlite3VdbeJumpHere(v, jmp2); + sqlite3VdbeResolveLabel(v, ckUniq); /* The OP_IdxRowid opcode is an optimized version of OP_Column ** that extracts the rowid off the end of the index record. @@ -141637,7 +147489,7 @@ SQLITE_PRIVATE void sqlite3Pragma( Table *pTab = sqliteHashData(x); sqlite3_vtab *pVTab; int a1; - if( pObjTab && pObjTab!=pTab ) continue; + if( tableSkipIntegrityCheck(pTab,pObjTab) ) continue; if( IsOrdinaryTable(pTab) ) continue; if( !IsVirtual(pTab) ) continue; if( pTab->nCol<=0 ){ @@ -141869,6 +147721,8 @@ SQLITE_PRIVATE void sqlite3Pragma( eMode = SQLITE_CHECKPOINT_RESTART; }else if( sqlite3StrICmp(zRight, "truncate")==0 ){ eMode = SQLITE_CHECKPOINT_TRUNCATE; + }else if( sqlite3StrICmp(zRight, "noop")==0 ){ + eMode = SQLITE_CHECKPOINT_NOOP; } } pParse->nMem = 3; @@ -142116,9 +147970,10 @@ SQLITE_PRIVATE void sqlite3Pragma( ** disables the timeout. */ /*case PragTyp_BUSY_TIMEOUT*/ default: { + int n = 0; assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT ); - if( zRight ){ - sqlite3_busy_timeout(db, sqlite3Atoi(zRight)); + if( zRight && sqlite3GetInt32(zRight,&n) ){ + sqlite3_busy_timeout(db, n); } returnSingleInt(v, db->busyTimeout); break; @@ -142608,7 +148463,8 @@ static void corruptSchema( static const char *azAlterType[] = { "rename", "drop column", - "add column" + "add column", + "drop constraint" }; *pData->pzErrMsg = sqlite3MPrintf(db, "error in %s %s after %s: %s", azObj[0], azObj[1], @@ -142684,6 +148540,7 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char } assert( iDb>=0 && iDb<db->nDb ); + assert( db->aDb[iDb].pSchema!=0 ); if( argv[3]==0 ){ corruptSchema(pData, argv, 0); }else if( argv[4] @@ -142702,6 +148559,7 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char int rc; u8 saved_iDb = db->init.iDb; sqlite3_stmt *pStmt; + const char *zEnd; TESTONLY(int rcp); /* Return code from sqlite3_prepare() */ assert( db->init.busy ); @@ -142716,7 +148574,7 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char db->init.orphanTrigger = 0; db->init.azInit = (const char**)argv; pStmt = 0; - TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0); + TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, &zEnd); rc = db->errCode; assert( (rc&0xFF)==(rcp&0xFF) ); db->init.iDb = saved_iDb; @@ -142732,6 +148590,8 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char corruptSchema(pData, argv, sqlite3_errmsg(db)); } } + }else if( zEnd[0] ){ + corruptSchema(pData, argv, 0); } db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */ sqlite3_finalize(pStmt); @@ -142759,6 +148619,16 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char } } } + if( pData->pzErrMsg[0]==0 ){ + Schema *pX = db->aDb[iDb].pSchema; + if( pX->tblHash.count + pX->idxHash.count + pX->trigHash.count + > (u32)db->aLimit[SQLITE_LIMIT_SCHEMA] + ){ + *pData->pzErrMsg = sqlite3MPrintf(db, "too many schema objects"); + pData->rc = SQLITE_ERROR; + return 1; + } + } return 0; } @@ -142790,7 +148660,13 @@ SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFl assert( sqlite3_mutex_held(db->mutex) ); assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); - db->init.busy = 1; + db->init.busy = 1 + ((mFlags & INITFLAG_AlterAdd)!=0); + /* ^--- Any non-zero value for init.busy means that we are scanning + ** the sqlite_schema table to build the internal schema representation, + ** rather than running actual CREATE statements. init.busy==2 has the + ** additional meaning that the scan is happening as part of + ** ALTER TABLE ADD COLUMN, which is stricter in its enforcement of + ** function name resolution. */ /* Construct the in-memory representation schema tables (sqlite_schema or ** sqlite_temp_schema) by invoking the parser directly. The appropriate @@ -142881,14 +148757,7 @@ SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFl #else encoding = SQLITE_UTF8; #endif - if( db->nVdbeActive>0 && encoding!=ENC(db) - && (db->mDbFlags & DBFLAG_Vacuum)==0 - ){ - rc = SQLITE_LOCKED; - goto initone_error_out; - }else{ - sqlite3SetTextEncoding(db, encoding); - } + sqlite3SetTextEncoding(db, encoding); }else{ /* If opening an attached database, the encoding much match ENC(db) */ if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){ @@ -143156,7 +149025,7 @@ SQLITE_PRIVATE void sqlite3ParseObjectReset(Parse *pParse){ assert( db->pParse==pParse ); assert( pParse->nested==0 ); #ifndef SQLITE_OMIT_SHARED_CACHE - if( pParse->aTableLock ) sqlite3DbNNFreeNN(db, pParse->aTableLock); + if( pParse->nTableLock ) sqlite3DbNNFreeNN(db, pParse->aTableLock); #endif while( pParse->pCleanup ){ ParseCleanup *pCleanup = pParse->pCleanup; @@ -143240,6 +149109,7 @@ SQLITE_PRIVATE void *sqlite3ParserAddCleanup( ** is generated by Lemon. */ SQLITE_PRIVATE void sqlite3ParseObjectInit(Parse *pParse, sqlite3 *db){ + assert( db!=0 ); memset(PARSE_HDR(pParse), 0, PARSE_HDR_SZ); memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ); assert( db->pParse!=pParse ); @@ -143442,9 +149312,11 @@ static int sqlite3LockAndPrepare( rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail); assert( rc==SQLITE_OK || *ppStmt==0 ); if( rc==SQLITE_OK || db->mallocFailed ) break; - }while( (rc==SQLITE_ERROR_RETRY && (cnt++)<SQLITE_MAX_PREPARE_RETRY) - || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) ); + cnt++; + }while( (rc==SQLITE_ERROR_RETRY && ALWAYS(cnt<=SQLITE_MAX_PREPARE_RETRY)) + || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt)==1) ); sqlite3BtreeLeaveAll(db); + assert( rc!=SQLITE_ERROR_RETRY ); rc = sqlite3ApiExit(db, rc); assert( (rc&db->errMask)==rc ); db->busyHandler.nBusy = 0; @@ -143637,7 +149509,7 @@ SQLITE_API int sqlite3_prepare16( const void **pzTail /* OUT: End of parsed string */ ){ int rc; - rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail); + rc = sqlite3Prepare16(db,zSql,nBytes&~1,0,ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ return rc; } @@ -143649,7 +149521,7 @@ SQLITE_API int sqlite3_prepare16_v2( const void **pzTail /* OUT: End of parsed string */ ){ int rc; - rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail); + rc = sqlite3Prepare16(db,zSql,nBytes&~1,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ return rc; } @@ -143662,7 +149534,7 @@ SQLITE_API int sqlite3_prepare16_v3( const void **pzTail /* OUT: End of parsed string */ ){ int rc; - rc = sqlite3Prepare16(db,zSql,nBytes, + rc = sqlite3Prepare16(db,zSql,nBytes&~1, SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK), ppStmt,pzTail); assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ @@ -143696,7 +149568,7 @@ SQLITE_API int sqlite3_prepare16_v3( */ typedef struct DistinctCtx DistinctCtx; struct DistinctCtx { - u8 isTnct; /* 0: Not distinct. 1: DISTICT 2: DISTINCT and ORDER BY */ + u8 isTnct; /* 0: Not distinct. 1: DISTINCT 2: DISTINCT and ORDER BY */ u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */ int tabTnct; /* Ephemeral table used for DISTINCT processing */ int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */ @@ -143826,10 +149698,8 @@ SQLITE_PRIVATE Select *sqlite3SelectNew( pNew->iLimit = 0; pNew->iOffset = 0; pNew->selId = ++pParse->nSelect; - pNew->addrOpenEphm[0] = -1; - pNew->addrOpenEphm[1] = -1; pNew->nSelectRow = 0; - if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc)); + if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, SZ_SRCLIST_1); pNew->pSrc = pSrc; pNew->pWhere = pWhere; pNew->pGroupBy = pGroupBy; @@ -143994,10 +149864,33 @@ SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *p */ SQLITE_PRIVATE int sqlite3ColumnIndex(Table *pTab, const char *zCol){ int i; - u8 h = sqlite3StrIHash(zCol); - Column *pCol; - for(pCol=pTab->aCol, i=0; i<pTab->nCol; pCol++, i++){ - if( pCol->hName==h && sqlite3StrICmp(pCol->zCnName, zCol)==0 ) return i; + u8 h; + const Column *aCol; + int nCol; + + h = sqlite3StrIHash(zCol); + aCol = pTab->aCol; + nCol = pTab->nCol; + + /* See if the aHx gives us a lucky match */ + i = pTab->aHx[h % sizeof(pTab->aHx)]; + assert( i<nCol ); + if( aCol[i].hName==h + && sqlite3StrICmp(aCol[i].zCnName, zCol)==0 + ){ + return i; + } + + /* No lucky match from the hash table. Do a full search. */ + i = 0; + while( 1 /*exit-by-break*/ ){ + if( aCol[i].hName==h + && sqlite3StrICmp(aCol[i].zCnName, zCol)==0 + ){ + return i; + } + i++; + if( i>=nCol ) break; } return -1; } @@ -144036,7 +149929,7 @@ static int tableAndColumnIndex( int iEnd, /* Last member of pSrc->a[] to check */ const char *zCol, /* Name of the column we are looking for */ int *piTab, /* Write index of pSrc->a[] here */ - int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ + int *piCol, /* Write index of pSrc->a[*piTab].pSTab->aCol[] here */ int bIgnoreHidden /* Ignore hidden columns */ ){ int i; /* For looping over tables in pSrc */ @@ -144095,8 +149988,7 @@ SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr *p, int iTable, u32 joinFlag){ assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); ExprSetVVAProperty(p, EP_NoReduce); p->w.iJoin = iTable; - if( p->op==TK_FUNCTION ){ - assert( ExprUseXList(p) ); + if( ExprUseXList(p) ){ if( p->x.pList ){ int i; for(i=0; i<p->x.pList->nExpr; i++){ @@ -144173,6 +150065,7 @@ static int sqlite3ProcessJoin(Parse *pParse, Select *p){ int i, j; /* Loop counters */ SrcItem *pLeft; /* Left table being joined */ SrcItem *pRight; /* Right table being joined */ + int bSeenTFunc = 0; /* True if have seen table-valued function */ pSrc = p->pSrc; pLeft = &pSrc->a[0]; @@ -144248,7 +150141,7 @@ static int sqlite3ProcessJoin(Parse *pParse, Select *p){ } pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol); sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol); - if( (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){ + if( (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 && pParse->nErr==0 ){ /* This branch runs if the query contains one or more RIGHT or FULL ** JOINs. If only a single table on the left side of this join ** contains the zName column, then this branch is a no-op. @@ -144264,6 +150157,8 @@ static int sqlite3ProcessJoin(Parse *pParse, Select *p){ */ ExprList *pFuncArgs = 0; /* Arguments to the coalesce() */ static const Token tkCoalesce = { "coalesce", 8 }; + assert( pE1!=0 ); + ExprSetProperty(pE1, EP_CanBeNull); while( tableAndColumnIndex(pSrc, iLeft+1, i, zName, &iLeft, &iLeftCol, pRight->fg.isSynthUsing)!=0 ){ if( pSrc->a[iLeft].fg.isUsing==0 @@ -144280,7 +150175,13 @@ static int sqlite3ProcessJoin(Parse *pParse, Select *p){ if( pFuncArgs ){ pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1); pE1 = sqlite3ExprFunction(pParse, pFuncArgs, &tkCoalesce, 0); + if( pE1 ){ + pE1->affExpr = SQLITE_AFF_DEFER; + } } + }else if( (pSrc->a[i+1].fg.jointype & JT_LEFT)!=0 && pParse->nErr==0 ){ + assert( pE1!=0 ); + ExprSetProperty(pE1, EP_CanBeNull); } pE2 = sqlite3CreateColumnExpr(db, pSrc, i+1, iRightCol); sqlite3SrcItemColumnUsed(pRight, iRightCol); @@ -144304,6 +150205,22 @@ static int sqlite3ProcessJoin(Parse *pParse, Select *p){ p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->u3.pOn); pRight->u3.pOn = 0; pRight->fg.isOn = 1; + p->selFlags |= SF_OnToWhere; + } + + if( bSeenTFunc==0 ){ + bSeenTFunc = (pLeft->fg.isTabFunc && pLeft->u1.pFuncArg); + } + + /* We also need to call sqlite3SelectCheckOnClauses() to verify that + ** table-valued function arguments do not illegally refer to any tables to + ** their right. This test is required if either (a) there is a RIGHT JOIN + ** in the SrcList, or (b) there is a LEFT JOIN to the right of a + ** table-valued function. */ + if( (pRight->fg.isTabFunc && joinType==EP_OuterON && pRight->u1.pFuncArg) + || (bSeenTFunc && joinType==EP_OuterON) + ){ + p->selFlags |= SF_OnToWhere; } } return 0; @@ -144769,6 +150686,48 @@ static void selectExprDefer( } #endif +#ifdef SQLITE_DEBUG +/* +** This is a byte-code validation check that only runs when SQLITE_DEBUG +** is defined. This routine looks backwards through the bytecode +** for the definition of cursor with index iCur. It extracts the KeyInfo from +** that cursor (it must be an index cursor) and verifies that the cursor +** does not use any collating seqeuences other than BINARY for its first +** nCol columns. +** +** This routine is used inside of an assert(). So it should return true +** on success and false if the invariant is not satisfied. +** +** tag-202607231411 +*/ +static int sqlite3CursorBloomable(Parse *pParse, int iCur, int nCol){ + int i,k; + Vdbe *v = pParse->pVdbe; + if( pParse->nErr ) return 1; + assert( v ); + for(k=sqlite3VdbeCurrentAddr(v)-1; k>0; k--){ + const VdbeOp *pOp = sqlite3VdbeGetOp(v, k); + const KeyInfo *pKeyInfo; + if( pOp->p1!=iCur ) continue; + if( pOp->opcode!=OP_OpenRead + && pOp->opcode!=OP_OpenWrite + && pOp->opcode!=OP_OpenEphemeral + ){ + continue; + } + assert( pOp->p4type==P4_KEYINFO ); + pKeyInfo = (const KeyInfo*)pOp->p4.pKeyInfo; + assert( pKeyInfo!=0 ); + for(i=0; i<nCol; i++){ + assert( sqlite3IsBinary(pKeyInfo->aColl[i]) ); + } + return 1; + } + return 0; +} +#endif /* SQLITE_DEBUG */ + + /* ** This routine generates the code for the inside of the inner loop ** of a SELECT. @@ -144944,29 +150903,6 @@ static void selectInnerLoop( } switch( eDest ){ - /* In this mode, write each query result to the key of the temporary - ** table iParm. - */ -#ifndef SQLITE_OMIT_COMPOUND_SELECT - case SRT_Union: { - int r1; - r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); - sqlite3ReleaseTempReg(pParse, r1); - break; - } - - /* Construct a record from the query result, but instead of - ** saving that record, use it as a key to delete elements from - ** the temporary table iParm. - */ - case SRT_Except: { - sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); - break; - } -#endif /* SQLITE_OMIT_COMPOUND_SELECT */ - /* Store the result as data using a unique key. */ case SRT_Fifo: @@ -145062,6 +150998,7 @@ static void selectInnerLoop( r1, pDest->zAffSdst, nResultCol); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); if( pDest->iSDParm2 ){ + assert( sqlite3CursorBloomable(pParse,iParm,nResultCol) ); sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pDest->iSDParm2, 0, regResult, nResultCol); ExplainQueryPlan((pParse, 0, "CREATE BLOOM FILTER")); @@ -145089,9 +151026,14 @@ static void selectInnerLoop( assert( nResultCol<=pDest->nSdst ); pushOntoSorter( pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); + pDest->iSDParm = regResult; }else{ assert( nResultCol==pDest->nSdst ); - assert( regResult==iParm ); + if( regResult!=iParm ){ + /* This occurs in cases where the SELECT had both a DISTINCT and + ** an OFFSET clause. */ + sqlite3VdbeAddOp3(v, OP_Copy, regResult, iParm, nResultCol-1); + } /* The LIMIT clause will jump out of the loop for us */ } break; @@ -145189,8 +151131,11 @@ static void selectInnerLoop( ** X extra columns. */ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ - int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*); - KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra); + int nExtra = (N+X)*(sizeof(CollSeq*)+1); + KeyInfo *p; + assert( X>=0 ); + if( NEVER(N+X>0xffff) ) return (KeyInfo*)sqlite3OomFault(db); + p = sqlite3DbMallocRawNN(db, SZ_KEYINFO(0) + nExtra); if( p ){ p->aSortFlags = (u8*)&p->aColl[N+X]; p->nKeyField = (u16)N; @@ -145198,7 +151143,7 @@ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ p->enc = ENC(db); p->db = db; p->nRef = 1; - memset(&p[1], 0, nExtra); + memset(p->aColl, 0, nExtra); }else{ return (KeyInfo*)sqlite3OomFault(db); } @@ -145383,6 +151328,9 @@ static void generateSortTail( Table *pTab = pSort->aDefer[i].pTab; int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead); + sqlite3VdbeAddOp2(v, OP_Rewind, pSort->aDefer[i].iCsr, + sqlite3VdbeCurrentAddr(v)+1); + VdbeCoverage(v); nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey); } #endif @@ -145757,6 +151705,10 @@ static void generateColumnTypes( #endif sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); } +#else + UNUSED_PARAMETER(pParse); + UNUSED_PARAMETER(pTabList); + UNUSED_PARAMETER(pEList); #endif /* !defined(SQLITE_OMIT_DECLTYPE) */ } @@ -146067,8 +152019,8 @@ SQLITE_PRIVATE void sqlite3SubqueryColumnTypes( } } if( zType ){ - const i64 k = sqlite3Strlen30(zType); - n = sqlite3Strlen30(pCol->zCnName); + const i64 k = strlen(zType); + n = strlen(pCol->zCnName); pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+k+2); pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL); if( pCol->zCnName ){ @@ -146085,6 +152037,20 @@ SQLITE_PRIVATE void sqlite3SubqueryColumnTypes( pTab->szTabRow = 1; /* Any non-zero value works */ } +/* +** Check the current subquery nesting depth. Return true and set an +** error if it has gone too deep. +*/ +static int checkSubqueryNestingDepth(Parse *pParse){ +#if SQLITE_MAX_EXPR_DEPTH>0 + if( pParse->nNestSel >= pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH] ){ + sqlite3ErrorMsg(pParse, "VIEWs and/or subqueries nested too deep"); + return 1; + } +#endif + return 0; +} + /* ** Given a SELECT statement, generate a Table structure that describes ** the result set of that SELECT. @@ -146094,6 +152060,8 @@ SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, c sqlite3 *db = pParse->db; u64 savedFlags; + pParse->nNestSel++; + if( checkSubqueryNestingDepth(pParse) ) return 0; savedFlags = db->flags; db->flags &= ~(u64)SQLITE_FullColNames; db->flags |= SQLITE_ShortColNames; @@ -146115,6 +152083,8 @@ SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, c sqlite3DeleteTable(db, pTab); return 0; } + pParse->nNestSel--; + assert( pParse->nNestSel>=0 ); return pTab; } @@ -146126,9 +152096,7 @@ SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){ if( pParse->pVdbe ){ return pParse->pVdbe; } - if( pParse->pToplevel==0 - && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) - ){ + if( pParse->pToplevel==0 ){ pParse->okConstFactor = 1; } return sqlite3VdbeCreate(pParse); @@ -146179,7 +152147,7 @@ static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ p->iLimit = iLimit = ++pParse->nMem; v = sqlite3GetVdbe(pParse); assert( v!=0 ); - if( sqlite3ExprIsInteger(pLimit->pLeft, &n, pParse) ){ + if( sqlite3ExprIsInteger(pLimit->pLeft, &n, pParse, 0) ){ sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); VdbeComment((v, "LIMIT counter")); if( n==0 ){ @@ -146192,6 +152160,7 @@ static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ sqlite3ExprCode(pParse, pLimit->pLeft, iLimit); sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); VdbeComment((v, "LIMIT counter")); + sqlite3MayAbort(pParse); sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); } if( pLimit->pRight ){ @@ -146199,6 +152168,7 @@ static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ pParse->nMem++; /* Allocate an extra register for limit+offset */ sqlite3ExprCode(pParse, pLimit->pRight, iOffset); sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); + sqlite3MayAbort(pParse); VdbeComment((v, "OFFSET counter")); sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset); VdbeComment((v, "LIMIT+OFFSET")); @@ -146241,9 +152211,9 @@ static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ ** function is responsible for ensuring that this structure is eventually ** freed. */ -static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ +static KeyInfo *multiSelectByMergeKeyInfo(Parse *pParse, Select *p, int nExtra){ ExprList *pOrderBy = p->pOrderBy; - int nOrderBy = ALWAYS(pOrderBy!=0) ? pOrderBy->nExpr : 0; + int nOrderBy = (pOrderBy!=0) ? pOrderBy->nExpr : 0; sqlite3 *db = pParse->db; KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); if( pRet ){ @@ -146376,7 +152346,7 @@ static void generateWithRecursiveQuery( regCurrent = ++pParse->nMem; sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); if( pOrderBy ){ - KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); + KeyInfo *pKeyInfo = multiSelectByMergeKeyInfo(pParse, p, 1); sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, (char*)pKeyInfo, P4_KEYINFO); destQueue.pOrderBy = pOrderBy; @@ -146385,8 +152355,28 @@ static void generateWithRecursiveQuery( } VdbeComment((v, "Queue table")); if( iDistinct ){ - p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); - p->selFlags |= SF_UsesEphemeral; + /* Generate an ephemeral table used to enforce distinctness on the + ** output of the recursive part of the CTE. + */ + KeyInfo *pKeyInfo; /* Collating sequence for the result set */ + CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ + + assert( p->pNext==0 ); + assert( p->pEList!=0 ); + nCol = p->pEList->nExpr; + pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nCol, 1); + if( pKeyInfo ){ + for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ + *apColl = multiSelectCollSeq(pParse, p, i); + if( 0==*apColl ){ + *apColl = pParse->db->pDfltColl; + } + } + sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iDistinct, nCol, 0, + (void*)pKeyInfo, P4_KEYINFO); + }else{ + assert( pParse->nErr>0 ); + } } /* Detach the ORDER BY clause from the compound SELECT */ @@ -146461,7 +152451,7 @@ static void generateWithRecursiveQuery( #endif /* SQLITE_OMIT_CTE */ /* Forward references */ -static int multiSelectOrderBy( +static int multiSelectByMerge( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ @@ -146526,11 +152516,33 @@ static int hasAnchor(Select *p){ } /* -** This routine is called to process a compound query form from +** Return TRUE if p is a UNION with a LIMIT of exactly 1 and no OFFSET +** clause. This is a precondition for a couple of related optimizations. +** +** False negatives are harmless (apart from resulting in a slower query). +** False positives can result in incorrect answers, however. To provoke +** false negatives for testing purposes, disable the SQLITE_UnionLimit +** optimization. +*/ +static int unionWithLimitOne(sqlite3 *db, Select *p){ + int v; + if( p->op!=TK_UNION ) return 0; + if( p->pLimit==0 ) return 0; + if( p->pLimit->pRight ) return 0; /* No OFFSET */ + v = 0; + assert( p->pLimit->pLeft!=0 ); + if( sqlite3ExprIsInteger(p->pLimit->pLeft, &v, 0, 0)==0 ) return 0; + if( v!=1 ) return 0; + if( OptimizationDisabled(db, SQLITE_UnionLimit) ) return 0; + return 1; +} + +/* +** This routine is called to process a compound query formed from ** two or more separate queries using UNION, UNION ALL, EXCEPT, or ** INTERSECT ** -** "p" points to the right-most of the two queries. the query on the +** "p" points to the right-most of the two queries. The query on the ** left is p->pPrior. The left query could also be a compound query ** in which case this routine will be called recursively. ** @@ -146610,12 +152622,27 @@ static int multiSelect( generateWithRecursiveQuery(pParse, p, &dest); }else #endif - - /* Compound SELECTs that have an ORDER BY clause are handled separately. - */ if( p->pOrderBy ){ - return multiSelectOrderBy(pParse, p, pDest); - }else{ + /* If the compound has an ORDER BY clause, then always use the merge + ** algorithm. */ + return multiSelectByMerge(pParse, p, pDest); + }else if( p->op!=TK_ALL && !unionWithLimitOne(db,p) ){ + /* If the compound is EXCEPT, INTERSECT, or UNION (anything other than + ** UNION ALL) then also always use the merge algorithm. However, the + ** multiSelectByMerge() routine requires that the compound have an + ** ORDER BY clause, and it doesn't right now. So invent one first. */ + Expr *pOne = sqlite3ExprInt32(db, 1); + p->pOrderBy = sqlite3ExprListAppend(pParse, 0, pOne); + if( pParse->nErr ) goto multi_select_end; + assert( p->pOrderBy!=0 ); + p->pOrderBy->a[0].u.x.iOrderByCol = 1; + return multiSelectByMerge(pParse, p, pDest); + }else{ + /* For a UNION ALL compound without ORDER BY, or for a UNION with a + ** LIMIT of exactly 1 and no OFFSET and no ORDER BY, simply run the left + ** query, then run the right query */ + int addr = 0; + int nLimit = 0; /* Initialize to suppress harmless compiler warning */ #ifndef SQLITE_OMIT_EXPLAIN if( pPrior->pPrior==0 ){ @@ -146623,282 +152650,55 @@ static int multiSelect( ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY")); } #endif - - /* Generate code for the left and right SELECT statements. - */ - switch( p->op ){ - case TK_ALL: { - int addr = 0; - int nLimit = 0; /* Initialize to suppress harmless compiler warning */ - assert( !pPrior->pLimit ); - pPrior->iLimit = p->iLimit; - pPrior->iOffset = p->iOffset; - pPrior->pLimit = p->pLimit; - TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL left...\n")); - rc = sqlite3Select(pParse, pPrior, &dest); - pPrior->pLimit = 0; - if( rc ){ - goto multi_select_end; - } - p->pPrior = 0; - p->iLimit = pPrior->iLimit; - p->iOffset = pPrior->iOffset; - if( p->iLimit ){ - addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); - VdbeComment((v, "Jump ahead if LIMIT reached")); - if( p->iOffset ){ - sqlite3VdbeAddOp3(v, OP_OffsetLimit, - p->iLimit, p->iOffset+1, p->iOffset); - } - } - ExplainQueryPlan((pParse, 1, "UNION ALL")); - TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL right...\n")); - rc = sqlite3Select(pParse, p, &dest); - testcase( rc!=SQLITE_OK ); - pDelete = p->pPrior; - p->pPrior = pPrior; - p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); - if( p->pLimit - && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit, pParse) - && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) - ){ - p->nSelectRow = sqlite3LogEst((u64)nLimit); - } - if( addr ){ - sqlite3VdbeJumpHere(v, addr); - } - break; - } - case TK_EXCEPT: - case TK_UNION: { - int unionTab; /* Cursor number of the temp table holding result */ - u8 op = 0; /* One of the SRT_ operations to apply to self */ - int priorOp; /* The SRT_ operation to apply to prior selects */ - Expr *pLimit; /* Saved values of p->nLimit */ - int addr; - SelectDest uniondest; - - testcase( p->op==TK_EXCEPT ); - testcase( p->op==TK_UNION ); - priorOp = SRT_Union; - if( dest.eDest==priorOp ){ - /* We can reuse a temporary table generated by a SELECT to our - ** right. - */ - assert( p->pLimit==0 ); /* Not allowed on leftward elements */ - unionTab = dest.iSDParm; - }else{ - /* We will need to create our own temporary table to hold the - ** intermediate results. - */ - unionTab = pParse->nTab++; - assert( p->pOrderBy==0 ); - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); - assert( p->addrOpenEphm[0] == -1 ); - p->addrOpenEphm[0] = addr; - findRightmost(p)->selFlags |= SF_UsesEphemeral; - assert( p->pEList ); - } - - - /* Code the SELECT statements to our left - */ - assert( !pPrior->pOrderBy ); - sqlite3SelectDestInit(&uniondest, priorOp, unionTab); - TREETRACE(0x200, pParse, p, ("multiSelect EXCEPT/UNION left...\n")); - rc = sqlite3Select(pParse, pPrior, &uniondest); - if( rc ){ - goto multi_select_end; - } - - /* Code the current SELECT statement - */ - if( p->op==TK_EXCEPT ){ - op = SRT_Except; - }else{ - assert( p->op==TK_UNION ); - op = SRT_Union; - } - p->pPrior = 0; - pLimit = p->pLimit; - p->pLimit = 0; - uniondest.eDest = op; - ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", - sqlite3SelectOpName(p->op))); - TREETRACE(0x200, pParse, p, ("multiSelect EXCEPT/UNION right...\n")); - rc = sqlite3Select(pParse, p, &uniondest); - testcase( rc!=SQLITE_OK ); - assert( p->pOrderBy==0 ); - pDelete = p->pPrior; - p->pPrior = pPrior; - p->pOrderBy = 0; - if( p->op==TK_UNION ){ - p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); - } - sqlite3ExprDelete(db, p->pLimit); - p->pLimit = pLimit; - p->iLimit = 0; - p->iOffset = 0; - - /* Convert the data in the temporary table into whatever form - ** it is that we currently need. - */ - assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); - assert( p->pEList || db->mallocFailed ); - if( dest.eDest!=priorOp && db->mallocFailed==0 ){ - int iCont, iBreak, iStart; - iBreak = sqlite3VdbeMakeLabel(pParse); - iCont = sqlite3VdbeMakeLabel(pParse); - computeLimitRegisters(pParse, p, iBreak); - sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); - iStart = sqlite3VdbeCurrentAddr(v); - selectInnerLoop(pParse, p, unionTab, - 0, 0, &dest, iCont, iBreak); - sqlite3VdbeResolveLabel(v, iCont); - sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); - sqlite3VdbeResolveLabel(v, iBreak); - sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); - } - break; - } - default: assert( p->op==TK_INTERSECT ); { - int tab1, tab2; - int iCont, iBreak, iStart; - Expr *pLimit; - int addr; - SelectDest intersectdest; - int r1; - - /* INTERSECT is different from the others since it requires - ** two temporary tables. Hence it has its own case. Begin - ** by allocating the tables we will need. - */ - tab1 = pParse->nTab++; - tab2 = pParse->nTab++; - assert( p->pOrderBy==0 ); - - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); - assert( p->addrOpenEphm[0] == -1 ); - p->addrOpenEphm[0] = addr; - findRightmost(p)->selFlags |= SF_UsesEphemeral; - assert( p->pEList ); - - /* Code the SELECTs to our left into temporary table "tab1". - */ - sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); - TREETRACE(0x400, pParse, p, ("multiSelect INTERSECT left...\n")); - rc = sqlite3Select(pParse, pPrior, &intersectdest); - if( rc ){ - goto multi_select_end; - } - - /* Code the current SELECT into temporary table "tab2" - */ - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); - assert( p->addrOpenEphm[1] == -1 ); - p->addrOpenEphm[1] = addr; - p->pPrior = 0; - pLimit = p->pLimit; - p->pLimit = 0; - intersectdest.iSDParm = tab2; - ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", - sqlite3SelectOpName(p->op))); - TREETRACE(0x400, pParse, p, ("multiSelect INTERSECT right...\n")); - rc = sqlite3Select(pParse, p, &intersectdest); - testcase( rc!=SQLITE_OK ); - pDelete = p->pPrior; - p->pPrior = pPrior; - if( p->nSelectRow>pPrior->nSelectRow ){ - p->nSelectRow = pPrior->nSelectRow; - } - sqlite3ExprDelete(db, p->pLimit); - p->pLimit = pLimit; - - /* Generate code to take the intersection of the two temporary - ** tables. - */ - if( rc ) break; - assert( p->pEList ); - iBreak = sqlite3VdbeMakeLabel(pParse); - iCont = sqlite3VdbeMakeLabel(pParse); - computeLimitRegisters(pParse, p, iBreak); - sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); - r1 = sqlite3GetTempReg(pParse); - iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1); - sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); - VdbeCoverage(v); - sqlite3ReleaseTempReg(pParse, r1); - selectInnerLoop(pParse, p, tab1, - 0, 0, &dest, iCont, iBreak); - sqlite3VdbeResolveLabel(v, iCont); - sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); - sqlite3VdbeResolveLabel(v, iBreak); - sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); - sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); - break; - } - } - - #ifndef SQLITE_OMIT_EXPLAIN - if( p->pNext==0 ){ - ExplainQueryPlanPop(pParse); - } - #endif - } - if( pParse->nErr ) goto multi_select_end; - - /* Compute collating sequences used by - ** temporary tables needed to implement the compound select. - ** Attach the KeyInfo structure to all temporary tables. - ** - ** This section is run by the right-most SELECT statement only. - ** SELECT statements to the left always skip this part. The right-most - ** SELECT might also skip this part if it has no ORDER BY clause and - ** no temp tables are required. - */ - if( p->selFlags & SF_UsesEphemeral ){ - int i; /* Loop counter */ - KeyInfo *pKeyInfo; /* Collating sequence for the result set */ - Select *pLoop; /* For looping through SELECT statements */ - CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ - int nCol; /* Number of columns in result set */ - - assert( p->pNext==0 ); - assert( p->pEList!=0 ); - nCol = p->pEList->nExpr; - pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); - if( !pKeyInfo ){ - rc = SQLITE_NOMEM_BKPT; + assert( !pPrior->pLimit ); + pPrior->iLimit = p->iLimit; + pPrior->iOffset = p->iOffset; + pPrior->pLimit = sqlite3ExprDup(db, p->pLimit, 0); + TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL left...\n")); + rc = sqlite3Select(pParse, pPrior, &dest); + sqlite3ExprDelete(db, pPrior->pLimit); + pPrior->pLimit = 0; + if( rc ){ goto multi_select_end; } - for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ - *apColl = multiSelectCollSeq(pParse, p, i); - if( 0==*apColl ){ - *apColl = db->pDfltColl; - } + p->pPrior = 0; + p->iLimit = pPrior->iLimit; + p->iOffset = pPrior->iOffset; + if( p->iLimit ){ + addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); + VdbeComment((v, "Jump ahead if LIMIT reached")); + if( p->iOffset ){ + sqlite3VdbeAddOp3(v, OP_OffsetLimit, + p->iLimit, p->iOffset+1, p->iOffset); + } + } + ExplainQueryPlan((pParse, 1, "UNION ALL")); + TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL right...\n")); + rc = sqlite3Select(pParse, p, &dest); + testcase( rc!=SQLITE_OK ); + pDelete = p->pPrior; + p->pPrior = pPrior; + p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); + if( p->pLimit + && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit, pParse, 0) + && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) + ){ + p->nSelectRow = sqlite3LogEst((u64)nLimit); } - - for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ - for(i=0; i<2; i++){ - int addr = pLoop->addrOpenEphm[i]; - if( addr<0 ){ - /* If [0] is unused then [1] is also unused. So we can - ** always safely abort as soon as the first unused slot is found */ - assert( pLoop->addrOpenEphm[1]<0 ); - break; - } - sqlite3VdbeChangeP2(v, addr, nCol); - sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), - P4_KEYINFO); - pLoop->addrOpenEphm[i] = -1; - } + if( addr ){ + sqlite3VdbeJumpHere(v, addr); } - sqlite3KeyInfoUnref(pKeyInfo); +#ifndef SQLITE_OMIT_EXPLAIN + if( p->pNext==0 ){ + ExplainQueryPlanPop(pParse); + } +#endif } multi_select_end: pDest->iSdst = dest.iSdst; pDest->nSdst = dest.nSdst; + pDest->iSDParm2 = dest.iSDParm2; if( pDelete ){ sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pDelete); } @@ -146924,8 +152724,8 @@ SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){ ** Code an output subroutine for a coroutine implementation of a ** SELECT statement. ** -** The data to be output is contained in pIn->iSdst. There are -** pIn->nSdst columns to be output. pDest is where the output should +** The data to be output is contained in an array of pIn->nSdst registers +** starting at register pIn->iSdst. pDest is where the output should ** be sent. ** ** regReturn is the number of the register holding the subroutine @@ -146954,6 +152754,8 @@ static int generateOutputSubroutine( int iContinue; int addr; + assert( pIn->eDest==SRT_Coroutine ); + addr = sqlite3VdbeCurrentAddr(v); iContinue = sqlite3VdbeMakeLabel(pParse); @@ -146975,23 +152777,60 @@ static int generateOutputSubroutine( */ codeOffset(v, p->iOffset, iContinue); - assert( pDest->eDest!=SRT_Exists ); - assert( pDest->eDest!=SRT_Table ); switch( pDest->eDest ){ /* Store the result as data using a unique key. */ + case SRT_Fifo: + case SRT_DistFifo: + case SRT_Table: case SRT_EphemTab: { int r1 = sqlite3GetTempReg(pParse); int r2 = sqlite3GetTempReg(pParse); + int iParm = pDest->iSDParm; + testcase( pDest->eDest==SRT_Table ); + testcase( pDest->eDest==SRT_EphemTab ); + testcase( pDest->eDest==SRT_Fifo ); + testcase( pDest->eDest==SRT_DistFifo ); sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); - sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); - sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); +#if !defined(SQLITE_ENABLE_NULL_TRIM) && defined(SQLITE_DEBUG) + /* A destination of SRT_Table and a non-zero iSDParm2 parameter means + ** that this is an "UPDATE ... FROM" on a virtual table or view. In this + ** case set the p5 parameter of the OP_MakeRecord to OPFLAG_NOCHNG_MAGIC. + ** This does not affect operation in any way - it just allows MakeRecord + ** to process OPFLAG_NOCHANGE values without an assert() failing. */ + if( pDest->eDest==SRT_Table && pDest->iSDParm2 ){ + sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC); + } +#endif +#ifndef SQLITE_OMIT_CTE + if( pDest->eDest==SRT_DistFifo ){ + /* If the destination is DistFifo, then cursor (iParm+1) is open + ** on an ephemeral index that is used to enforce uniqueness on the + ** total result. At this point, we are processing the setup portion + ** of the recursive CTE using the merge algorithm, so the results are + ** guaranteed to be unique anyhow. But we still need to populate the + ** (iParm+1) cursor for use by the subsequent recursive phase. + */ + sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1, + pIn->iSdst, pIn->nSdst); + } +#endif + sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); + sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); sqlite3ReleaseTempReg(pParse, r2); sqlite3ReleaseTempReg(pParse, r1); break; } + /* If any row exist in the result set, record that fact and abort. + */ + case SRT_Exists: { + sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm); + /* The LIMIT clause will terminate the loop for us */ + break; + } + #ifndef SQLITE_OMIT_SUBQUERY /* If we are creating a set for an "expr IN (SELECT ...)". */ @@ -147004,6 +152843,7 @@ static int generateOutputSubroutine( sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1, pIn->iSdst, pIn->nSdst); if( pDest->iSDParm2>0 ){ + assert( sqlite3CursorBloomable(pParse, pDest->iSDParm, pIn->nSdst) ); sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pDest->iSDParm2, 0, pIn->iSdst, pIn->nSdst); ExplainQueryPlan((pParse, 0, "CREATE BLOOM FILTER")); @@ -147038,9 +152878,51 @@ static int generateOutputSubroutine( break; } +#ifndef SQLITE_OMIT_CTE + /* Write the results into a priority queue that is order according to + ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an + ** index with pSO->nExpr+2 columns. Build a key using pSO for the first + ** pSO->nExpr columns, then make sure all keys are unique by adding a + ** final OP_Sequence column. The last column is the record as a blob. + */ + case SRT_DistQueue: + case SRT_Queue: { + int nKey; + int r1, r2, r3, ii; + ExprList *pSO; + int iParm = pDest->iSDParm; + pSO = pDest->pOrderBy; + assert( pSO ); + nKey = pSO->nExpr; + r1 = sqlite3GetTempReg(pParse); + r2 = sqlite3GetTempRange(pParse, nKey+2); + r3 = r2+nKey+1; + + sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r3); + if( pDest->eDest==SRT_DistQueue ){ + sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); + } + for(ii=0; ii<nKey; ii++){ + sqlite3VdbeAddOp2(v, OP_SCopy, + pIn->iSdst + pSO->a[ii].u.x.iOrderByCol - 1, + r2+ii); + } + sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); + sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); + sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2); + sqlite3ReleaseTempReg(pParse, r1); + sqlite3ReleaseTempRange(pParse, r2, nKey+2); + break; + } +#endif /* SQLITE_OMIT_CTE */ + + /* Ignore the output */ + case SRT_Discard: { + break; + } + /* If none of the above, then the result destination must be - ** SRT_Output. This routine is never called with any other - ** destination other than the ones handled above or SRT_Output. + ** SRT_Output. ** ** For SRT_Output, results are stored in a sequence of registers. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to @@ -147068,8 +152950,9 @@ static int generateOutputSubroutine( } /* -** Alternative compound select code generator for cases when there -** is an ORDER BY clause. +** Generate code for a compound SELECT statement using a merge +** algorithm. The compound must have an ORDER BY clause for this +** to work. ** ** We assume a query of the following form: ** @@ -147086,7 +152969,7 @@ static int generateOutputSubroutine( ** ** outB: Move the output of the selectB coroutine into the output ** of the compound query. (Only generated for UNION and -** UNION ALL. EXCEPT and INSERTSECT never output a row that +** UNION ALL. EXCEPT and INTERSECT never output a row that ** appears only in B.) ** ** AltB: Called when there is data from both coroutines and A<B. @@ -147139,10 +153022,8 @@ static int generateOutputSubroutine( ** AeqB: ... ** AgtB: ... ** Init: initialize coroutine registers -** yield coA -** if eof(A) goto EofA -** yield coB -** if eof(B) goto EofB +** yield coA, on eof goto EofA +** yield coB, on eof goto EofB ** Cmpr: Compare A, B ** Jump AltB, AeqB, AgtB ** End: ... @@ -147150,10 +153031,10 @@ static int generateOutputSubroutine( ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not ** actually called using Gosub and they do not Return. EofA and EofB loop ** until all data is exhausted then jump to the "end" label. AltB, AeqB, -** and AgtB jump to either L2 or to one of EofA or EofB. +** and AgtB jump to either Cmpr or to one of EofA or EofB. */ #ifndef SQLITE_OMIT_COMPOUND_SELECT -static int multiSelectOrderBy( +static int multiSelectByMerge( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ @@ -147225,10 +153106,8 @@ static int multiSelectOrderBy( if( pItem->u.x.iOrderByCol==i ) break; } if( j==nOrderBy ){ - Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); + Expr *pNew = sqlite3ExprInt32(db, i); if( pNew==0 ) return SQLITE_NOMEM_BKPT; - pNew->flags |= EP_IntValue; - pNew->u.iValue = i; p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i; } @@ -147236,26 +153115,29 @@ static int multiSelectOrderBy( } /* Compute the comparison permutation and keyinfo that is used with - ** the permutation used to determine if the next - ** row of results comes from selectA or selectB. Also add explicit - ** collations to the ORDER BY clause terms so that when the subqueries - ** to the right and the left are evaluated, they use the correct - ** collation. + ** the permutation to determine if the next row of results comes + ** from selectA or selectB. Also add literal collations to the + ** ORDER BY clause terms so that when selectA and selectB are + ** evaluated, they use the correct collation. */ aPermute = sqlite3DbMallocRawNN(db, sizeof(u32)*(nOrderBy + 1)); if( aPermute ){ struct ExprList_item *pItem; + int bKeep = 0; aPermute[0] = nOrderBy; for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){ assert( pItem!=0 ); assert( pItem->u.x.iOrderByCol>0 ); assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr ); aPermute[i] = pItem->u.x.iOrderByCol - 1; + if( aPermute[i]!=(u32)i-1 ) bKeep = 1; + } + if( bKeep==0 ){ + sqlite3DbFreeNN(db, aPermute); + aPermute = 0; } - pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1); - }else{ - pKeyMerge = 0; } + pKeyMerge = multiSelectByMergeKeyInfo(pParse, p, 1); /* Allocate a range of temporary registers and the KeyInfo needed ** for the logic that removes duplicate result rows when the @@ -147308,7 +153190,7 @@ static int multiSelectOrderBy( /* Compute the limit registers */ computeLimitRegisters(pParse, p, labelEnd); - if( p->iLimit && op==TK_ALL ){ + if( p->iLimit && (op==TK_ALL || unionWithLimitOne(db,p)) ){ regLimitA = ++pParse->nMem; regLimitB = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, @@ -147334,7 +153216,7 @@ static int multiSelectOrderBy( */ addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); - VdbeComment((v, "left SELECT")); + VdbeComment((v, "SUBR: next-A")); pPrior->iLimit = regLimitA; ExplainQueryPlan((pParse, 1, "LEFT")); sqlite3Select(pParse, pPrior, &destA); @@ -147346,7 +153228,7 @@ static int multiSelectOrderBy( */ addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); - VdbeComment((v, "right SELECT")); + VdbeComment((v, "SUBR: next-B")); savedLimit = p->iLimit; savedOffset = p->iOffset; p->iLimit = regLimitB; @@ -147360,7 +153242,7 @@ static int multiSelectOrderBy( /* Generate a subroutine that outputs the current row of the A ** select as the next output row of the compound select. */ - VdbeNoopComment((v, "Output routine for A")); + VdbeNoopComment((v, "SUBR: out-A")); addrOutA = generateOutputSubroutine(pParse, p, &destA, pDest, regOutA, regPrev, pKeyDup, labelEnd); @@ -147369,7 +153251,7 @@ static int multiSelectOrderBy( ** select as the next output row of the compound select. */ if( op==TK_ALL || op==TK_UNION ){ - VdbeNoopComment((v, "Output routine for B")); + VdbeNoopComment((v, "SUBR: out-B")); addrOutB = generateOutputSubroutine(pParse, p, &destB, pDest, regOutB, regPrev, pKeyDup, labelEnd); @@ -147382,10 +153264,12 @@ static int multiSelectOrderBy( if( op==TK_EXCEPT || op==TK_INTERSECT ){ addrEofA_noB = addrEofA = labelEnd; }else{ - VdbeNoopComment((v, "eof-A subroutine")); + VdbeNoopComment((v, "SUBR: eof-A")); addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); + VdbeComment((v, "out-B")); addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); VdbeCoverage(v); + VdbeComment((v, "next-B")); sqlite3VdbeGoto(v, addrEofA); p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); } @@ -147397,17 +153281,20 @@ static int multiSelectOrderBy( addrEofB = addrEofA; if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; }else{ - VdbeNoopComment((v, "eof-B subroutine")); + VdbeNoopComment((v, "SUBR: eof-B")); addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); + VdbeComment((v, "out-A")); sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); + VdbeComment((v, "next-A")); sqlite3VdbeGoto(v, addrEofB); } /* Generate code to handle the case of A<B */ - VdbeNoopComment((v, "A-lt-B subroutine")); addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); + VdbeComment((v, "out-A")); sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); + VdbeComment((v, "next-A")); sqlite3VdbeGoto(v, labelCmpr); /* Generate code to handle the case of A==B @@ -147418,36 +153305,48 @@ static int multiSelectOrderBy( addrAeqB = addrAltB; addrAltB++; }else{ - VdbeNoopComment((v, "A-eq-B subroutine")); - addrAeqB = - sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); - sqlite3VdbeGoto(v, labelCmpr); + addrAeqB = addrAltB + 1; } /* Generate code to handle the case of A>B */ - VdbeNoopComment((v, "A-gt-B subroutine")); addrAgtB = sqlite3VdbeCurrentAddr(v); if( op==TK_ALL || op==TK_UNION ){ sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); + VdbeComment((v, "out-B")); + sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); + VdbeComment((v, "next-B")); + sqlite3VdbeGoto(v, labelCmpr); + }else{ + addrAgtB++; /* Just do next-B. Might as well use the next-B call + ** in the next code block */ } - sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); - sqlite3VdbeGoto(v, labelCmpr); /* This code runs once to initialize everything. */ sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); + VdbeComment((v, "next-A")); + /* v--- Also the A>B case for EXCEPT and INTERSECT */ sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); + VdbeComment((v, "next-B")); /* Implement the main merge loop */ + if( aPermute!=0 ){ + sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); + } sqlite3VdbeResolveLabel(v, labelCmpr); - sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, (char*)pKeyMerge, P4_KEYINFO); - sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); - sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); + if( aPermute!=0 ){ + sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); + } + sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); + VdbeCoverageIf(v, op==TK_ALL); + VdbeCoverageIf(v, op==TK_UNION); + VdbeCoverageIf(v, op==TK_EXCEPT); + VdbeCoverageIf(v, op==TK_INTERSECT); /* Jump to the this point in order to terminate the query. */ @@ -147481,7 +153380,7 @@ static int multiSelectOrderBy( ** ## About "isOuterJoin": ** ** The isOuterJoin column indicates that the replacement will occur into a -** position in the parent that NULL-able due to an OUTER JOIN. Either the +** position in the parent that is NULL-able due to an OUTER JOIN. Either the ** target slot in the parent is the right operand of a LEFT JOIN, or one of ** the left operands of a RIGHT JOIN. In either case, we need to potentially ** bypass the substituted expression with OP_IfNullRow. @@ -147511,6 +153410,7 @@ typedef struct SubstContext { int iTable; /* Replace references to this table */ int iNewTable; /* New table number */ int isOuterJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */ + int nSelDepth; /* Depth of sub-query recursion. Top==1 */ ExprList *pEList; /* Replacement expressions */ ExprList *pCList; /* Collation sequences for replacement expr */ } SubstContext; @@ -147586,38 +153486,41 @@ static Expr *substExpr( if( pSubst->isOuterJoin ){ ExprSetProperty(pNew, EP_CanBeNull); } - if( ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) ){ - sqlite3SetJoinExpr(pNew, pExpr->w.iJoin, - pExpr->flags & (EP_OuterON|EP_InnerON)); - } - sqlite3ExprDelete(db, pExpr); - pExpr = pNew; - if( pExpr->op==TK_TRUEFALSE ){ - pExpr->u.iValue = sqlite3ExprTruthValue(pExpr); - pExpr->op = TK_INTEGER; - ExprSetProperty(pExpr, EP_IntValue); + if( pNew->op==TK_TRUEFALSE ){ + pNew->u.iValue = sqlite3ExprTruthValue(pNew); + pNew->op = TK_INTEGER; + ExprSetProperty(pNew, EP_IntValue); } /* Ensure that the expression now has an implicit collation sequence, ** just as it did when it was a column of a view or sub-query. */ { - CollSeq *pNat = sqlite3ExprCollSeq(pSubst->pParse, pExpr); + CollSeq *pNat = sqlite3ExprCollSeq(pSubst->pParse, pNew); CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pSubst->pCList->a[iColumn].pExpr ); - if( pNat!=pColl || (pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE) ){ - pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr, + if( pNat!=pColl || (pNew->op!=TK_COLUMN && pNew->op!=TK_COLLATE) ){ + pNew = sqlite3ExprAddCollateString(pSubst->pParse, pNew, (pColl ? pColl->zName : "BINARY") ); } } - ExprClearProperty(pExpr, EP_Collate); + ExprClearProperty(pNew, EP_Collate); + if( ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) ){ + sqlite3SetJoinExpr(pNew, pExpr->w.iJoin, + pExpr->flags & (EP_OuterON|EP_InnerON)); + } + sqlite3ExprDelete(db, pExpr); + pExpr = pNew; } } }else{ if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){ pExpr->iTable = pSubst->iNewTable; } + if( pExpr->op==TK_AGG_FUNCTION && pExpr->op2>=pSubst->nSelDepth ){ + pExpr->op2--; + } pExpr->pLeft = substExpr(pSubst, pExpr->pLeft); pExpr->pRight = substExpr(pSubst, pExpr->pRight); if( ExprUseXSelect(pExpr) ){ @@ -147655,6 +153558,7 @@ static void substSelect( SrcItem *pItem; int i; if( !p ) return; + pSubst->nSelDepth++; do{ substExprList(pSubst, p->pEList); substExprList(pSubst, p->pGroupBy); @@ -147672,6 +153576,7 @@ static void substSelect( } } }while( doPrior && (p = p->pPrior)!=0 ); + pSubst->nSelDepth--; } #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ @@ -147766,7 +153671,9 @@ static int renumberCursorsCb(Walker *pWalker, Expr *pExpr){ if( op==TK_COLUMN || op==TK_IF_NULL_ROW ){ renumberCursorDoMapping(pWalker, &pExpr->iTable); } - if( ExprHasProperty(pExpr, EP_OuterON) ){ + if( ExprHasProperty(pExpr, (EP_OuterON|EP_InnerON)) ){ + testcase( ExprHasProperty(pExpr, EP_OuterON) ); + testcase( ExprHasProperty(pExpr, EP_InnerON) ); renumberCursorDoMapping(pWalker, &pExpr->w.iJoin); } return WRC_Continue; @@ -147887,9 +153794,9 @@ static int compoundHasDifferentAffinities(Select *p){ ** from 2015-02-09.) ** ** (3) If the subquery is the right operand of a LEFT JOIN then -** (3a) the subquery may not be a join and -** (3b) the FROM clause of the subquery may not contain a virtual -** table and +** (3a) the subquery may not be a join +** (**) Was (3b): "the FROM clause of the subquery may not contain +** a virtual table" ** (**) Was: "The outer query may not have a GROUP BY." This case ** is now managed correctly ** (3d) the outer query may not be DISTINCT. @@ -148105,7 +154012,7 @@ static int flattenSubquery( */ if( (pSubitem->fg.jointype & (JT_OUTER|JT_LTORJ))!=0 ){ if( pSubSrc->nSrc>1 /* (3a) */ - || IsVirtual(pSubSrc->a[0].pSTab) /* (3b) */ + /**** || IsVirtual(pSubSrc->a[0].pSTab) (3b)-omitted */ || (p->selFlags & SF_Distinct)!=0 /* (3d) */ || (pSubitem->fg.jointype & JT_RIGHT)!=0 /* (26) */ ){ @@ -148283,7 +154190,7 @@ static int flattenSubquery( ** complete, since there may still exist Expr.pTab entries that ** refer to the subquery even after flattening. Ticket #3346. ** - ** pSubitem->pTab is always non-NULL by test restrictions and tests above. + ** pSubitem->pSTab is always non-NULL by test restrictions and tests above. */ if( ALWAYS(pSubitem->pSTab!=0) ){ Table *pTabToDel = pSubitem->pSTab; @@ -148313,17 +154220,12 @@ static int flattenSubquery( pSub = pSub1; for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ int nSubSrc; - u8 jointype = 0; - u8 ltorj = pSrc->a[iFrom].fg.jointype & JT_LTORJ; + u8 jointype = pParent->pSrc->a[iFrom].fg.jointype; assert( pSub!=0 ); pSubSrc = pSub->pSrc; /* FROM clause of subquery */ nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ pSrc = pParent->pSrc; /* FROM clause of the outer query */ - if( pParent==p ){ - jointype = pSubitem->fg.jointype; /* First time through the loop */ - } - /* The subquery uses a single slot of the FROM clause of the outer ** query. If the subquery has more than one element in its FROM clause, ** then expand the outer query to make space for it to hold all elements @@ -148348,6 +154250,7 @@ static int flattenSubquery( /* Transfer the FROM clause terms from the subquery into the ** outer query. */ + iNewParent = pSubSrc->a[0].iCursor; for(i=0; i<nSubSrc; i++){ SrcItem *pItem = &pSrc->a[i+iFrom]; assert( pItem->fg.isTabFunc==0 ); @@ -148356,14 +154259,12 @@ static int flattenSubquery( || pItem->u4.zDatabase==0 ); if( pItem->fg.isUsing ) sqlite3IdListDelete(db, pItem->u3.pUsing); *pItem = pSubSrc->a[i]; - pItem->fg.jointype |= ltorj; - iNewParent = pSubSrc->a[i].iCursor; + pItem->fg.jointype |= (jointype & JT_LTORJ); memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); } - pSrc->a[iFrom].fg.jointype &= JT_LTORJ; - pSrc->a[iFrom].fg.jointype |= jointype | ltorj; + pSrc->a[iFrom].fg.jointype |= jointype; - /* Now begin substituting subquery result set expressions for + /* Begin substituting subquery result set expressions for ** references to the iParent in the outer query. ** ** Example: @@ -148375,7 +154276,7 @@ static int flattenSubquery( ** We look at every expression in the outer query and every place we see ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". */ - if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){ + if( pSub->pOrderBy ){ /* At this point, any non-zero iOrderByCol values indicate that the ** ORDER BY column expression is identical to the iOrderByCol'th ** expression returned by SELECT statement pSub. Since these values @@ -148383,9 +154284,9 @@ static int flattenSubquery( ** zero them before transferring the ORDER BY clause. ** ** Not doing this may cause an error if a subsequent call to this - ** function attempts to flatten a compound sub-query into pParent - ** (the only way this can happen is if the compound sub-query is - ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ + ** function attempts to flatten a compound sub-query into pParent. + ** See ticket [d11a6e908f]. + */ ExprList *pOrderBy = pSub->pOrderBy; for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].u.x.iOrderByCol = 0; @@ -148397,6 +154298,7 @@ static int flattenSubquery( pWhere = pSub->pWhere; pSub->pWhere = 0; if( isOuterJoin>0 ){ + assert( pSubSrc->nSrc==1 ); sqlite3SetJoinExpr(pWhere, iNewParent, EP_OuterON); } if( pWhere ){ @@ -148412,6 +154314,7 @@ static int flattenSubquery( x.iTable = iParent; x.iNewTable = iNewParent; x.isOuterJoin = isOuterJoin; + x.nSelDepth = 0; x.pEList = pSub->pEList; x.pCList = findLeftmostExprlist(pSub); substSelect(&x, pParent, 0); @@ -148474,12 +154377,21 @@ struct WhereConst { }; /* -** Add a new entry to the pConst object. Except, do not add duplicate -** pColumn entries. Also, do not add if doing so would not be appropriate. +** Add a new entry to the pConst object, if appropriate. +** +** * Do not add if pValue is not constant. (This is enforced by +** the caller) ** -** The caller guarantees the pColumn is a column and pValue is a constant. -** This routine has to do some additional checks before completing the -** insert. +** * Do not add duplicate pColumn entries +** +** * Do not add if pValue has an affinity +** +** * Do not add if the comparison uses a collating sequence other +** than binary. +** +** * Do not add if pValue is a function that might return a subtype +** +** The caller guarantees the pColumn is a column. */ static void constInsert( WhereConst *pConst, /* The WhereConst into which we are inserting */ @@ -148490,12 +154402,12 @@ static void constInsert( int i; assert( pColumn->op==TK_COLUMN ); assert( sqlite3ExprIsConstant(pConst->pParse, pValue) ); - if( ExprHasProperty(pColumn, EP_FixedCol) ) return; if( sqlite3ExprAffinity(pValue)!=0 ) return; if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){ return; } + if( sqlite3ExprCanReturnSubtype(pConst->pParse, pValue) ) return; /* 2018-10-25 ticket [cf5ed20f] ** Make sure the same pColumn is not inserted more than once */ @@ -148508,7 +154420,8 @@ static void constInsert( return; /* Already present. Return without doing anything. */ } } - if( sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){ + assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB ); + if( sqlite3ExprAffinity(pColumn)<=SQLITE_AFF_BLOB ){ pConst->bHasAffBlob = 1; } @@ -148583,7 +154496,8 @@ static int propagateConstantExprRewriteOne( if( pColumn==pExpr ) continue; if( pColumn->iTable!=pExpr->iTable ) continue; if( pColumn->iColumn!=pExpr->iColumn ) continue; - if( bIgnoreAffBlob && sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){ + assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB ); + if( bIgnoreAffBlob && sqlite3ExprAffinity(pColumn)<=SQLITE_AFF_BLOB ){ break; } /* A match is found. Add the EP_FixedCol property */ @@ -148639,7 +154553,7 @@ static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){ ** ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or ** CONSTANT=COLUMN that are top-level AND-connected terms that are not -** part of a ON clause from a LEFT JOIN, then throughout the query +** part of a ON clause from an OUTER JOIN, then throughout the query ** replace all other occurrences of COLUMN with CONSTANT. ** ** For example, the query: @@ -148995,9 +154909,20 @@ static int pushDownWhereTerms( x.iTable = pSrc->iCursor; x.iNewTable = pSrc->iCursor; x.isOuterJoin = 0; + x.nSelDepth = 0; x.pEList = pSubq->pEList; x.pCList = findLeftmostExprlist(pSubq); pNew = substExpr(&x, pNew); + assert( pNew!=0 || pParse->nErr!=0 ); + if( pParse->nErr==0 && pNew->op==TK_IN && ExprUseXSelect(pNew) ){ + assert( pNew->x.pSelect!=0 ); + pNew->x.pSelect->selFlags |= SF_ClonedRhsIn; + assert( pWhere!=0 ); + assert( pWhere->op==TK_IN ); + assert( ExprUseXSelect(pWhere) ); + assert( pWhere->x.pSelect!=0 ); + pWhere->x.pSelect->selFlags |= SF_ClonedRhsIn; + } #ifndef SQLITE_OMIT_WINDOWFUNC if( pSubq->pWin && 0==pushDownWindowCheck(pParse, pSubq, pNew) ){ /* Restriction 6c has prevented push-down in this case */ @@ -149232,14 +155157,14 @@ SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, SrcItem *pFrom){ ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) ** ORDER BY ... COLLATE ... ** -** This transformation is necessary because the multiSelectOrderBy() routine +** This transformation is necessary because the multiSelectByMerge() routine ** above that generates the code for a compound SELECT with an ORDER BY clause ** uses a merge algorithm that requires the same collating sequence on the ** result columns as on the ORDER BY clause. See ticket -** http://www.sqlite.org/src/info/6709574d2a +** http://sqlite.org/src/info/6709574d2a ** ** This transformation is only needed for EXCEPT, INTERSECT, and UNION. -** The UNION ALL operator works fine with multiSelectOrderBy() even when +** The UNION ALL operator works fine with multiSelectByMerge() even when ** there are COLLATE terms in the ORDER BY. */ static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ @@ -149297,7 +155222,7 @@ static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ #ifndef SQLITE_OMIT_WINDOWFUNC p->pWinDefn = 0; #endif - p->selFlags &= ~SF_Compound; + p->selFlags &= ~(u32)SF_Compound; assert( (p->selFlags & SF_Converted)==0 ); p->selFlags |= SF_Converted; assert( pNew->pPrior!=0 ); @@ -149386,14 +155311,13 @@ SQLITE_PRIVATE With *sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ } /* -** This function checks if argument pFrom refers to a CTE declared by +** This function checks to see if argument pFrom refers to a CTE declared by ** a WITH clause on the stack currently maintained by the parser (on the -** pParse->pWith linked list). And if currently processing a CTE -** CTE expression, through routine checks to see if the reference is -** a recursive reference to the CTE. +** pParse->pWith linked list). And if currently processing a CTE expression, +** it also checks to see if the reference is a recursive reference to the CTE. ** -** If pFrom matches a CTE according to either of these two above, pFrom->pTab -** and other fields are populated accordingly. +** If pFrom matches a CTE, pFrom->pSTab and other fields are populated +** accordingly. ** ** Return 0 if no match is found. ** Return 1 if a match is found. @@ -149522,6 +155446,18 @@ static int resolveFromTermToCte( pRecTerm = pRecTerm->pPrior; } +#if SQLITE_MAX_EXPR_DEPTH>0 + if( pParse->nTab>=db->aLimit[SQLITE_LIMIT_EXPR_DEPTH] ){ + /* Bug 2026-10-04T05:35:14Z: Prevent nested CTEs from generating + ** an exponential number of cursors. The error message here will + ** be "Nested too deep", which isn't exactly correct, but it is + ** sufficient, and we don't want to use extra code space for more + ** detail on such an obscure error. */ + pParse->nNestSel = pParse->nTab; + } + pParse->nNestSel++; + if( checkSubqueryNestingDepth(pParse) ) return 2; +#endif pCte->zCteErr = "circular reference: %s"; pSavedWith = pParse->pWith; pParse->pWith = pWith; @@ -149546,6 +155482,10 @@ static int resolveFromTermToCte( } } pParse->pWith = pWith; +#if SQLITE_MAX_EXPR_DEPTH>0 + pParse->nNestSel--; + assert( pParse->nNestSel>=0 ); +#endif for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); pEList = pLeft->pEList; @@ -149713,7 +155653,7 @@ static int selectExpander(Walker *pWalker, Select *p){ pEList = p->pEList; if( pParse->pWith && (p->selFlags & SF_View) ){ if( p->pWith==0 ){ - p->pWith = (With*)sqlite3DbMallocZero(db, sizeof(With)); + p->pWith = (With*)sqlite3DbMallocZero(db, SZ_WITH(1) ); if( p->pWith==0 ){ return WRC_Abort; } @@ -149785,7 +155725,7 @@ static int selectExpander(Walker *pWalker, Select *p){ } #ifndef SQLITE_OMIT_VIRTUALTABLE else if( ALWAYS(IsVirtual(pTab)) - && pFrom->fg.fromDDL + && (pFrom->fg.fromDDL || (pParse->prepFlags & SQLITE_PREPARE_FROM_DDL)) && ALWAYS(pTab->u.vtab.p!=0) && pTab->u.vtab.p->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0) ){ @@ -149992,6 +155932,7 @@ static int selectExpander(Walker *pWalker, Select *p){ pRight = sqlite3Expr(db, TK_ID, zName); if( (pTabList->nSrc>1 && ( (pFrom->fg.jointype & JT_LTORJ)==0 + || zTName!=0 || (selFlags & SF_NestedFrom)!=0 || !inAnyUsingClause(zName,pFrom,pTabList->nSrc-i-1) ) @@ -150430,6 +156371,7 @@ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ if( pFunc->bOBPayload ){ /* extra columns for the function arguments */ assert( ExprUseXList(pFunc->pFExpr) ); + assert( pFunc->pFExpr->x.pList!=0 ); nExtra += pFunc->pFExpr->x.pList->nExpr; } if( pFunc->bUseSubtype ){ @@ -150500,7 +156442,7 @@ static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ } sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i)); sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, (u8)nArg); + sqlite3VdbeChangeP5(v, (u16)nArg); sqlite3VdbeAddOp2(v, OP_Next, pF->iOBTab, iTop+1); VdbeCoverage(v); sqlite3VdbeJumpHere(v, iTop); sqlite3ReleaseTempRange(pParse, regAgg, nArg); @@ -150663,7 +156605,7 @@ static void updateAccumulator( } sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i)); sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, (u8)nArg); + sqlite3VdbeChangeP5(v, (u16)nArg); sqlite3ReleaseTempRange(pParse, regAgg, nArg); } if( addrNext ){ @@ -150737,7 +156679,7 @@ static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){ && pExpr->pAggInfo==0 ){ sqlite3 *db = pWalker->pParse->db; - Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1"); + Expr *pNew = sqlite3ExprInt32(db, 1); if( pNew ){ Expr *pWhere = pS->pWhere; SWAP(Expr, *pNew, *pExpr); @@ -150852,6 +156794,7 @@ static void agginfoFree(sqlite3 *db, void *pArg){ ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries ** * The outer query is a simple count(*) with no WHERE clause or other ** extraneous syntax. +** * None of the subqueries are DISTINCT (forumpost/a860f5fb2e 2025-03-10) ** ** Return TRUE if the optimization is undertaken. */ @@ -150876,7 +156819,8 @@ static int countOfViewOptimization(Parse *pParse, Select *p){ if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */ if( ExprHasProperty(pExpr, EP_WinFunc) ) return 0;/* Not a window function */ pFrom = p->pSrc->a; - if( pFrom->fg.isSubquery==0 ) return 0; /* FROM is a subquery */ + if( pFrom->fg.isSubquery==0 ) return 0; /* FROM is a subquery */ + if( (p->selFlags & SF_Correlated)!=0 ) return 0; /* Not a correlated subq */ pSub = pFrom->u4.pSubq->pSelect; if( pSub->pPrior==0 ) return 0; /* Must be a compound */ if( pSub->selFlags & SF_CopyCte ) return 0; /* Not a CTE */ @@ -150884,7 +156828,11 @@ static int countOfViewOptimization(Parse *pParse, Select *p){ if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */ if( pSub->pWhere ) return 0; /* No WHERE clause */ if( pSub->pLimit ) return 0; /* No LIMIT clause */ - if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */ + if( pSub->selFlags & (SF_Aggregate|SF_Distinct) ){ + testcase( pSub->selFlags & SF_Aggregate ); + testcase( pSub->selFlags & SF_Distinct ); + return 0; /* Not an aggregate nor DISTINCT */ + } assert( pSub->pHaving==0 ); /* Due to the previous */ pSub = pSub->pPrior; /* Repeat over compound */ }while( pSub ); @@ -150896,14 +156844,14 @@ static int countOfViewOptimization(Parse *pParse, Select *p){ pExpr = 0; pSub = sqlite3SubqueryDetach(db, pFrom); sqlite3SrcListDelete(db, p->pSrc); - p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc)); + p->pSrc = sqlite3DbMallocZero(pParse->db, SZ_SRCLIST_1); while( pSub ){ Expr *pTerm; pPrior = pSub->pPrior; pSub->pPrior = 0; pSub->pNext = 0; pSub->selFlags |= SF_Aggregate; - pSub->selFlags &= ~SF_Compound; + pSub->selFlags &= ~(u32)SF_Compound; pSub->nSelectRow = 0; sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pSub->pEList); pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount; @@ -150915,10 +156863,14 @@ static int countOfViewOptimization(Parse *pParse, Select *p){ }else{ pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr); } + if( pParse->nErr ){ + sqlite3ExprDelete(db, pExpr); + pExpr = 0; + } pSub = pPrior; } p->pEList->a[0].pExpr = pExpr; - p->selFlags &= ~SF_Aggregate; + p->selFlags &= ~(u32)SF_Aggregate; #if TREETRACE_ENABLED if( sqlite3TreeTrace & 0x200 ){ @@ -151014,6 +156966,278 @@ static int fromClauseTermCanBeCoroutine( return 1; } +/* +** Argument pWhere is the WHERE clause belonging to SELECT statement p. This +** function attempts to transform expressions of the form: +** +** EXISTS (SELECT ...) +** +** into joins. For example, given +** +** CREATE TABLE sailors(sid INTEGER PRIMARY KEY, name TEXT); +** CREATE TABLE reserves(sid INT, day DATE, PRIMARY KEY(sid, day)); +** +** SELECT name FROM sailors AS S WHERE EXISTS ( +** SELECT * FROM reserves AS R WHERE S.sid = R.sid AND R.day = '2022-10-25' +** ); +** +** the SELECT statement may be transformed as follows: +** +** SELECT name FROM sailors AS S, reserves AS R +** WHERE S.sid = R.sid AND R.day = '2022-10-25'; +** +** **Approximately**. Really, we have to ensure that the FROM-clause term +** that was formerly inside the EXISTS is only executed once. This is handled +** by setting the SrcItem.fg.fromExists flag, which then causes code in +** the where.c file to exit the corresponding loop after the first successful +** match (if any). +*/ +static SQLITE_NOINLINE void existsToJoin( + Parse *pParse, /* Parsing context */ + Select *p, /* The SELECT statement being optimized */ + Expr *pWhere /* part of the WHERE clause currently being examined */ +){ + if( pParse->nErr==0 + && pWhere!=0 + && !ExprHasProperty(pWhere, EP_OuterON|EP_InnerON) + && ALWAYS(p->pSrc!=0) + && p->pSrc->nSrc<BMS + && (p->pLimit==0 || p->pLimit->pRight==0) + ){ + if( pWhere->op==TK_AND ){ + Expr *pRight = pWhere->pRight; + existsToJoin(pParse, p, pWhere->pLeft); + existsToJoin(pParse, p, pRight); + } + else if( pWhere->op==TK_EXISTS ){ + Select *pSub = pWhere->x.pSelect; + Expr *pSubWhere = pSub->pWhere; + if( pSub->pSrc->nSrc==1 + && (pSub->selFlags & SF_Aggregate)==0 + && !pSub->pSrc->a[0].fg.isSubquery + && pSub->pLimit==0 + && pSub->pPrior==0 + ){ + /* Before combining the sub-select with the parent, renumber the + ** cursor used by the subselect. This is because the EXISTS expression + ** might be a copy of another EXISTS expression from somewhere + ** else in the tree, and in this case it is important that it use + ** a unique cursor number. */ + sqlite3 *db = pParse->db; + int *aCsrMap = sqlite3DbMallocZero(db, (pParse->nTab+2)*sizeof(int)); + if( aCsrMap==0 ) return; + aCsrMap[0] = (pParse->nTab+1); + renumberCursors(pParse, pSub, -1, aCsrMap); + sqlite3DbFree(db, aCsrMap); + + memset(pWhere, 0, sizeof(*pWhere)); + pWhere->op = TK_INTEGER; + pWhere->u.iValue = 1; + ExprSetProperty(pWhere, EP_IntValue); + assert( p->pWhere!=0 ); + pSub->pSrc->a[0].fg.fromExists = 1; + p->pSrc = sqlite3SrcListAppendList(pParse, p->pSrc, pSub->pSrc); + if( pSubWhere ){ + p->pWhere = sqlite3PExpr(pParse, TK_AND, p->pWhere, pSubWhere); + pSub->pWhere = 0; + } + pSub->pSrc = 0; + sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pSub); + recomputeColumnsUsed(p, &p->pSrc->a[p->pSrc->nSrc-1]); +#if TREETRACE_ENABLED + if( sqlite3TreeTrace & 0x100000 ){ + TREETRACE(0x100000,pParse,p, + ("After EXISTS-to-JOIN optimization:\n")); + sqlite3TreeViewSelect(0, p, 0); + } +#endif + } + } + } +} + +/* +** Type used for Walker callbacks by selectCheckOnClauses(). +*/ +typedef struct CheckOnCtx CheckOnCtx; +struct CheckOnCtx { + SrcList *pSrc; /* SrcList for this context */ + int iJoin; /* Cursors must be left of this one, if not negative */ + int bFuncArg; /* True for table-function arg */ + CheckOnCtx *pParent; /* Parent context */ +}; + +/* +** True if the SrcList passed as the only argument contains at least +** one RIGHT or FULL JOIN. False otherwise. +*/ +#define hasRightJoin(pSrc) (((pSrc)->a[0].fg.jointype & JT_LTORJ)!=0) + +/* +** The xExpr callback for the search of invalid ON clause terms. +*/ +static int selectCheckOnClausesExpr(Walker *pWalker, Expr *pExpr){ + CheckOnCtx *pCtx = pWalker->u.pCheckOnCtx; + + /* Check if pExpr is root or near-root of an ON clause constraint that needs + ** to be checked to ensure that it does not refer to tables in its FROM + ** clause to the right of itself. i.e. it is either: + ** + ** + an ON clause on an OUTER join, or + ** + an ON clause on an INNER join within a FROM that features at + ** least one RIGHT or FULL join. + */ + if( (ExprHasProperty(pExpr, EP_OuterON)) + || (ExprHasProperty(pExpr, EP_InnerON) && hasRightJoin(pCtx->pSrc)) + ){ + /* If CheckOnCtx.iJoin is already set, then fall through and process + ** this expression node as normal. Or, if CheckOnCtx.iJoin is still 0, + ** set it to the cursor number of the RHS of the join to which this + ** ON expression was attached and then iterate through the entire + ** expression. */ + assert( pCtx->iJoin<0 || pCtx->iJoin==pExpr->w.iJoin ); + if( pCtx->iJoin<0 ){ + pCtx->iJoin = pExpr->w.iJoin; + sqlite3WalkExprNN(pWalker, pExpr); + pCtx->iJoin = -1; + return WRC_Prune; + } + } + + if( pExpr->op==TK_COLUMN ){ + /* A column expression. Find the SrcList (if any) to which it refers. + ** Then, if CheckOnCtx.iJoin indicates that this expression is part of an + ** ON clause from that SrcList (i.e. if iJoin is non-zero), check that it + ** does not refer to a table to the right of CheckOnCtx.iJoin. */ + int iTab = pExpr->iTable; + do { + SrcList *pSrc = pCtx->pSrc; + int nSrc = pSrc->nSrc; + int ii; + for(ii=0; ii<nSrc && pSrc->a[ii].iCursor!=iTab; ii++){} + if( ii<nSrc ){ + /* pSrc is the FROM clause that contains iTab */ + if( pCtx->iJoin>=0 ){ + for(ii--; ii>=0 && pSrc->a[ii].iCursor!=pCtx->iJoin; ii--){} + if( ii>=0 ){ + /* Table iJoin appears to the left of table iTab in the SrcList. + ** Therefore the expression refers to a table to its right. */ + sqlite3ErrorMsg(pWalker->pParse, + "%s references tables to its right", + (pCtx->bFuncArg ? "table-function argument" : "ON clause") + ); + return WRC_Abort; + } + } + break; + } + pCtx = pCtx->pParent; + }while( pCtx ); + } + return WRC_Continue; +} + +/* +** The xSelect callback for the search of invalid ON clause terms. +*/ +static int selectCheckOnClausesSelect(Walker *pWalker, Select *pSelect){ + CheckOnCtx *pCtx = pWalker->u.pCheckOnCtx; + if( pSelect->pSrc==pCtx->pSrc || pSelect->pSrc->nSrc==0 ){ + return WRC_Continue; + }else{ + CheckOnCtx sCtx; + memset(&sCtx, 0, sizeof(sCtx)); + sCtx.pSrc = pSelect->pSrc; + sCtx.pParent = pCtx; + sCtx.iJoin = -1; + pWalker->u.pCheckOnCtx = &sCtx; + sqlite3WalkSelect(pWalker, pSelect); + pWalker->u.pCheckOnCtx = pCtx; + pSelect->selFlags &= ~SF_OnToWhere; + return WRC_Prune; + } +} + +/* +** Check all ON clauses in pSelect to verify that they do not reference +** columns to the right. +*/ +SQLITE_PRIVATE void sqlite3SelectCheckOnClauses(Parse *pParse, Select *pSelect){ + Walker w; + CheckOnCtx sCtx; + int ii; + assert( pSelect->selFlags & SF_OnToWhere ); + assert( pSelect->pSrc!=0 && pSelect->pSrc->nSrc>=2 ); + memset(&w, 0, sizeof(w)); + w.pParse = pParse; + w.xExprCallback = selectCheckOnClausesExpr; + w.xSelectCallback = selectCheckOnClausesSelect; + w.u.pCheckOnCtx = &sCtx; + memset(&sCtx, 0, sizeof(sCtx)); + sCtx.pSrc = pSelect->pSrc; + sCtx.iJoin = -1; + sqlite3WalkExpr(&w, pSelect->pWhere); + pSelect->selFlags &= ~SF_OnToWhere; + + /* Check for any table-function args that are attached to virtual tables + ** on the RHS of an outer join. They are subject to similar constraints + ** as ON clauses. Specifically: + ** + ** * If the table-valued function is to the left of any RIGHT JOIN, or if + ** it is the RHS of a RIGHT JOIN, then the table-valued function arguments + ** may not refer to any tables to the right of this one. + ** + ** * If the table-valued function is to the left of a LEFT JOIN, then it + ** may not refer to any table that occurs to the right of the LEFT JOIN. + */ + sCtx.bFuncArg = 1; + for(ii=0; ii<pSelect->pSrc->nSrc; ii++){ + SrcItem *pItem = &pSelect->pSrc->a[ii]; + if( pItem->fg.isTabFunc ){ + sCtx.iJoin = -1; + if( (pItem->fg.jointype & (JT_LTORJ|JT_RIGHT)) ){ + sCtx.iJoin = pItem->iCursor; + }else{ + int jj; + for(jj=ii+1; jj<pSelect->pSrc->nSrc; jj++){ + SrcItem *pItem2 = &pSelect->pSrc->a[jj]; + if( pItem2->fg.jointype & JT_OUTER ){ + sCtx.iJoin = pItem2[-1].iCursor; + break; + } + } + } + if( sCtx.iJoin>=0 ){ + sqlite3WalkExprList(&w, pItem->u1.pFuncArg); + } + } + } +} + +/* +** If p2 exists and p1 and p2 have the same number of terms, then change +** every term of p1 to have the same sort order as p2 and return true. +** +** If p2 is NULL or p1 and p2 are different lengths, then make no changes +** and return false. +** +** p1 must be non-NULL. +*/ +static int sqlite3CopySortOrder(ExprList *p1, ExprList *p2){ + assert( p1 ); + if( p2 && p1->nExpr==p2->nExpr ){ + int ii; + for(ii=0; ii<p1->nExpr; ii++){ + u8 sortFlags; + sortFlags = p2->a[ii].fg.sortFlags & KEYINFO_ORDER_DESC; + p1->a[ii].fg.sortFlags = sortFlags; + } + return 1; + }else{ + return 0; + } +} + /* ** Generate byte-code for the SELECT statement given in the p argument. ** @@ -151109,8 +157333,7 @@ SQLITE_PRIVATE int sqlite3Select( assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue ); assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue ); if( IgnorableDistinct(pDest) ){ - assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || - pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard || + assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Discard || pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_DistFifo ); /* All of these destinations are also able to ignore the ORDER BY clause */ if( p->pOrderBy ){ @@ -151125,8 +157348,7 @@ SQLITE_PRIVATE int sqlite3Select( testcase( pParse->earlyCleanup ); p->pOrderBy = 0; } - p->selFlags &= ~SF_Distinct; - p->selFlags |= SF_NoopOrderBy; + p->selFlags &= ~(u32)SF_Distinct; } sqlite3SelectPrep(pParse, p, 0); if( pParse->nErr ){ @@ -151164,7 +157386,7 @@ SQLITE_PRIVATE int sqlite3Select( ** and leaving this flag set can cause errors if a compound sub-query ** in p->pSrc is flattened into this query and this function called ** again as part of compound SELECT processing. */ - p->selFlags &= ~SF_UFSrcCheck; + p->selFlags &= ~(u32)SF_UFSrcCheck; } if( pDest->eDest==SRT_Output ){ @@ -151382,6 +157604,13 @@ SQLITE_PRIVATE int sqlite3Select( } #endif + /* If there may be an "EXISTS (SELECT ...)" in the WHERE clause, attempt + ** to change it into a join. */ + if( pParse->bHasExists && OptimizationEnabled(db,SQLITE_ExistsToJoin) ){ + existsToJoin(pParse, p, p->pWhere); + pTabList = p->pSrc; + } + /* Do the WHERE-clause constant propagation optimization if this is ** a join. No need to spend time on this operation for non-join queries ** as the equivalent optimization will be handled by query planner in @@ -151496,7 +157725,7 @@ SQLITE_PRIVATE int sqlite3Select( #endif assert( pSubq->pSelect && (pSub->selFlags & SF_PushDown)!=0 ); }else{ - TREETRACE(0x4000,pParse,p,("WHERE-lcause push-down not possible\n")); + TREETRACE(0x4000,pParse,p,("WHERE-clause push-down not possible\n")); } /* Convert unused result columns of the subquery into simple NULL @@ -151647,13 +157876,14 @@ SQLITE_PRIVATE int sqlite3Select( ** BY and DISTINCT, and an index or separate temp-table for the other. */ if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct - && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 + && sqlite3CopySortOrder(pEList, sSort.pOrderBy) + && sqlite3ExprListCompare(pEList, sSort.pOrderBy, -1)==0 && OptimizationEnabled(db, SQLITE_GroupByOrder) #ifndef SQLITE_OMIT_WINDOWFUNC && p->pWin==0 #endif ){ - p->selFlags &= ~SF_Distinct; + p->selFlags &= ~(u32)SF_Distinct; pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); if( pGroupBy ){ for(i=0; i<pGroupBy->nExpr; i++){ @@ -151762,6 +157992,12 @@ SQLITE_PRIVATE int sqlite3Select( if( pWInfo==0 ) goto select_end; if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); + if( pDest->eDest<=SRT_DistQueue && pDest->eDest>=SRT_DistFifo ){ + /* TUNING: For a UNION CTE, because UNION is implies DISTINCT, + ** reduce the estimated output row count by 8 (LogEst 30). + ** Search for tag-20250414a to see other cases */ + p->nSelectRow -= 30; + } } if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); @@ -151855,21 +158091,10 @@ SQLITE_PRIVATE int sqlite3Select( ** but not actually sorted. Either way, record the fact that the ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp ** variable. */ - if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){ - int ii; - /* The GROUP BY processing doesn't care whether rows are delivered in - ** ASC or DESC order - only that each group is returned contiguously. - ** So set the ASC/DESC flags in the GROUP BY to match those in the - ** ORDER BY to maximize the chances of rows being delivered in an - ** order that makes the ORDER BY redundant. */ - for(ii=0; ii<pGroupBy->nExpr; ii++){ - u8 sortFlags; - sortFlags = sSort.pOrderBy->a[ii].fg.sortFlags & KEYINFO_ORDER_DESC; - pGroupBy->a[ii].fg.sortFlags = sortFlags; - } - if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ - orderByGrp = 1; - } + if( sqlite3CopySortOrder(pGroupBy, sSort.pOrderBy) + && sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 + ){ + orderByGrp = 1; } }else{ assert( 0==sqlite3LogEst(1) ); @@ -151992,6 +158217,7 @@ SQLITE_PRIVATE int sqlite3Select( sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); VdbeComment((v, "clear abort flag")); sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); + sqlite3ExprNullRegisterRange(pParse, iAMem, pGroupBy->nExpr); /* Begin a loop that will extract all source rows in GROUP BY order. ** This might involve two separate loops with an OP_Sort in between, or @@ -152135,6 +158361,10 @@ SQLITE_PRIVATE int sqlite3Select( if( iOrderByCol ){ Expr *pX = p->pEList->a[iOrderByCol-1].pExpr; Expr *pBase = sqlite3ExprSkipCollateAndLikely(pX); + while( ALWAYS(pBase!=0) && pBase->op==TK_IF_NULL_ROW ){ + pX = pBase->pLeft; + pBase = sqlite3ExprSkipCollateAndLikely(pX); + } if( ALWAYS(pBase!=0) && pBase->op!=TK_AGG_COLUMN && pBase->op!=TK_REGISTER @@ -152158,12 +158388,12 @@ SQLITE_PRIVATE int sqlite3Select( ** for the next GROUP BY batch. */ sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); - VdbeComment((v, "output one row")); + VdbeComment((v, "output one row of %d", p->selId)); sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); VdbeComment((v, "check abort flag")); sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); - VdbeComment((v, "reset accumulator")); + VdbeComment((v, "reset accumulator %d", p->selId)); /* Update the aggregate accumulators based on the content of ** the current row @@ -152171,7 +158401,7 @@ SQLITE_PRIVATE int sqlite3Select( sqlite3VdbeJumpHere(v, addr1); updateAccumulator(pParse, iUseFlag, pAggInfo, eDist); sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); - VdbeComment((v, "indicate data in accumulator")); + VdbeComment((v, "indicate data in accumulator %d", p->selId)); /* End of the loop */ @@ -152188,7 +158418,7 @@ SQLITE_PRIVATE int sqlite3Select( /* Output the final row of result */ sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); - VdbeComment((v, "output final row")); + VdbeComment((v, "output final row of %d", p->selId)); /* Jump over the subroutines */ @@ -152209,7 +158439,7 @@ SQLITE_PRIVATE int sqlite3Select( addrOutputRow = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v); - VdbeComment((v, "Groupby result generator entry point")); + VdbeComment((v, "Groupby result generator entry point %d", p->selId)); sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); finalizeAggFunctions(pParse, pAggInfo); sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); @@ -152217,14 +158447,14 @@ SQLITE_PRIVATE int sqlite3Select( &sDistinct, pDest, addrOutputRow+1, addrSetAbort); sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); - VdbeComment((v, "end groupby result generator")); + VdbeComment((v, "end groupby result generator %d", p->selId)); /* Generate a subroutine that will reset the group-by accumulator */ sqlite3VdbeResolveLabel(v, addrReset); resetAccumulator(pParse, pAggInfo); sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); - VdbeComment((v, "indicate accumulator empty")); + VdbeComment((v, "indicate accumulator %d empty", p->selId)); sqlite3VdbeAddOp1(v, OP_Return, regReset); if( distFlag!=0 && eDist!=WHERE_DISTINCT_NOOP ){ @@ -152674,7 +158904,7 @@ SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerS sqlite3SelectDelete(db, pTmp->pSelect); sqlite3IdListDelete(db, pTmp->pIdList); sqlite3UpsertDelete(db, pTmp->pUpsert); - sqlite3SrcListDelete(db, pTmp->pFrom); + sqlite3SrcListDelete(db, pTmp->pSrc); sqlite3DbFree(db, pTmp->zSpan); sqlite3DbFree(db, pTmp); @@ -152718,7 +158948,8 @@ SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){ assert( pParse->db->pVtabCtx==0 ); #endif assert( pParse->bReturning ); - assert( &(pParse->u1.pReturning->retTrig) == pTrig ); + assert( !pParse->isCreate ); + assert( &(pParse->u1.d.pReturning->retTrig) == pTrig ); pTrig->table = pTab->zName; pTrig->pTabSchema = pTab->pSchema; pTrig->pNext = pList; @@ -152853,8 +159084,9 @@ SQLITE_PRIVATE void sqlite3BeginTrigger( if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){ if( !noErr ){ sqlite3ErrorMsg(pParse, "trigger %T already exists", pName); + }else if( db->init.busy ){ + sqlite3ErrorMsg(pParse,""); /* Err msg generated by corruptSchema() */ }else{ - assert( !db->init.busy ); sqlite3CodeVerifySchema(pParse, iDb); VVA_ONLY( pParse->ifNotExists = 1; ) } @@ -152862,11 +159094,16 @@ SQLITE_PRIVATE void sqlite3BeginTrigger( } } + /* NB: The SQLITE_ALLOW_TRIGGERS_ON_SYSTEM_TABLES compile-time option is + ** experimental and unsupported. Do not use it unless understand the + ** implications and you cannot get by without this capability. */ +#if !defined(SQLITE_ALLOW_TRIGGERS_ON_SYSTEM_TABLES) /* Experimental */ /* Do not create a trigger on a system table */ if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){ sqlite3ErrorMsg(pParse, "cannot create trigger on system table"); goto trigger_cleanup; } +#endif /* INSTEAD of triggers are only for views and views only support INSTEAD ** of triggers. @@ -152973,16 +159210,22 @@ SQLITE_PRIVATE void sqlite3FinishTrigger( DbFixer sFix; /* Fixer object */ int iDb; /* Database containing the trigger */ Token nameToken; /* Trigger name for error reporting */ + i64 n; /* Number of steps */ pParse->pNewTrigger = 0; if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup; zName = pTrig->zName; iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); + assert( iDb>=00 && iDb<db->nDb ); pTrig->step_list = pStepList; - while( pStepList ){ + for(n=0; pStepList; n++){ pStepList->pTrig = pTrig; pStepList = pStepList->pNext; } + if( n>pParse->db->aLimit[SQLITE_LIMIT_TRIGGER_STEPS] ){ + sqlite3ErrorMsg(pParse, "trigger \"%w\" contains too many steps", zName); + goto triggerfinish_cleanup; + } sqlite3TokenInit(&nameToken, pTrig->zName); sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken); if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) @@ -153012,12 +159255,12 @@ SQLITE_PRIVATE void sqlite3FinishTrigger( if( sqlite3ReadOnlyShadowTables(db) ){ TriggerStep *pStep; for(pStep=pTrig->step_list; pStep; pStep=pStep->pNext){ - if( pStep->zTarget!=0 - && sqlite3ShadowTableName(db, pStep->zTarget) + if( pStep->pSrc!=0 + && sqlite3ShadowTableName(db, pStep->pSrc->a[0].zName) ){ sqlite3ErrorMsg(pParse, "trigger \"%s\" may not write to shadow table \"%s\"", - pTrig->zName, pStep->zTarget); + pTrig->zName, pStep->pSrc->a[0].zName); goto triggerfinish_cleanup; } } @@ -153108,26 +159351,39 @@ SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep( static TriggerStep *triggerStepAllocate( Parse *pParse, /* Parser context */ u8 op, /* Trigger opcode */ - Token *pName, /* The target name */ + SrcList *pTabList, /* Target table */ const char *zStart, /* Start of SQL text */ const char *zEnd /* End of SQL text */ ){ + Trigger *pNew = pParse->pNewTrigger; sqlite3 *db = pParse->db; - TriggerStep *pTriggerStep; + TriggerStep *pTriggerStep = 0; - if( pParse->nErr ) return 0; - pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1); - if( pTriggerStep ){ - char *z = (char*)&pTriggerStep[1]; - memcpy(z, pName->z, pName->n); - sqlite3Dequote(z); - pTriggerStep->zTarget = z; - pTriggerStep->op = op; - pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd); - if( IN_RENAME_OBJECT ){ - sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName); + if( pParse->nErr==0 ){ + if( pNew + && pNew->pSchema!=db->aDb[1].pSchema + && pTabList->a[0].u4.zDatabase + ){ + sqlite3ErrorMsg(pParse, + "qualified table names are not allowed on INSERT, UPDATE, and DELETE " + "statements within triggers"); + }else{ + pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep)); + if( pTriggerStep ){ + pTriggerStep->pSrc = sqlite3SrcListDup(db, pTabList, EXPRDUP_REDUCE); + pTriggerStep->op = op; + pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd); + if( pTriggerStep->pSrc && IN_RENAME_OBJECT ){ + sqlite3RenameTokenRemap(pParse, + pTriggerStep->pSrc->a[0].zName, + pTabList->a[0].zName + ); + } + } } } + + sqlite3SrcListDelete(db, pTabList); return pTriggerStep; } @@ -153140,7 +159396,7 @@ static TriggerStep *triggerStepAllocate( */ SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep( Parse *pParse, /* Parser */ - Token *pTableName, /* Name of the table into which we insert */ + SrcList *pTabList, /* Table to INSERT into */ IdList *pColumn, /* List of columns in pTableName to insert into */ Select *pSelect, /* A SELECT statement that supplies values */ u8 orconf, /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */ @@ -153153,7 +159409,7 @@ SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep( assert(pSelect != 0 || db->mallocFailed); - pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTableName,zStart,zEnd); + pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTabList, zStart, zEnd); if( pTriggerStep ){ if( IN_RENAME_OBJECT ){ pTriggerStep->pSelect = pSelect; @@ -153185,7 +159441,7 @@ SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep( */ SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep( Parse *pParse, /* Parser */ - Token *pTableName, /* Name of the table to be updated */ + SrcList *pTabList, /* Name of the table to be updated */ SrcList *pFrom, /* FROM clause for an UPDATE-FROM, or NULL */ ExprList *pEList, /* The SET clause: list of column and new values */ Expr *pWhere, /* The WHERE clause */ @@ -153196,21 +159452,36 @@ SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep( sqlite3 *db = pParse->db; TriggerStep *pTriggerStep; - pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTableName,zStart,zEnd); + pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTabList, zStart, zEnd); if( pTriggerStep ){ + SrcList *pFromDup = 0; if( IN_RENAME_OBJECT ){ pTriggerStep->pExprList = pEList; pTriggerStep->pWhere = pWhere; - pTriggerStep->pFrom = pFrom; + pFromDup = pFrom; pEList = 0; pWhere = 0; pFrom = 0; }else{ pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE); pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); - pTriggerStep->pFrom = sqlite3SrcListDup(db, pFrom, EXPRDUP_REDUCE); + pFromDup = sqlite3SrcListDup(db, pFrom, EXPRDUP_REDUCE); } pTriggerStep->orconf = orconf; + + if( pFromDup && !IN_RENAME_OBJECT){ + Select *pSub; + Token as = {0, 0}; + pSub = sqlite3SelectNew(pParse, 0, pFromDup, 0,0,0,0, SF_NestedFrom, 0); + pFromDup = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, &as, pSub ,0); + } + if( pFromDup && pTriggerStep->pSrc ){ + pTriggerStep->pSrc = sqlite3SrcListAppendList( + pParse, pTriggerStep->pSrc, pFromDup + ); + }else{ + sqlite3SrcListDelete(db, pFromDup); + } } sqlite3ExprListDelete(db, pEList); sqlite3ExprDelete(db, pWhere); @@ -153225,7 +159496,7 @@ SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep( */ SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep( Parse *pParse, /* Parser */ - Token *pTableName, /* The table from which rows are deleted */ + SrcList *pTabList, /* The table from which rows are deleted */ Expr *pWhere, /* The WHERE clause */ const char *zStart, /* Start of SQL text */ const char *zEnd /* End of SQL text */ @@ -153233,7 +159504,7 @@ SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep( sqlite3 *db = pParse->db; TriggerStep *pTriggerStep; - pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTableName,zStart,zEnd); + pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTabList, zStart, zEnd); if( pTriggerStep ){ if( IN_RENAME_OBJECT ){ pTriggerStep->pWhere = pWhere; @@ -153433,6 +159704,7 @@ static SQLITE_NOINLINE Trigger *triggersReallyExist( p = pList; if( (pParse->db->flags & SQLITE_EnableTrigger)==0 && pTab->pTrigger!=0 + && sqlite3SchemaToIndex(pParse->db, pTab->pTrigger->pSchema)!=1 ){ /* The SQLITE_DBCONFIG_ENABLE_TRIGGER setting is off. That means that ** only TEMP triggers are allowed. Truncate the pList so that it @@ -153495,52 +159767,6 @@ SQLITE_PRIVATE Trigger *sqlite3TriggersExist( return triggersReallyExist(pParse,pTab,op,pChanges,pMask); } -/* -** Convert the pStep->zTarget string into a SrcList and return a pointer -** to that SrcList. -** -** This routine adds a specific database name, if needed, to the target when -** forming the SrcList. This prevents a trigger in one database from -** referring to a target in another database. An exception is when the -** trigger is in TEMP in which case it can refer to any other database it -** wants. -*/ -SQLITE_PRIVATE SrcList *sqlite3TriggerStepSrc( - Parse *pParse, /* The parsing context */ - TriggerStep *pStep /* The trigger containing the target token */ -){ - sqlite3 *db = pParse->db; - SrcList *pSrc; /* SrcList to be returned */ - char *zName = sqlite3DbStrDup(db, pStep->zTarget); - pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); - assert( pSrc==0 || pSrc->nSrc==1 ); - assert( zName || pSrc==0 ); - if( pSrc ){ - Schema *pSchema = pStep->pTrig->pSchema; - pSrc->a[0].zName = zName; - if( pSchema!=db->aDb[1].pSchema ){ - assert( pSrc->a[0].fg.fixedSchema || pSrc->a[0].u4.zDatabase==0 ); - pSrc->a[0].u4.pSchema = pSchema; - pSrc->a[0].fg.fixedSchema = 1; - } - if( pStep->pFrom ){ - SrcList *pDup = sqlite3SrcListDup(db, pStep->pFrom, 0); - if( pDup && pDup->nSrc>1 && !IN_RENAME_OBJECT ){ - Select *pSubquery; - Token as; - pSubquery = sqlite3SelectNew(pParse,0,pDup,0,0,0,0,SF_NestedFrom,0); - as.n = 0; - as.z = 0; - pDup = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&as,pSubquery,0); - } - pSrc = sqlite3SrcListAppendList(pParse, pSrc, pDup); - } - }else{ - sqlite3DbFree(db, zName); - } - return pSrc; -} - /* ** Return true if the pExpr term from the RETURNING clause argument ** list is of the form "*". Raise an error if the terms if of the @@ -153686,7 +159912,11 @@ static void codeReturningTrigger( ExprList *pNew; Returning *pReturning; Select sSelect; - SrcList sFrom; + SrcList *pFrom; + union { + SrcList sSrc; + u8 fromSpace[SZ_SRCLIST_1]; + } uSrc; assert( v!=0 ); if( !pParse->bReturning ){ @@ -153695,19 +159925,21 @@ static void codeReturningTrigger( return; } assert( db->pParse==pParse ); - pReturning = pParse->u1.pReturning; + assert( !pParse->isCreate ); + pReturning = pParse->u1.d.pReturning; if( pTrigger != &(pReturning->retTrig) ){ /* This RETURNING trigger is for a different statement */ return; } memset(&sSelect, 0, sizeof(sSelect)); - memset(&sFrom, 0, sizeof(sFrom)); + memset(&uSrc, 0, sizeof(uSrc)); + pFrom = &uSrc.sSrc; sSelect.pEList = sqlite3ExprListDup(db, pReturning->pReturnEL, 0); - sSelect.pSrc = &sFrom; - sFrom.nSrc = 1; - sFrom.a[0].pSTab = pTab; - sFrom.a[0].zName = pTab->zName; /* tag-20240424-1 */ - sFrom.a[0].iCursor = -1; + sSelect.pSrc = pFrom; + pFrom->nSrc = 1; + pFrom->a[0].pSTab = pTab; + pFrom->a[0].zName = pTab->zName; /* tag-20240424-1 */ + pFrom->a[0].iCursor = -1; sqlite3SelectPrep(pParse, &sSelect, 0); if( pParse->nErr==0 ){ assert( db->mallocFailed==0 ); @@ -153800,7 +160032,7 @@ static int codeTriggerProgram( switch( pStep->op ){ case TK_UPDATE: { sqlite3Update(pParse, - sqlite3TriggerStepSrc(pParse, pStep), + sqlite3SrcListDup(db, pStep->pSrc, 0), sqlite3ExprListDup(db, pStep->pExprList, 0), sqlite3ExprDup(db, pStep->pWhere, 0), pParse->eOrconf, 0, 0, 0 @@ -153810,7 +160042,7 @@ static int codeTriggerProgram( } case TK_INSERT: { sqlite3Insert(pParse, - sqlite3TriggerStepSrc(pParse, pStep), + sqlite3SrcListDup(db, pStep->pSrc, 0), sqlite3SelectDup(db, pStep->pSelect, 0), sqlite3IdListDup(db, pStep->pIdList), pParse->eOrconf, @@ -153821,7 +160053,7 @@ static int codeTriggerProgram( } case TK_DELETE: { sqlite3DeleteFrom(pParse, - sqlite3TriggerStepSrc(pParse, pStep), + sqlite3SrcListDup(db, pStep->pSrc, 0), sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0 ); sqlite3VdbeAddOp0(v, OP_ResetCount); @@ -153886,7 +160118,7 @@ static TriggerPrg *codeRowTrigger( Table *pTab, /* The table pTrigger is attached to */ int orconf /* ON CONFLICT policy to code trigger program with */ ){ - Parse *pTop = sqlite3ParseToplevel(pParse); + Parse *pTop; /* Top level Parse object */ sqlite3 *db = pParse->db; /* Database handle */ TriggerPrg *pPrg; /* Value to return */ Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */ @@ -153895,10 +160127,24 @@ static TriggerPrg *codeRowTrigger( SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */ int iEndTrigger = 0; /* Label to jump to if WHEN is false */ Parse sSubParse; /* Parse context for sub-vdbe */ + int nDepth; /* Trigger depth */ + /* Ensure that triggers are not chained too deep. This test is linear + ** in the chaining depth, but sensible code ought not be chaining + ** triggers excessively, so that shouldn't be a problem. + */ + pTop = pParse; + for(nDepth=0; pTop->pOuterParse; pTop = pTop->pOuterParse, nDepth++){} + if( nDepth>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){ + sqlite3ErrorMsg(pParse, "triggers nested too deep"); + return 0; + } + + pTop = sqlite3ParseToplevel(pParse); assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) ); assert( pTop->pVdbe ); + /* Allocate the TriggerPrg and SubProgram objects. To ensure that they ** are freed if an error occurs, link them into the Parse.pTriggerPrg ** list of the top-level Parse object sooner rather than later. */ @@ -153925,6 +160171,8 @@ static TriggerPrg *codeRowTrigger( sSubParse.eTriggerOp = pTrigger->op; sSubParse.nQueryLoop = pParse->nQueryLoop; sSubParse.prepFlags = pParse->prepFlags; + sSubParse.oldmask = 0; + sSubParse.newmask = 0; v = sqlite3GetVdbe(&sSubParse); if( v ){ @@ -154057,7 +160305,7 @@ SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect( ** invocation is disallowed if (a) the sub-program is really a trigger, ** not a foreign key action, and (b) the flag to enable recursive triggers ** is clear. */ - sqlite3VdbeChangeP5(v, (u8)bRecursive); + sqlite3VdbeChangeP5(v, (u16)bRecursive); } } @@ -154272,26 +160520,37 @@ static void updateVirtualTable( ** integer. In that case, add an OP_RealAffinity opcode to make sure ** it has been converted into REAL. */ -SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){ +static SQLITE_NOINLINE void columnDefaultUncommonCase( + Vdbe *v, /* Byte code under construction */ + Table *pTab, /* The table */ + Column *pCol /* Which column of the table */ +){ + sqlite3_value *pValue = 0; + u8 enc = ENC(sqlite3VdbeDb(v)); + Parse *pParse = sqlite3VdbeParser(v); + assert( !IsView(pTab) ); + sqlite3ValueFromExpr(sqlite3VdbeDb(v), + sqlite3ColumnExprAuth(pTab,pCol,pParse), enc, + pCol->affinity, &pValue); + if( pValue ){ + sqlite3VdbeAppendP4(v, pValue, P4_MEM); + } +} +SQLITE_PRIVATE void sqlite3ColumnDefault( + Vdbe *v, /* Byte code under construction */ + Table *pTab, /* The table */ + int i, /* Which column of the table */ + int iReg /* Register in which results are stored */ +){ Column *pCol; assert( pTab!=0 ); assert( pTab->nCol>i ); pCol = &pTab->aCol[i]; if( pCol->iDflt ){ - sqlite3_value *pValue = 0; - u8 enc = ENC(sqlite3VdbeDb(v)); - assert( !IsView(pTab) ); - VdbeComment((v, "%s.%s", pTab->zName, pCol->zCnName)); - assert( i<pTab->nCol ); - sqlite3ValueFromExpr(sqlite3VdbeDb(v), - sqlite3ColumnExpr(pTab,pCol), enc, - pCol->affinity, &pValue); - if( pValue ){ - sqlite3VdbeAppendP4(v, pValue, P4_MEM); - } + columnDefaultUncommonCase(v,pTab,pCol); } #ifndef SQLITE_OMIT_FLOATING_POINT - if( pCol->affinity==SQLITE_AFF_REAL && !IsVirtual(pTab) ){ + if( pCol->affinity==SQLITE_AFF_REAL ){ sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); } #endif @@ -154679,38 +160938,32 @@ SQLITE_PRIVATE void sqlite3Update( */ chngRowid = chngPk = 0; for(i=0; i<pChanges->nExpr; i++){ - u8 hCol = sqlite3StrIHash(pChanges->a[i].zEName); /* If this is an UPDATE with a FROM clause, do not resolve expressions ** here. The call to sqlite3Select() below will do that. */ if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){ goto update_cleanup; } - for(j=0; j<pTab->nCol; j++){ - if( pTab->aCol[j].hName==hCol - && sqlite3StrICmp(pTab->aCol[j].zCnName, pChanges->a[i].zEName)==0 - ){ - if( j==pTab->iPKey ){ - chngRowid = 1; - pRowidExpr = pChanges->a[i].pExpr; - iRowidExpr = i; - }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){ - chngPk = 1; - } + j = sqlite3ColumnIndex(pTab, pChanges->a[i].zEName); + if( j>=0 ){ + if( j==pTab->iPKey ){ + chngRowid = 1; + pRowidExpr = pChanges->a[i].pExpr; + iRowidExpr = i; + }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){ + chngPk = 1; + } #ifndef SQLITE_OMIT_GENERATED_COLUMNS - else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){ - testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ); - testcase( pTab->aCol[j].colFlags & COLFLAG_STORED ); - sqlite3ErrorMsg(pParse, - "cannot UPDATE generated column \"%s\"", - pTab->aCol[j].zCnName); - goto update_cleanup; - } -#endif - aXRef[j] = i; - break; + else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){ + testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ); + testcase( pTab->aCol[j].colFlags & COLFLAG_STORED ); + sqlite3ErrorMsg(pParse, + "cannot UPDATE generated column \"%s\"", + pTab->aCol[j].zCnName); + goto update_cleanup; } - } - if( j>=pTab->nCol ){ +#endif + aXRef[j] = i; + }else{ if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zEName) ){ j = -1; chngRowid = 1; @@ -155112,6 +161365,7 @@ SQLITE_PRIVATE void sqlite3Update( sqlite3VdbeAddOp3(v, OP_Column, iEph, iRowidExpr, regNewRowid); } sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v); + sqlite3MayAbort(pParse); } /* Compute the old pre-UPDATE content of the row being changed, if that @@ -155903,7 +162157,8 @@ SQLITE_PRIVATE void sqlite3UpsertDoUpdate( /* excluded.* columns of type REAL need to be converted to a hard real */ for(i=0; i<pTab->nCol; i++){ if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){ - sqlite3VdbeAddOp1(v, OP_RealAffinity, pTop->regData+i); + int iStorage = pTop->regData + sqlite3TableColumnToStorage(pTab, i); + sqlite3VdbeAddOp1(v, OP_RealAffinity, iStorage); } } sqlite3Update(pParse, pSrc, sqlite3ExprListDup(db,pUpsert->pUpsertSet,0), @@ -156033,7 +162288,7 @@ SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm, Expr *pInto){ #else /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments ** to VACUUM are silently ignored. This is a back-out of a bug fix that - ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270). + ** occurred on 2016-08-19 (https://sqlite.org/src/info/083f9e6270). ** The buggy behavior is required for binary compatibility with some ** legacy applications. */ iDb = sqlite3FindDb(pParse->db, pNm); @@ -156112,7 +162367,8 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum( saved_nChange = db->nChange; saved_nTotalChange = db->nTotalChange; saved_mTrace = db->mTrace; - db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks; + db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_Comments + | SQLITE_AttachCreate | SQLITE_AttachWrite; db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum; db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_Defensive | SQLITE_CountRows); @@ -156146,9 +162402,11 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum( pDb = &db->aDb[nDb]; assert( strcmp(pDb->zDbSName,zDbVacuum)==0 ); pTemp = pDb->pBt; + nRes = sqlite3BtreeGetRequestedReserve(pMain); if( pOut ){ sqlite3_file *id = sqlite3PagerFile(sqlite3BtreePager(pTemp)); i64 sz = 0; + const char *zFilename; if( id->pMethods!=0 && (sqlite3OsFileSize(id, &sz)!=SQLITE_OK || sz>0) ){ rc = SQLITE_ERROR; sqlite3SetString(pzErrMsg, db, "output file already exists"); @@ -156160,8 +162418,16 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum( ** they are for the database being vacuumed, except that PAGER_CACHESPILL ** is always set. */ pgflags = db->aDb[iDb].safety_level | (db->flags & PAGER_FLAGS_MASK); + + /* If the VACUUM INTO target file is a URI filename and if the + ** "reserve=N" query parameter is present, reset the reserve to the + ** amount specified, if the amount is within range */ + zFilename = sqlite3BtreeGetFilename(pTemp); + if( ALWAYS(zFilename) ){ + int nNew = (int)sqlite3_uri_int64(zFilename, "reserve", nRes); + if( nNew>=0 && nNew<=255 ) nRes = nNew; + } } - nRes = sqlite3BtreeGetRequestedReserve(pMain); sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size); sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0)); @@ -156480,6 +162746,7 @@ SQLITE_API int sqlite3_drop_modules(sqlite3 *db, const char** azNames){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif + sqlite3_mutex_enter(db->mutex); for(pThis=sqliteHashFirst(&db->aModule); pThis; pThis=pNext){ Module *pMod = (Module*)sqliteHashData(pThis); pNext = sqliteHashNext(pThis); @@ -156490,6 +162757,7 @@ SQLITE_API int sqlite3_drop_modules(sqlite3 *db, const char** azNames){ } createModule(db, pMod->zName, 0, 0, 0); } + sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } @@ -156817,11 +163085,12 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ ** schema table. We just need to update that slot with all ** the information we've collected. ** - ** The VM register number pParse->regRowid holds the rowid of an + ** The VM register number pParse->u1.cr.regRowid holds the rowid of an ** entry in the sqlite_schema table that was created for this vtab ** by sqlite3StartTable(). */ iDb = sqlite3SchemaToIndex(db, pTab->pSchema); + assert( pParse->isCreate ); sqlite3NestedParse(pParse, "UPDATE %Q." LEGACY_SCHEMA_TABLE " " "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q " @@ -156830,7 +163099,7 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ pTab->zName, pTab->zName, zStmt, - pParse->regRowid + pParse->u1.cr.regRowid ); v = sqlite3GetVdbe(pParse); sqlite3ChangeCookie(pParse, iDb); @@ -157057,6 +163326,8 @@ SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){ if( rc!=SQLITE_OK ){ sqlite3ErrorMsg(pParse, "%s", zErr); pParse->rc = rc; + }else{ + sqlite3MarkAllShadowTablesOf(db, pTab); } sqlite3DbFree(db, zErr); } @@ -157168,7 +163439,9 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){ z = (const unsigned char*)zCreateTable; for(i=0; aKeyword[i]; i++){ int tokenType = 0; - do{ z += sqlite3GetToken(z, &tokenType); }while( tokenType==TK_SPACE ); + do{ + z += sqlite3GetToken(z, &tokenType); + }while( tokenType==TK_SPACE || tokenType==TK_COMMENT ); if( tokenType!=aKeyword[i] ){ sqlite3ErrorWithMsg(db, SQLITE_ERROR, "syntax error"); return SQLITE_ERROR; @@ -157614,9 +163887,12 @@ SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){ addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName)); addModuleArgument(pParse, pTab, 0); addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName)); + db->nSchemaLock++; rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr); + db->nSchemaLock--; if( rc ){ sqlite3ErrorMsg(pParse, "%s", zErr); + pParse->rc = rc; sqlite3DbFree(db, zErr); sqlite3VtabEponymousTableClear(db, pMod); } @@ -157639,6 +163915,17 @@ SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){ } } +/* +** Erase all eponymous virtual table instances associated with database +** handle db. +*/ +SQLITE_PRIVATE void sqlite3VtabEponymousTableClearAll(sqlite3 *db){ + HashElem *pElem; + for(pElem=sqliteHashFirst(&db->aModule); pElem; pElem=sqliteHashNext(pElem)){ + sqlite3VtabEponymousTableClear(db, (Module*)sqliteHashData(pElem)); + } +} + /* ** Return the ON CONFLICT resolution mode in effect for the virtual ** table update operation currently in progress. @@ -157812,6 +164099,7 @@ struct WhereLevel { int iTabCur; /* The VDBE cursor used to access the table */ int iIdxCur; /* The VDBE cursor used to access pIdx */ int addrBrk; /* Jump here to break out of the loop */ + int addrHalt; /* Abort the query due to empty table or similar */ int addrNxt; /* Jump here to start the next IN combination */ int addrSkip; /* Jump here for next iteration of skip-scan */ int addrCont; /* Jump here to continue with the next loop cycle */ @@ -157899,8 +164187,10 @@ struct WhereLoop { /**** whereLoopXfer() copies fields above ***********************/ # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot) u16 nLSlot; /* Number of slots allocated for aLTerm[] */ +#ifdef WHERETRACE_ENABLED LogEst rStarDelta; /* Cost delta due to star-schema heuristic. Not - ** initialized unless pWInfo->nOutStarDelta>0 */ + ** initialized unless pWInfo->bStarUsed */ +#endif WhereTerm **aLTerm; /* WhereTerms used */ WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */ WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */ @@ -157949,7 +164239,7 @@ struct WherePath { Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */ LogEst nRow; /* Estimated number of rows generated by this path */ LogEst rCost; /* Total cost of this path */ - LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */ + LogEst rUnsort; /* Total cost of this path ignoring sorting costs */ i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */ WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */ }; @@ -158015,6 +164305,9 @@ struct WhereTerm { u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */ int iParent; /* Disable pWC->a[iParent] when this term disabled */ int leftCursor; /* Cursor number of X in "X <op> <expr>" */ +#ifdef SQLITE_DEBUG + int iTerm; /* Which WhereTerm is this, for debug purposes */ +#endif union { struct { int leftColumn; /* Column number of X in "X <op> <expr>" */ @@ -158222,9 +164515,13 @@ struct WhereInfo { unsigned bDeferredSeek :1; /* Uses OP_DeferredSeek */ unsigned untestedTerms :1; /* Not all WHERE terms resolved by outer loop */ unsigned bOrderedInnerLoop:1;/* True if only the inner-most loop is ordered */ - unsigned sorted :1; /* True if really sorted (not just grouped) */ - LogEst nOutStarDelta; /* Artifical nOut reduction for star-query */ + unsigned sorted :1; /* True if really sorted (not just grouped) */ + unsigned bStarDone :1; /* True if check for star-query is complete */ + unsigned bStarUsed :1; /* True if star-query heuristic is used */ LogEst nRowOut; /* Estimated number of output rows */ +#ifdef WHERETRACE_ENABLED + LogEst rTotalCost; /* Total cost of the solution */ +#endif int iTop; /* The very beginning of the WHERE loop */ int iEndWhere; /* End of the WHERE clause itself */ WhereLoop *pLoops; /* List of all WhereLoop objects */ @@ -158232,9 +164529,14 @@ struct WhereInfo { Bitmask revMask; /* Mask of ORDER BY terms that need reversing */ WhereClause sWC; /* Decomposition of the WHERE clause */ WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */ - WhereLevel a[1]; /* Information about each nest loop in WHERE */ + WhereLevel a[FLEXARRAY]; /* Information about each nest loop in WHERE */ }; +/* +** The size (in bytes) of a WhereInfo object that holds N WhereLevels. +*/ +#define SZ_WHEREINFO(N) ROUND8(offsetof(WhereInfo,a)+(N)*sizeof(WhereLevel)) + /* ** Private interfaces - callable only by other where.c routines. ** @@ -158270,9 +164572,17 @@ SQLITE_PRIVATE int sqlite3WhereExplainBloomFilter( const WhereInfo *pWInfo, /* WHERE clause */ const WhereLevel *pLevel /* Bloom filter on this level */ ); +SQLITE_PRIVATE void sqlite3WhereAddExplainText( + Parse *pParse, /* Parse context */ + int addr, + SrcList *pTabList, /* Table list this loop refers to */ + WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ + u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ +); #else # define sqlite3WhereExplainOneScan(u,v,w,x) 0 # define sqlite3WhereExplainBloomFilter(u,v,w) 0 +# define sqlite3WhereAddExplainText(u,v,w,x,y) #endif /* SQLITE_OMIT_EXPLAIN */ #ifdef SQLITE_ENABLE_STMT_SCANSTATUS SQLITE_PRIVATE void sqlite3WhereAddScanStatus( @@ -158308,10 +164618,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*); SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*); SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*); SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, SrcItem*, WhereClause*); - - - - +SQLITE_PRIVATE int sqlite3WhereLoopBloomable(const WhereLoop*); /* ** Bitmasks for the operators on WhereTerm objects. These are all @@ -158474,38 +164781,37 @@ static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){ } /* -** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN -** command, or if stmt_scanstatus_v2() stats are enabled, or if SQLITE_DEBUG -** was defined at compile-time. If it is not a no-op, a single OP_Explain -** opcode is added to the output to describe the table scan strategy in pLevel. -** -** If an OP_Explain opcode is added to the VM, its address is returned. -** Otherwise, if no OP_Explain is coded, zero is returned. +** This function sets the P4 value of an existing OP_Explain opcode to +** text describing the loop in pLevel. If the OP_Explain opcode already has +** a P4 value, it is freed before it is overwritten. */ -SQLITE_PRIVATE int sqlite3WhereExplainOneScan( +SQLITE_PRIVATE void sqlite3WhereAddExplainText( Parse *pParse, /* Parse context */ + int addr, /* Address of OP_Explain opcode */ SrcList *pTabList, /* Table list this loop refers to */ WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ ){ - int ret = 0; #if !defined(SQLITE_DEBUG) if( sqlite3ParseToplevel(pParse)->explain==2 || IS_STMT_SCANSTATUS(pParse->db) ) #endif { + VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe, addr); SrcItem *pItem = &pTabList->a[pLevel->iFrom]; - Vdbe *v = pParse->pVdbe; /* VM being constructed */ sqlite3 *db = pParse->db; /* Database handle */ int isSearch; /* True for a SEARCH. False for SCAN. */ WhereLoop *pLoop; /* The controlling WhereLoop object */ u32 flags; /* Flags that describe this loop */ +#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN) char *zMsg; /* Text to add to EQP output */ +#endif StrAccum str; /* EQP output string */ char zBuf[100]; /* Initial space for EQP output string */ + if( db->mallocFailed ) return; + pLoop = pLevel->pWLoop; flags = pLoop->wsFlags; - if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0; isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) @@ -158513,7 +164819,10 @@ SQLITE_PRIVATE int sqlite3WhereExplainOneScan( sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); str.printfFlags = SQLITE_PRINTF_INTERNAL; - sqlite3_str_appendf(&str, "%s %S", isSearch ? "SEARCH" : "SCAN", pItem); + sqlite3_str_appendf(&str, "%s %S%s", + isSearch ? "SEARCH" : "SCAN", + pItem, + pItem->fg.fromExists ? " EXISTS" : ""); if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){ const char *zFmt = 0; Index *pIdx; @@ -158529,7 +164838,7 @@ SQLITE_PRIVATE int sqlite3WhereExplainOneScan( zFmt = "AUTOMATIC PARTIAL COVERING INDEX"; }else if( flags & WHERE_AUTO_INDEX ){ zFmt = "AUTOMATIC COVERING INDEX"; - }else if( flags & WHERE_IDX_ONLY ){ + }else if( flags & (WHERE_IDX_ONLY|WHERE_EXPRIDX) ){ zFmt = "COVERING INDEX %s"; }else{ zFmt = "INDEX %s"; @@ -158581,11 +164890,50 @@ SQLITE_PRIVATE int sqlite3WhereExplainOneScan( sqlite3_str_append(&str, " (~1 row)", 9); } #endif +#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN) zMsg = sqlite3StrAccumFinish(&str); sqlite3ExplainBreakpoint("",zMsg); - ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v), - pParse->addrExplain, pLoop->rRun, - zMsg, P4_DYNAMIC); +#endif + + assert( pOp->opcode==OP_Explain ); + assert( pOp->p4type==P4_DYNAMIC || pOp->p4.z==0 ); + sqlite3DbFree(db, pOp->p4.z); + pOp->p4type = P4_DYNAMIC; + pOp->p4.z = sqlite3StrAccumFinish(&str); + } +} + + +/* +** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN +** command, or if stmt_scanstatus_v2() stats are enabled, or if SQLITE_DEBUG +** was defined at compile-time. If it is not a no-op, a single OP_Explain +** opcode is added to the output to describe the table scan strategy in pLevel. +** +** If an OP_Explain opcode is added to the VM, its address is returned. +** Otherwise, if no OP_Explain is coded, zero is returned. +*/ +SQLITE_PRIVATE int sqlite3WhereExplainOneScan( + Parse *pParse, /* Parse context */ + SrcList *pTabList, /* Table list this loop refers to */ + WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ + u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ +){ + int ret = 0; +#if !defined(SQLITE_DEBUG) + if( sqlite3ParseToplevel(pParse)->explain==2 || IS_STMT_SCANSTATUS(pParse->db) ) +#endif + { + if( (pLevel->pWLoop->wsFlags & WHERE_MULTI_OR)==0 + && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 + ){ + Vdbe *v = pParse->pVdbe; + int addr = sqlite3VdbeCurrentAddr(v); + ret = sqlite3VdbeAddOp3( + v, OP_Explain, addr, pParse->addrExplain, pLevel->pWLoop->rRun + ); + sqlite3WhereAddExplainText(pParse, addr, pTabList, pLevel, wctrlFlags); + } } return ret; } @@ -158684,9 +165032,10 @@ SQLITE_PRIVATE void sqlite3WhereAddScanStatus( } }else{ int addr; + VdbeOp *pOp; assert( pSrclist->a[pLvl->iFrom].fg.isSubquery ); addr = pSrclist->a[pLvl->iFrom].u4.pSubq->addrFillSub; - VdbeOp *pOp = sqlite3VdbeGetOp(v, addr-1); + pOp = sqlite3VdbeGetOp(v, addr-1); assert( sqlite3VdbeDb(v)->mallocFailed || pOp->opcode==OP_InitCoroutine ); assert( sqlite3VdbeDb(v)->mallocFailed || pOp->p2>addr ); sqlite3VdbeScanStatusRange(v, addrExplain, addr, pOp->p2-1); @@ -158866,7 +165215,7 @@ static void adjustOrderByCol(ExprList *pOrderBy, ExprList *pEList){ /* ** pX is an expression of the form: (vector) IN (SELECT ...) ** In other words, it is a vector IN operator with a SELECT clause on the -** LHS. But not all terms in the vector are indexable and the terms might +** RHS. But not all terms in the vector are indexable and the terms might ** not be in the correct order for indexing. ** ** This routine makes a copy of the input pX expression and then adjusts @@ -158909,6 +165258,7 @@ static Expr *removeUnindexableInClauseTerms( ExprList *pRhs = 0; /* New RHS after modifications */ ExprList *pLhs = 0; /* New LHS after mods */ int i; /* Loop counter */ + int nRhs = 0; /* Number of RHS terms added so far */ assert( ExprUseXSelect(pNew) ); pOrigRhs = pSelect->pEList; @@ -158922,7 +165272,12 @@ static Expr *removeUnindexableInClauseTerms( int iField; assert( (pLoop->aLTerm[i]->eOperator & (WO_OR|WO_AND))==0 ); iField = pLoop->aLTerm[i]->u.x.iField - 1; - if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */ + if( iField!=nRhs ){ + ExprClearProperty(pNew, EP_Subrtn); + } + if( NEVER(pOrigRhs->a[iField].pExpr==0) ){ + continue; /* Duplicate PK column */ + } pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr); pOrigRhs->a[iField].pExpr = 0; if( pRhs ) pRhs->a[pRhs->nExpr-1].u.x.iOrderByCol = iField+1; @@ -158931,6 +165286,7 @@ static Expr *removeUnindexableInClauseTerms( pLhs = sqlite3ExprListAppend(pParse,pLhs,pOrigLhs->a[iField].pExpr); pOrigLhs->a[iField].pExpr = 0; } + nRhs++; } } sqlite3ExprListDelete(db, pOrigRhs); @@ -158939,6 +165295,7 @@ static Expr *removeUnindexableInClauseTerms( pNew->pLeft->x.pList = pLhs; } pSelect->pEList = pRhs; + pSelect->selId = ++pParse->nSelect; /* Req'd for SubrtnSig validity */ if( pLhs && pLhs->nExpr==1 ){ /* Take care here not to generate a TK_VECTOR containing only a ** single value. Since the parser never creates such a vector, some @@ -159018,7 +165375,7 @@ static SQLITE_NOINLINE void codeINTerm( return; } } - for(i=iEq;i<pLoop->nLTerm; i++){ + for(i=iEq; i<pLoop->nLTerm; i++){ assert( pLoop->aLTerm[i]!=0 ); if( pLoop->aLTerm[i]->pExpr==pX ) nEq++; } @@ -159027,22 +165384,25 @@ static SQLITE_NOINLINE void codeINTerm( if( !ExprUseXSelect(pX) || pX->x.pSelect->pEList->nExpr==1 ){ eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab); }else{ - Expr *pExpr = pTerm->pExpr; - if( pExpr->iTable==0 || !ExprHasProperty(pExpr, EP_Subrtn) ){ - sqlite3 *db = pParse->db; - pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX); - if( !db->mallocFailed ){ - aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq); - eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap,&iTab); - pExpr->iTable = iTab; - } - sqlite3ExprDelete(db, pX); - }else{ - int n = sqlite3ExprVectorSize(pX->pLeft); - aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*MAX(nEq,n)); - eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab); + sqlite3 *db = pParse->db; + Expr *pXMod = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX); + if( nEq>1 ){ + /* If this IN(SELECT ...) expression drives more than one column of + ** the index, disable the seek-scan optimization. The reasons for this + ** are that (a) it is only possible to make this happen by populating + ** the sqlite_stat1 table with inconsistent information, and (b) it + ** would require sqlite3FindInIndex() to find an index that is not + ** only unique for the columns in question, but also delivers them + ** in sorted order (requires checking asc/desc, and rejecting cases + ** where the indexed columns are not in the right order). */ + pLoop->wsFlags &= ~WHERE_IN_SEEKSCAN; + } + if( !db->mallocFailed ){ + int nCol = pX->x.pSelect->pEList->nExpr; + aiMap = (int*)sqlite3DbMallocZero(db, sizeof(int)*nCol); + eType = sqlite3FindInIndex(pParse, pXMod, IN_INDEX_LOOP, 0, aiMap, &iTab); } - pX = pExpr; + sqlite3ExprDelete(db, pXMod); } if( eType==IN_INDEX_INDEX_DESC ){ @@ -159072,7 +165432,7 @@ static SQLITE_NOINLINE void codeINTerm( if( pIn ){ int iMap = 0; /* Index in aiMap[] */ pIn += i; - for(i=iEq;i<pLoop->nLTerm; i++){ + for(i=iEq; i<pLoop->nLTerm; i++){ if( pLoop->aLTerm[i]->pExpr==pX ){ int iOut = iTarget + i - iEq; if( eType==IN_INDEX_ROWID ){ @@ -159286,12 +165646,7 @@ static int codeAllEqualityTerms( testcase( pTerm->wtFlags & TERM_VIRTUAL ); r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); if( r1!=regBase+j ){ - if( nReg==1 ){ - sqlite3ReleaseTempReg(pParse, regBase); - regBase = r1; - }else{ - sqlite3VdbeAddOp2(v, OP_Copy, r1, regBase+j); - } + sqlite3VdbeAddOp2(v, OP_Copy, r1, regBase+j); } if( pTerm->eOperator & WO_IN ){ if( pTerm->pExpr->flags & EP_xIsSelect ){ @@ -159723,6 +166078,7 @@ static SQLITE_NOINLINE void filterPullDown( int addrNxt, /* Jump here to bypass inner loops */ Bitmask notReady /* Loops that are not ready */ ){ + int saved_addrBrk; while( ++iLevel < pWInfo->nLevel ){ WhereLevel *pLevel = &pWInfo->a[iLevel]; WhereLoop *pLoop = pLevel->pWLoop; @@ -159731,7 +166087,7 @@ static SQLITE_NOINLINE void filterPullDown( /* ,--- Because sqlite3ConstructBloomFilter() has will not have set ** vvvvv--' pLevel->regFilter if this were true. */ if( NEVER(pLoop->prereq & notReady) ) continue; - assert( pLevel->addrBrk==0 ); + saved_addrBrk = pLevel->addrBrk; pLevel->addrBrk = addrNxt; if( pLoop->wsFlags & WHERE_IPK ){ WhereTerm *pTerm = pLoop->aLTerm[0]; @@ -159743,6 +166099,7 @@ static SQLITE_NOINLINE void filterPullDown( regRowid = codeEqualityTerm(pParse, pTerm, pLevel, 0, 0, regRowid); sqlite3VdbeAddOp2(pParse->pVdbe, OP_MustBeInt, regRowid, addrNxt); VdbeCoverage(pParse->pVdbe); + assert( sqlite3WhereLoopBloomable(pLoop) ); sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter, addrNxt, regRowid, 1); VdbeCoverage(pParse->pVdbe); @@ -159756,12 +166113,13 @@ static SQLITE_NOINLINE void filterPullDown( r1 = codeAllEqualityTerms(pParse,pLevel,0,0,&zStartAff); codeApplyAffinity(pParse, r1, nEq, zStartAff); sqlite3DbFree(pParse->db, zStartAff); + assert( sqlite3WhereLoopBloomable(pLoop) ); sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter, addrNxt, r1, nEq); VdbeCoverage(pParse->pVdbe); } pLevel->regFilter = 0; - pLevel->addrBrk = 0; + pLevel->addrBrk = saved_addrBrk; } } @@ -159786,6 +166144,49 @@ static int whereLoopIsOneRow(WhereLoop *pLoop){ return 0; } +/* +** This is called while coding loop pLevel, which scans FROM clause item +** pTabItem. pE is an expression for which all the prerequisites are +** available. This function tests if pE can be coded as part of the current +** loop, or whether it needs to be deferred to ensure outer joins are +** processed correctly. This function returns non-zero if the expression +** can be coded as part of the loop, or 0 if it must be deferred. +** +** The expression must be deferred if: +** +** * There are any RIGHT joins in the FROM clause and the expression +** was not part of an ON clause, or was part of an ON clause to the +** right of the join. +** +** * The table is the RHS of a LEFT JOIN and the expression was not +** part of an ON clause on an OUTER join, or was part of an ON clause +** on an OUTER join to the right of the join. +*/ +static int whereExprIsReady( + WhereInfo *pWInfo, + WhereLevel *pLevel, + SrcItem *pTabItem, + Expr *pE +){ + u8 jtype = pTabItem->fg.jointype; + if( jtype & (JT_LEFT|JT_LTORJ|JT_RIGHT) ){ + if( !ExprHasProperty(pE,EP_OuterON|EP_InnerON) ){ + /* Defer processing WHERE clause constraints until after outer + ** join processing. tag-20220513a */ + return 0; + }else if( (jtype & JT_LEFT) && !ExprHasProperty(pE,EP_OuterON) ){ + return 0; + }else{ + Bitmask m = sqlite3WhereGetMask(&pWInfo->sMaskSet, pE->w.iJoin); + if( m & pLevel->notReady ){ + /* An ON clause that is not ripe */ + return 0; + } + } + } + return 1; +} + /* ** Generate code for the start of the iLevel-th loop in the WHERE clause ** implementation described by pWInfo. @@ -159808,7 +166209,6 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( sqlite3 *db; /* Database connection */ SrcItem *pTabItem; /* FROM clause term being coded */ int addrBrk; /* Jump here to break out of the loop */ - int addrHalt; /* addrBrk for the outermost loop */ int addrCont; /* Jump here to continue with next cycle */ int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ int iReleaseReg = 0; /* Temp register to free before returning */ @@ -159852,7 +166252,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( ** there are no IN operators in the constraints, the "addrNxt" label ** is the same as "addrBrk". */ - addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse); + addrBrk = pLevel->addrNxt = pLevel->addrBrk; addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse); /* If this is the right table of a LEFT OUTER JOIN, allocate and @@ -159866,16 +166266,11 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( pLevel->iLeftJoin = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); VdbeComment((v, "init LEFT JOIN match flag")); + if( pTabItem->fg.viaCoroutine ){ + sqlite3VdbeAddOp2(v, OP_NullRow, pTabItem->iCursor, 1); + } } - /* Compute a safe address to jump to if we discover that the table for - ** this loop is empty and can never contribute content. */ - for(j=iLevel; j>0; j--){ - if( pWInfo->a[j].iLeftJoin ) break; - if( pWInfo->a[j].pRJ ) break; - } - addrHalt = pWInfo->a[j].addrBrk; - /* Special case of a FROM clause subquery implemented as a co-routine */ if( pTabItem->fg.viaCoroutine ){ int regYield; @@ -159909,7 +166304,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( if( SMASKBIT32(j) & pLoop->u.vtab.mHandleIn ){ int iTab = pParse->nTab++; int iCache = ++pParse->nMem; - sqlite3CodeRhsOfIN(pParse, pTerm->pExpr, iTab); + sqlite3CodeRhsOfIN(pParse, pTerm->pExpr, iTab, 0); sqlite3VdbeAddOp3(v, OP_VInitIn, iTab, iTarget, iCache); }else{ codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); @@ -159931,6 +166326,9 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( } sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); + /* The instruction immediately prior to OP_VFilter must be an OP_Integer + ** that sets the "argc" value for xVFilter. This is necessary for + ** resolveP2() to work correctly. See tag-20250207a. */ sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pLoop->u.vtab.idxStr, pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC); @@ -160111,7 +166509,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( VdbeCoverageIf(v, pX->op==TK_GE); sqlite3ReleaseTempReg(pParse, rTemp); }else{ - sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt); + sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, pLevel->addrHalt); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); } @@ -160151,36 +166549,36 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); } }else if( pLoop->wsFlags & WHERE_INDEXED ){ - /* Case 4: A scan using an index. + /* Case 4: Search using an index. ** - ** The WHERE clause may contain zero or more equality - ** terms ("==" or "IN" operators) that refer to the N - ** left-most columns of the index. It may also contain - ** inequality constraints (>, <, >= or <=) on the indexed - ** column that immediately follows the N equalities. Only - ** the right-most column can be an inequality - the rest must - ** use the "==" and "IN" operators. For example, if the - ** index is on (x,y,z), then the following clauses are all - ** optimized: + ** The WHERE clause may contain zero or more equality + ** terms ("==" or "IN" or "IS" operators) that refer to the N + ** left-most columns of the index. It may also contain + ** inequality constraints (>, <, >= or <=) on the indexed + ** column that immediately follows the N equalities. Only + ** the right-most column can be an inequality - the rest must + ** use the "==", "IN", or "IS" operators. For example, if the + ** index is on (x,y,z), then the following clauses are all + ** optimized: ** - ** x=5 - ** x=5 AND y=10 - ** x=5 AND y<10 - ** x=5 AND y>5 AND y<10 - ** x=5 AND y=5 AND z<=10 + ** x=5 + ** x=5 AND y=10 + ** x=5 AND y<10 + ** x=5 AND y>5 AND y<10 + ** x=5 AND y=5 AND z<=10 ** - ** The z<10 term of the following cannot be used, only - ** the x=5 term: + ** The z<10 term of the following cannot be used, only + ** the x=5 term: ** - ** x=5 AND z<10 + ** x=5 AND z<10 ** - ** N may be zero if there are inequality constraints. - ** If there are no inequality constraints, then N is at - ** least one. + ** N may be zero if there are inequality constraints. + ** If there are no inequality constraints, then N is at + ** least one. ** - ** This case is also used when there are no WHERE clause - ** constraints but an index is selected anyway, in order - ** to force the output order to conform to an ORDER BY. + ** This case is also used when there are no WHERE clause + ** constraints but an index is selected anyway, in order + ** to force the output order to conform to an ORDER BY. */ static const u8 aStartOp[] = { 0, @@ -160365,6 +166763,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( VdbeComment((v, "NULL-scan pass ctr")); } if( pLevel->regFilter ){ + assert( sqlite3WhereLoopBloomable(pLoop) ); sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt, regBase, nEq); VdbeCoverage(v); @@ -160521,12 +166920,13 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( if( pLevel->iLeftJoin==0 ){ /* If a partial index is driving the loop, try to eliminate WHERE clause ** terms from the query that must be true due to the WHERE clause of - ** the partial index. + ** the partial index. This optimization does not work on an outer join, + ** as shown by: ** - ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work - ** for a LEFT JOIN. + ** 2019-11-02 ticket 623eff57e76d45f6 (LEFT JOIN) + ** 2025-05-29 forum post 7dee41d32506c4ae (RIGHT JOIN) */ - if( pIdx->pPartIdxWhere ){ + if( pIdx->pPartIdxWhere && pLevel->pRJ==0 ){ whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC); } }else{ @@ -160629,12 +167029,11 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). */ - if( pWInfo->nLevel>1 ){ + if( pWInfo->nLevel>1 || pTabItem->fg.fromExists ){ int nNotReady; /* The number of notReady tables */ SrcItem *origSrc; /* Original list of tables */ nNotReady = pWInfo->nLevel - iLevel - 1; - pOrTab = sqlite3DbMallocRawNN(db, - sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); + pOrTab = sqlite3DbMallocRawNN(db, SZ_SRCLIST(nNotReady+1)); if( pOrTab==0 ) return notReady; pOrTab->nAlloc = (u8)(nNotReady + 1); pOrTab->nSrc = pOrTab->nAlloc; @@ -160643,6 +167042,13 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( for(k=1; k<=nNotReady; k++){ memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); } + + /* Clear the fromExists flag on the OR-optimized table entry so that + ** the calls to sqlite3WhereEnd() do not code early-exits after the + ** first row is visited. The early exit applies to this table's + ** overall loop - including the multiple OR branches and any WHERE + ** conditions not passed to the sub-loops - not to the sub-loops. */ + pOrTab->a[0].fg.fromExists = 0; }else{ pOrTab = pWInfo->pTabList; } @@ -160685,7 +167091,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( ** ** This optimization also only applies if the (x1 OR x2 OR ...) term ** is not contained in the ON clause of a LEFT JOIN. - ** See ticket http://www.sqlite.org/src/info/f2369304e4 + ** See ticket http://sqlite.org/src/info/f2369304e4 ** ** 2022-02-04: Do not push down slices of a row-value comparison. ** In other words, "w" or "y" may not be a slice of a vector. Otherwise, @@ -160714,6 +167120,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( } if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; if( ExprHasProperty(pExpr, EP_Subquery) ) continue; /* tag-20220303a */ + if( whereExprIsReady(pWInfo, pLevel, pTabItem, pExpr)==0 ) continue; pExpr = sqlite3ExprDup(db, pExpr, 0); pAndExpr = sqlite3ExprAnd(pParse, pAndExpr, pExpr); } @@ -160886,7 +167293,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( assert( pLevel->op==OP_Return ); pLevel->p2 = sqlite3VdbeCurrentAddr(v); - if( pWInfo->nLevel>1 ){ sqlite3DbFreeNN(db, pOrTab); } + if( pWInfo->pTabList!=pOrTab ){ sqlite3DbFreeNN(db, pOrTab); } if( !untestedTerms ) disableTerm(pLevel, pTerm); }else #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ @@ -160906,7 +167313,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( codeCursorHint(pTabItem, pWInfo, pLevel, 0); pLevel->op = aStep[bRev]; pLevel->p1 = iCur; - pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt); + pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev],iCur,pLevel->addrHalt); VdbeCoverageIf(v, bRev==0); VdbeCoverageIf(v, bRev!=0); pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; @@ -160954,22 +167361,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( } pE = pTerm->pExpr; assert( pE!=0 ); - if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT) ){ - if( !ExprHasProperty(pE,EP_OuterON|EP_InnerON) ){ - /* Defer processing WHERE clause constraints until after outer - ** join processing. tag-20220513a */ - continue; - }else if( (pTabItem->fg.jointype & JT_LEFT)==JT_LEFT - && !ExprHasProperty(pE,EP_OuterON) ){ - continue; - }else{ - Bitmask m = sqlite3WhereGetMask(&pWInfo->sMaskSet, pE->w.iJoin); - if( m & pLevel->notReady ){ - /* An ON clause that is not ripe */ - continue; - } - } - } + if( whereExprIsReady(pWInfo, pLevel, pTabItem, pE)==0 ) continue; if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){ iNext = 2; continue; @@ -161043,6 +167435,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( WO_EQ|WO_IN|WO_IS, 0); if( pAlt==0 ) continue; if( pAlt->wtFlags & (TERM_CODED) ) continue; + if( ExprHasProperty(pAlt->pExpr, EP_Collate) ) continue; if( (pAlt->eOperator & WO_IN) && ExprUseXSelect(pAlt->pExpr) && (pAlt->pExpr->x.pSelect->pEList->nExpr>1) @@ -161094,8 +167487,10 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( VdbeComment((v, "match against %s", pTab->zName)); sqlite3VdbeAddOp3(v, OP_MakeRecord, r+1, nPk, r); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pRJ->iMatch, r, r+1, nPk); - sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pRJ->regBloom, 0, r+1, nPk); - sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + if( pRJ->regBloom ){ + sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pRJ->regBloom, 0, r+1, nPk); + sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + } sqlite3VdbeJumpHere(v, jmp1); sqlite3ReleaseTempRange(pParse, r, nPk+1); } @@ -161119,9 +167514,11 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( ** loop will run that invokes this subroutine for unmatched rows ** of pTab, with all tables to left begin set to NULL. */ - WhereRightJoin *pRJ = pLevel->pRJ; - sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pRJ->regReturn); - pRJ->addrSubrtn = sqlite3VdbeCurrentAddr(v); + { + WhereRightJoin *pRJ = pLevel->pRJ; + sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pRJ->regReturn); + pRJ->addrSubrtn = sqlite3VdbeCurrentAddr(v); + } assert( pParse->withinRJSubrtn < 255 ); pParse->withinRJSubrtn++; @@ -161177,7 +167574,11 @@ SQLITE_PRIVATE SQLITE_NOINLINE void sqlite3WhereRightJoinLoop( WhereInfo *pSubWInfo; WhereLoop *pLoop = pLevel->pWLoop; SrcItem *pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; - SrcList sFrom; + SrcList *pFrom; + union { + SrcList sSrc; + u8 fromSpace[SZ_SRCLIST_1]; + } uSrc; Bitmask mAll = 0; int k; @@ -161221,21 +167622,39 @@ SQLITE_PRIVATE SQLITE_NOINLINE void sqlite3WhereRightJoinLoop( sqlite3ExprDup(pParse->db, pTerm->pExpr, 0)); } } - sFrom.nSrc = 1; - sFrom.nAlloc = 1; - memcpy(&sFrom.a[0], pTabItem, sizeof(SrcItem)); - sFrom.a[0].fg.jointype = 0; - assert( pParse->withinRJSubrtn < 100 ); + if( pLevel->iIdxCur ){ + /* pSubWhere may contain expressions that read from an index on the + ** table on the RHS of the right join. All such expressions first test + ** if the index is pointing at a NULL row, and if so, read from the + ** table cursor instead. So ensure that the index cursor really is + ** pointing at a NULL row here, so that no values are read from it during + ** the scan of the RHS of the RIGHT join below. */ + sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); + } + pFrom = &uSrc.sSrc; + pFrom->nSrc = 1; + pFrom->nAlloc = 1; + memcpy(&pFrom->a[0], pTabItem, sizeof(SrcItem)); + pFrom->a[0].fg.jointype = 0; + if( pParse->withinRJSubrtn >= 100 ){ + /* This limit --------------^^^ + ** is based on an historical assert(). It is not compile-time or + ** run-time configurable. It could perhaps be raised as high as 254, + ** but only an attack robot would ever do even 100 RIGHT JOINS within + ** a single query, so we'll just leave it as it is. */ + sqlite3ErrorMsg(pParse, "too many RIGHT JOINs"); + return; + } pParse->withinRJSubrtn++; - pSubWInfo = sqlite3WhereBegin(pParse, &sFrom, pSubWhere, 0, 0, 0, + pSubWInfo = sqlite3WhereBegin(pParse, pFrom, pSubWhere, 0, 0, 0, WHERE_RIGHT_JOIN, 0); if( pSubWInfo ){ - int iCur = pLevel->iTabCur; - int r = ++pParse->nMem; - int nPk; - int jmp; + int iCur = pLevel->iTabCur; /* Table on RHS of RIGHT JOIN &*/ + int r = ++pParse->nMem; /* Register range to hold primary key */ + int nPk; /* Number of values in the primary key */ + int r2; /* Register holding record for primary key */ int addrCont = sqlite3WhereContinueLabel(pSubWInfo); - Table *pTab = pTabItem->pSTab; + Table *pTab = pTabItem->pSTab; /* Table on RHS of RIGHT JOIN */ if( HasRowid(pTab) ){ sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, r); nPk = 1; @@ -161249,11 +167668,31 @@ SQLITE_PRIVATE SQLITE_NOINLINE void sqlite3WhereRightJoinLoop( sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk); } } - jmp = sqlite3VdbeAddOp4Int(v, OP_Filter, pRJ->regBloom, 0, r, nPk); - VdbeCoverage(v); + + /* Generate code that checks to see if the current row of the RHS table + ** has appeared in any prior output row. */ + if( pRJ->regBloom ){ + sqlite3VdbeAddOp4Int(v, OP_Filter, pRJ->regBloom, + sqlite3VdbeCurrentAddr(v)+2, r, nPk); + VdbeCoverage(v); + } sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, addrCont, r, nPk); VdbeCoverage(v); - sqlite3VdbeJumpHere(v, jmp); + r2 = sqlite3GetTempReg(pParse); + + /* Generate code that inserts the PK of the RHS table into the + ** pRH->iMatch index to indicate that the current row has appeared + ** in the output set. */ + sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, r2); + sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pRJ->iMatch, r2, r, nPk); + sqlite3ReleaseTempReg(pParse, r2); + if( pRJ->regBloom ){ + sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pRJ->regBloom, 0, r, nPk); + sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); + } + + /* Invoke the subroutine that actually puts the current RHS table row + ** into the output set, with NULLs for the LHS. */ sqlite3VdbeAddOp2(v, OP_Gosub, pRJ->regReturn, pRJ->addrSubrtn); sqlite3WhereEnd(pSubWInfo); } @@ -161479,19 +167918,19 @@ static int isLikeOrGlob( if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){ z = sqlite3_value_text(pVal); } - sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); + sqlite3VdbeReprepareOnBind(pParse->pVdbe, iCol, 0); assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER ); }else if( op==TK_STRING ){ assert( !ExprHasProperty(pRight, EP_IntValue) ); z = (u8*)pRight->u.zToken; } if( z ){ - /* Count the number of prefix bytes prior to the first wildcard. - ** or U+fffd character. If the underlying database has a UTF16LE - ** encoding, then only consider ASCII characters. Note that the - ** encoding of z[] is UTF8 - we are dealing with only UTF8 here in - ** this code, but the database engine itself might be processing - ** content using a different encoding. */ + /* Count the number of prefix bytes prior to the first wildcard, + ** U+fffd character, or malformed utf-8. If the underlying database + ** has a UTF16LE encoding, then only consider ASCII characters. Note that + ** the encoding of z[] is UTF8 - we are dealing with only UTF8 here in this + ** code, but the database engine itself might be processing content using a + ** different encoding. */ cnt = 0; while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; @@ -161499,7 +167938,9 @@ static int isLikeOrGlob( cnt++; }else if( c>=0x80 ){ const u8 *z2 = z+cnt-1; - if( sqlite3Utf8Read(&z2)==0xfffd || ENC(db)==SQLITE_UTF16LE ){ + if( c==0xff || sqlite3Utf8Read(&z2)==0xfffd /* bad utf-8 */ + || ENC(db)==SQLITE_UTF16LE + ){ cnt--; break; }else{ @@ -161558,13 +167999,14 @@ static int isLikeOrGlob( ){ int isNum; double rDummy; - isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8); + assert( zNew[iTo]==0 ); + isNum = sqlite3AtoF(zNew, &rDummy); if( isNum<=0 ){ if( iTo==1 && zNew[0]=='-' ){ isNum = +1; }else{ zNew[iTo-1]++; - isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8); + isNum = sqlite3AtoF(zNew, &rDummy); zNew[iTo-1]--; } } @@ -161581,7 +168023,7 @@ static int isLikeOrGlob( ** reprepare the statement when that parameter is rebound */ if( op==TK_VARIABLE ){ Vdbe *v = pParse->pVdbe; - sqlite3VdbeSetVarmask(v, pRight->iColumn); + sqlite3VdbeReprepareOnBind(v, pRight->iColumn, 0); assert( !ExprHasProperty(pRight, EP_IntValue) ); if( *pisComplete && pRight->u.zToken[1] ){ /* If the rhs of the LIKE expression is a variable, and the current @@ -161607,6 +168049,34 @@ static int isLikeOrGlob( } #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ +/* +** If pExpr is one of "like", "glob", "match", or "regexp", then +** return the corresponding SQLITE_INDEX_CONSTRAINT_xxxx value. +** If not, return 0. +** +** pExpr is guaranteed to be a TK_FUNCTION. +*/ +SQLITE_PRIVATE int sqlite3ExprIsLikeOperator(const Expr *pExpr){ + static const struct { + const char *zOp; + unsigned char eOp; + } aOp[] = { + { "match", SQLITE_INDEX_CONSTRAINT_MATCH }, + { "glob", SQLITE_INDEX_CONSTRAINT_GLOB }, + { "like", SQLITE_INDEX_CONSTRAINT_LIKE }, + { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP } + }; + int i; + assert( pExpr->op==TK_FUNCTION ); + assert( !ExprHasProperty(pExpr, EP_IntValue) ); + for(i=0; i<ArraySize(aOp); i++){ + if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){ + return aOp[i].eOp; + } + } + return 0; +} + #ifndef SQLITE_OMIT_VIRTUALTABLE /* @@ -161643,15 +168113,6 @@ static int isAuxiliaryVtabOperator( Expr **ppRight /* Expression to left of MATCH/op2 */ ){ if( pExpr->op==TK_FUNCTION ){ - static const struct Op2 { - const char *zOp; - unsigned char eOp2; - } aOp[] = { - { "match", SQLITE_INDEX_CONSTRAINT_MATCH }, - { "glob", SQLITE_INDEX_CONSTRAINT_GLOB }, - { "like", SQLITE_INDEX_CONSTRAINT_LIKE }, - { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP } - }; ExprList *pList; Expr *pCol; /* Column reference */ int i; @@ -161671,16 +168132,11 @@ static int isAuxiliaryVtabOperator( */ pCol = pList->a[1].pExpr; assert( pCol->op!=TK_COLUMN || (ExprUseYTab(pCol) && pCol->y.pTab!=0) ); - if( ExprIsVtab(pCol) ){ - for(i=0; i<ArraySize(aOp); i++){ - assert( !ExprHasProperty(pExpr, EP_IntValue) ); - if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){ - *peOp2 = aOp[i].eOp2; - *ppRight = pList->a[0].pExpr; - *ppLeft = pCol; - return 1; - } - } + if( ExprIsVtab(pCol) && (i = sqlite3ExprIsLikeOperator(pExpr))!=0 ){ + *peOp2 = i; + *ppRight = pList->a[0].pExpr; + *ppLeft = pCol; + return 1; } /* We can also match against the first column of overloaded @@ -161765,7 +168221,10 @@ static void transferJoinMarkings(Expr *pDerived, Expr *pBase){ static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){ pWC->a[iChild].iParent = iParent; pWC->a[iChild].truthProb = pWC->a[iParent].truthProb; + assert( pWC->a[iParent].nChild < UMXV(pWC->a[0].nChild) ); pWC->a[iParent].nChild++; + testcase( pWC->a[iParent].nChild == UMXV(pWC->a[0].nChild) ); + } /* @@ -161814,16 +168273,22 @@ static void whereCombineDisjuncts( Expr *pNew; /* New virtual expression */ int op; /* Operator for the combined expression */ int idxNew; /* Index in pWC of the next virtual term */ + Expr *pA, *pB; /* Expressions associated with pOne and pTwo */ if( (pOne->wtFlags | pTwo->wtFlags) & TERM_VNULL ) return; if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return; - assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 ); - assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 ); - if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return; - if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return; + pA = pOne->pExpr; + pB = pTwo->pExpr; + assert( pA->pLeft!=0 && pA->pRight!=0 ); + assert( pB->pLeft!=0 && pB->pRight!=0 ); + if( sqlite3ExprCompare(0,pA->pLeft, pB->pLeft, -1) ) return; + if( sqlite3ExprCompare(0,pA->pRight, pB->pRight,-1) ) return; + if( ExprHasProperty(pA,EP_Commuted)!=ExprHasProperty(pB,EP_Commuted) ){ + return; + } /* If we reach this point, it means the two subterms can be combined */ if( (eOp & (eOp-1))!=0 ){ if( eOp & (WO_LT|WO_LE) ){ @@ -161834,7 +168299,7 @@ static void whereCombineDisjuncts( } } db = pWC->pWInfo->pParse->db; - pNew = sqlite3ExprDup(db, pOne->pExpr, 0); + pNew = sqlite3ExprDup(db, pA, 0); if( pNew==0 ) return; for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); } pNew->op = op; @@ -162148,29 +168613,58 @@ static void exprAnalyzeOrTerm( } } - /* At this point, okToChngToIN is true if original pTerm satisfies - ** case 1. In that case, construct a new virtual term that is - ** pTerm converted into an IN operator. + /* At this point, okToChngToIN is true if original pTerm is a + ** candidate to satisfy case 1, though we are not yet certain that + ** the collating sequences are all compatible. Try to construct a + ** new virtual term that is pTerm converted from an OR operator + ** into an IN operator. + ** + ** During construction, verify that the collating sequences on all + ** subterms of the OR are compatible. Omit the construction of the + ** new IN operator if there are any collating sequence mismatches. */ if( okToChngToIN ){ Expr *pDup; /* A transient duplicate expression */ ExprList *pList = 0; /* The RHS of the IN operator */ Expr *pLeft = 0; /* The LHS of the IN operator */ + CollSeq *pCollSeq = 0; /* Collating sequence to use */ Expr *pNew; /* The complete IN operator */ for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){ + Expr *pThis; if( (pOrTerm->wtFlags & TERM_OK)==0 ) continue; assert( pOrTerm->eOperator & WO_EQ ); assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 ); assert( pOrTerm->leftCursor==iCursor ); assert( pOrTerm->u.x.leftColumn==iColumn ); - pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0); + pThis = pOrTerm->pExpr; + pDup = sqlite3ExprDup(db, pThis->pRight, 0); pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup); - pLeft = pOrTerm->pExpr->pLeft; + if( pLeft==0 ){ + pLeft = pThis->pLeft; + pCollSeq = sqlite3ExprCompareCollSeq(pParse, pThis); + }else{ + assert( 0==sqlite3ExprCompare(pParse, + sqlite3ExprSkipCollate(pThis->pLeft), + sqlite3ExprSkipCollate(pLeft), -1) ); + if( pCollSeq!=sqlite3ExprCompareCollSeq(pParse, pThis) ){ + pLeft = 0; /* Collating sequence mismatch */ + break; + } + } + } + if( pLeft==0 ){ + pNew = 0; /* Collating sequence mismatch */ + }else{ + pDup = sqlite3ExprDup(db, pLeft, 0); + if( sqlite3ExprCollSeq(pParse, pDup)!=pCollSeq + && ALWAYS(pCollSeq!=0) + ){ + assert( pCollSeq->zName!=0 ); + pDup = sqlite3ExprAddCollateString(pParse, pDup, pCollSeq->zName); + } + pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0); } - assert( pLeft!=0 ); - pDup = sqlite3ExprDup(db, pLeft, 0); - pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0); if( pNew ){ int idxNew; transferJoinMarkings(pNew, pExpr); @@ -162196,30 +168690,38 @@ static void exprAnalyzeOrTerm( ** 1. The SQLITE_Transitive optimization must be enabled ** 2. Must be either an == or an IS operator ** 3. Not originating in the ON clause of an OUTER JOIN -** 4. The affinities of A and B must be compatible -** 5a. Both operands use the same collating sequence OR -** 5b. The overall collating sequence is BINARY +** 4. The operator is not IS or else the query does not contain RIGHT JOIN +** 5. The affinities of A and B must be compatible +** 6. Both operands use the same collating sequence, and they must not +** use explicit COLLATE clauses. ** If this routine returns TRUE, that means that the RHS can be substituted ** for the LHS anyplace else in the WHERE clause where the LHS column occurs. ** This is an optimization. No harm comes from returning 0. But if 1 is ** returned when it should not be, then incorrect answers might result. */ -static int termIsEquivalence(Parse *pParse, Expr *pExpr){ +static int termIsEquivalence(Parse *pParse, Expr *pExpr, SrcList *pSrc){ char aff1, aff2; - CollSeq *pColl; - if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; - if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; - if( ExprHasProperty(pExpr, EP_OuterON) ) return 0; + if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; /* (1) */ + if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; /* (2) */ + if( ExprHasProperty(pExpr, EP_OuterON|EP_Collate) ) return 0; /* (3) */ + assert( pSrc!=0 ); + if( pExpr->op==TK_IS + && pSrc->nSrc>=2 + && (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 + ){ + return 0; /* (4) */ + } aff1 = sqlite3ExprAffinity(pExpr->pLeft); aff2 = sqlite3ExprAffinity(pExpr->pRight); if( aff1!=aff2 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2)) ){ - return 0; + return 0; /* (5) */ } - pColl = sqlite3ExprCompareCollSeq(pParse, pExpr); - if( sqlite3IsBinary(pColl) ) return 1; - return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight); + if( !sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight) ){ + return 0; /* (6) */ + } + return 1; } /* @@ -162377,10 +168879,14 @@ static void exprAnalyze( } assert( pWC->nTerm > idxTerm ); pTerm = &pWC->a[idxTerm]; +#ifdef SQLITE_DEBUG + pTerm->iTerm = idxTerm; +#endif pMaskSet = &pWInfo->sMaskSet; pExpr = pTerm->pExpr; assert( pExpr!=0 ); /* Because malloc() has not failed */ assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE ); +exprAnalyze_restart: pMaskSet->bVarSelect = 0; prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft); op = pExpr->op; @@ -162420,21 +168926,7 @@ static void exprAnalyze( prereqAll |= x; extraRight = x-1; /* ON clause terms may not be used with an index ** on left table of a LEFT JOIN. Ticket #3015 */ - if( (prereqAll>>1)>=x ){ - sqlite3ErrorMsg(pParse, "ON clause references tables to its right"); - return; - } }else if( (prereqAll>>1)>=x ){ - /* The ON clause of an INNER JOIN references a table to its right. - ** Most other SQL database engines raise an error. But SQLite versions - ** 3.0 through 3.38 just put the ON clause constraint into the WHERE - ** clause and carried on. Beginning with 3.39, raise an error only - ** if there is a RIGHT or FULL JOIN in the query. This makes SQLite - ** more like other systems, and also preserves legacy. */ - if( ALWAYS(pSrc->nSrc>0) && (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){ - sqlite3ErrorMsg(pParse, "ON clause references tables to its right"); - return; - } ExprClearProperty(pExpr, EP_InnerON); } } @@ -162484,8 +168976,8 @@ static void exprAnalyze( if( op==TK_IS ) pNew->wtFlags |= TERM_IS; pTerm = &pWC->a[idxTerm]; pTerm->wtFlags |= TERM_COPIED; - - if( termIsEquivalence(pParse, pDup) ){ + assert( pWInfo->pTabList!=0 ); + if( termIsEquivalence(pParse, pDup, pWInfo->pTabList) ){ pTerm->eOperator |= WO_EQUIV; eExtraOp = WO_EQUIV; } @@ -162539,6 +169031,7 @@ static void exprAnalyze( pList = pExpr->x.pList; assert( pList!=0 ); assert( pList->nExpr==2 ); + assert( pWC->a[idxTerm].nChild==0 ); for(i=0; i<2; i++){ Expr *pNewExpr; int idxNew; @@ -162559,7 +169052,12 @@ static void exprAnalyze( /* Analyze a term that is composed of two or more subterms connected by ** an OR operator. */ - else if( pExpr->op==TK_OR ){ + else if( pExpr->op==TK_OR && !ExprHasProperty(pExpr, EP_Collate) ){ + Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr); + if( pAlt!=pExpr ){ + pTerm->pExpr = pExpr = sqlite3ExprSkipCollateAndLikely(pAlt); + goto exprAnalyze_restart; + } assert( pWC->op==TK_AND ); exprAnalyzeOrTerm(pSrc, pWC, idxTerm); pTerm = &pWC->a[idxTerm]; @@ -162651,9 +169149,8 @@ static void exprAnalyze( } if( !db->mallocFailed ){ - u8 c, *pC; /* Last character before the first wildcard */ + u8 *pC; /* Last character before the first wildcard */ pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1]; - c = *pC; if( noCase ){ /* The point is to increment the last character before the first ** wildcard. But if we increment '@', that will push it into the @@ -162661,10 +169158,17 @@ static void exprAnalyze( ** inequality. To avoid this, make sure to also run the full ** LIKE on all candidate expressions by clearing the isComplete flag */ - if( c=='A'-1 ) isComplete = 0; - c = sqlite3UpperToLower[c]; + if( *pC=='A'-1 ) isComplete = 0; + *pC = sqlite3UpperToLower[*pC]; + } + + /* Increment the value of the last utf8 character in the prefix. */ + while( *pC==0xBF && pC>(u8*)pStr2->u.zToken ){ + *pC = 0x80; + pC--; } - *pC = c + 1; + assert( *pC!=0xFF ); /* isLikeOrGlob() guarantees this */ + (*pC)++; } zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY; pNewExpr1 = sqlite3ExprDup(db, pLeft, 0); @@ -162742,9 +169246,13 @@ static void exprAnalyze( #ifndef SQLITE_OMIT_WINDOWFUNC && pExpr->x.pSelect->pWin==0 #endif + && (pExpr->x.pSelect->selFlags & SF_MinMaxAgg)==0 && pWC->op==TK_AND + && pExpr->x.pSelect->pEList->nExpr <= UMXV(pTerm->nChild) + /* ^-- See bug 2026-06-04T10:00:49Z */ ){ int i; + assert( pTerm->nChild==0 ); for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){ int idxNew; idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL|TERM_SLICE); @@ -162785,7 +169293,7 @@ static void exprAnalyze( idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); testcase( idxNew==0 ); pNewTerm = &pWC->a[idxNew]; - pNewTerm->prereqRight = prereqExpr; + pNewTerm->prereqRight = prereqExpr | extraRight; pNewTerm->leftCursor = pLeft->iTable; pNewTerm->u.x.leftColumn = pLeft->iColumn; pNewTerm->eOperator = WO_AUX; @@ -162866,14 +169374,12 @@ static void whereAddLimitExpr( Expr *pNew; int iVal = 0; - if( sqlite3ExprIsInteger(pExpr, &iVal, pParse) && iVal>=0 ){ - Expr *pVal = sqlite3Expr(db, TK_INTEGER, 0); + if( sqlite3ExprIsInteger(pExpr, &iVal, pParse, 0) && iVal>=0 ){ + Expr *pVal = sqlite3ExprInt32(db, iVal); if( pVal==0 ) return; - ExprSetProperty(pVal, EP_IntValue); - pVal->u.iValue = iVal; pNew = sqlite3PExpr(pParse, TK_MATCH, 0, pVal); }else{ - Expr *pVal = sqlite3Expr(db, TK_REGISTER, 0); + Expr *pVal = sqlite3ExprAlloc(db, TK_REGISTER, 0, 0); if( pVal==0 ) return; pVal->iTable = iReg; pNew = sqlite3PExpr(pParse, TK_MATCH, 0, pVal); @@ -162896,7 +169402,7 @@ static void whereAddLimitExpr( ** ** 1. The SELECT statement has a LIMIT clause, and ** 2. The SELECT statement is not an aggregate or DISTINCT query, and -** 3. The SELECT statement has exactly one object in its from clause, and +** 3. The SELECT statement has exactly one object in its FROM clause, and ** that object is a virtual table, and ** 4. There are no terms in the WHERE clause that will not be passed ** to the virtual table xBestIndex method. @@ -162933,8 +169439,22 @@ SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3WhereAddLimit(WhereClause *pWC, Selec ** (leftCursor==iCsr) test below. */ continue; } - if( pWC->a[ii].leftCursor!=iCsr ) return; - if( pWC->a[ii].prereqRight!=0 ) return; + if( pWC->a[ii].leftCursor==iCsr && pWC->a[ii].prereqRight==0 ) continue; + + /* If this term has a parent with exactly one child, and the parent will + ** be passed through to xBestIndex, then this term can be ignored. */ + if( pWC->a[ii].iParent>=0 ){ + WhereTerm *pParent = &pWC->a[ pWC->a[ii].iParent ]; + if( pParent->leftCursor==iCsr + && pParent->prereqRight==0 + && pParent->nChild==1 + ){ + continue; + } + } + + /* This term will not be passed through. Do not add a LIMIT clause. */ + return; } /* Check condition (5). Return early if it is not met. */ @@ -163134,6 +169654,10 @@ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs( if( pItem->fg.isTabFunc==0 ) return; pTab = pItem->pSTab; assert( pTab!=0 ); + if( !IsVirtual(pTab) ){ + sqlite3ErrorMsg(pParse, "'%s' is not a function", pItem->zName); + return; + } pArgs = pItem->u1.pFuncArg; if( pArgs==0 ) return; for(j=k=0; j<pArgs->nExpr; j++){ @@ -163168,6 +169692,16 @@ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs( } } +/* +** Return true if the WhereLoop pLoop can be use a Bloom filter. +** tag-202607231411 +*/ +SQLITE_PRIVATE int sqlite3WhereLoopBloomable(const WhereLoop *pLoop){ + if( pLoop->wsFlags & WHERE_IPK ) return 1; + if( NEVER((pLoop->wsFlags & WHERE_INDEXED)==0) ) return 0; + return sqlite3IndexBloomable(pLoop->u.btree.pIndex, pLoop->u.btree.nEq); +} + /************** End of whereexpr.c *******************************************/ /************** Begin file where.c *******************************************/ /* @@ -163207,11 +169741,16 @@ struct HiddenIndexInfo { int eDistinct; /* Value to return from sqlite3_vtab_distinct() */ u32 mIn; /* Mask of terms that are <col> IN (...) */ u32 mHandleIn; /* Terms that vtab will handle as <col> IN (...) */ - sqlite3_value *aRhs[1]; /* RHS values for constraints. MUST BE LAST - ** because extra space is allocated to hold up - ** to nTerm such values */ + sqlite3_value *aRhs[FLEXARRAY]; /* RHS values for constraints. MUST BE LAST + ** Extra space is allocated to hold up + ** to nTerm such values */ }; +/* Size (in bytes) of a HiddenIndeInfo object sufficient to hold as +** many as N constraints */ +#define SZ_HIDDENINDEXINFO(N) \ + (offsetof(HiddenIndexInfo,aRhs) + (N)*sizeof(sqlite3_value*)) + /* Forward declaration of methods */ static int whereLoopResize(sqlite3*, WhereLoop*, int); @@ -163330,7 +169869,7 @@ SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ ** If the ONEPASS optimization is used (if this routine returns true) ** then also write the indices of open cursors used by ONEPASS ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data -** table and iaCur[1] gets the cursor used by an auxiliary index. +** table and aiCur[1] gets the cursor used by an auxiliary index. ** Either value may be -1, indicating that cursor is not used. ** Any cursors returned will have been opened for writing. ** @@ -163593,11 +170132,11 @@ static WhereTerm *whereScanNext(WhereScan *pScan){ pScan->pWC = pWC; pScan->k = k+1; #ifdef WHERETRACE_ENABLED - if( sqlite3WhereTrace & 0x20000 ){ + if( (sqlite3WhereTrace & 0x20000)!=0 && pScan->nEquiv>1 ){ int ii; - sqlite3DebugPrintf("SCAN-TERM %p: nEquiv=%d", - pTerm, pScan->nEquiv); - for(ii=0; ii<pScan->nEquiv; ii++){ + sqlite3DebugPrintf("EQUIVALENT TO {%d:%d} (due to TERM-%d):", + pScan->aiCur[0], pScan->aiColumn[0], pTerm->iTerm); + for(ii=1; ii<pScan->nEquiv; ii++){ sqlite3DebugPrintf(" {%d:%d}", pScan->aiCur[ii], pScan->aiColumn[ii]); } @@ -164011,7 +170550,7 @@ static int constraintCompatibleWithOuterJoin( return 0; } if( (pSrc->fg.jointype & (JT_LEFT|JT_RIGHT))!=0 - && ExprHasProperty(pTerm->pExpr, EP_InnerON) + && NEVER(ExprHasProperty(pTerm->pExpr, EP_InnerON)) ){ return 0; } @@ -164032,6 +170571,11 @@ static int constraintCompatibleWithOuterJoin( ** more than 20, then return false. ** ** 3. If no disqualifying conditions above are found, return true. +** +** 2025-01-03: I experimented with a new rule that returns false if the +** the datatype of the column is "BOOLEAN". This did not improve +** performance on any queries at hand, but it did burn CPU cycles, so the +** idea was not committed. */ static SQLITE_NOINLINE int columnIsGoodIndexCandidate( const Table *pTab, @@ -164116,7 +170660,7 @@ static void explainAutomaticIndex( sqlite3_str *pStr = sqlite3_str_new(pParse->db); sqlite3_str_appendf(pStr,"CREATE AUTOMATIC INDEX ON %s(", pTab->zName); assert( pIdx->nColumn>1 ); - assert( pIdx->aiColumn[pIdx->nColumn-1]==XN_ROWID ); + assert( pIdx->aiColumn[pIdx->nColumn-1]==XN_ROWID || !HasRowid(pTab) ); for(ii=0; ii<(pIdx->nColumn-1); ii++){ const char *zName = 0; int iCol = pIdx->aiColumn[ii]; @@ -164169,7 +170713,7 @@ static SQLITE_NOINLINE void constructAutomaticIndex( Bitmask idxCols; /* Bitmap of columns used for indexing */ Bitmask extraCols; /* Bitmap of additional columns */ u8 sentWarning = 0; /* True if a warning has been issued */ - u8 useBloomFilter = 0; /* True to also add a Bloom filter */ + u8 useBloomFilter = 1; /* True to also add a Bloom filter */ Expr *pPartial = 0; /* Partial Index Expression */ int iContinue = 0; /* Jump here to skip excluded rows */ SrcList *pTabList; /* The complete FROM clause */ @@ -164247,6 +170791,19 @@ static SQLITE_NOINLINE void constructAutomaticIndex( }else{ extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1)); } + if( !HasRowid(pTable) ){ + /* For WITHOUT ROWID tables, ensure that all PRIMARY KEY columns are + ** either in the idxCols mask or in the extraCols mask */ + for(i=0; i<pTable->nCol; i++){ + if( (pTable->aCol[i].colFlags & COLFLAG_PRIMKEY)==0 ) continue; + if( i>=BMS-1 ){ + extraCols |= MASKBIT(BMS-1); + break; + } + if( idxCols & MASKBIT(i) ) continue; + extraCols |= MASKBIT(i); + } + } mxBitCol = MIN(BMS-1,pTable->nCol); testcase( pTable->nCol==BMS-1 ); testcase( pTable->nCol==BMS-2 ); @@ -164258,7 +170815,10 @@ static SQLITE_NOINLINE void constructAutomaticIndex( } /* Construct the Index object to describe this index */ - pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed); + assert( nKeyCol <= pTable->nCol + MAX(0, pTable->nCol - BMS + 1) ); + /* ^-- This guarantees that the number of index columns will fit in the u16 */ + pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+HasRowid(pTable), + 0, &zNotUsed); if( pIdx==0 ) goto end_auto_index_create; pLoop->u.btree.pIndex = pIdx; pIdx->zName = "auto-index"; @@ -164280,18 +170840,13 @@ static SQLITE_NOINLINE void constructAutomaticIndex( pIdx->aiColumn[n] = pTerm->u.x.leftColumn; pColl = sqlite3ExprCompareCollSeq(pParse, pX); assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */ + if( !sqlite3IsBinary(pColl) ){ + /* Disallow the use of a Bloom filter if any non-BINARY collating + ** sequence is involved. tag-202607231411 */ + useBloomFilter = 0; + } pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY; n++; - if( ALWAYS(pX->pLeft!=0) - && sqlite3ExprAffinity(pX->pLeft)!=SQLITE_AFF_TEXT - ){ - /* TUNING: only use a Bloom filter on an automatic index - ** if one or more key columns has the ability to hold numeric - ** values, since strings all have the same hash in the Bloom - ** filter implementation and hence a Bloom filter on a text column - ** is not usually helpful. */ - useBloomFilter = 1; - } } } } @@ -164314,8 +170869,10 @@ static SQLITE_NOINLINE void constructAutomaticIndex( } } assert( n==nKeyCol ); - pIdx->aiColumn[n] = XN_ROWID; - pIdx->azColl[n] = sqlite3StrBINARY; + if( HasRowid(pTable) ){ + pIdx->aiColumn[n] = XN_ROWID; + pIdx->azColl[n] = sqlite3StrBINARY; + } /* Create the automatic index */ explainAutomaticIndex(pParse, pIdx, pPartial!=0, &addrExp); @@ -164345,7 +170902,9 @@ static SQLITE_NOINLINE void constructAutomaticIndex( VdbeCoverage(v); VdbeComment((v, "next row of %s", pSrc->pSTab->zName)); }else{ - addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v); + assert( pLevel->addrHalt ); + addrTop = sqlite3VdbeAddOp2(v, OP_Rewind,pLevel->iTabCur,pLevel->addrHalt); + VdbeCoverage(v); } if( pPartial ){ iContinue = sqlite3VdbeMakeLabel(pParse); @@ -164357,6 +170916,7 @@ static SQLITE_NOINLINE void constructAutomaticIndex( pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0 ); if( pLevel->regFilter ){ + assert( sqlite3WhereLoopBloomable(pLoop) ); sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, regBase, pLoop->u.btree.nEq); } @@ -164373,11 +170933,14 @@ static SQLITE_NOINLINE void constructAutomaticIndex( pSrc->u4.pSubq->regResult, pLevel->iIdxCur); sqlite3VdbeGoto(v, addrTop); pSrc->fg.viaCoroutine = 0; + sqlite3VdbeJumpHere(v, addrTop); }else{ sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v); sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX); + if( (pSrc->fg.jointype & JT_LEFT)!=0 ){ + sqlite3VdbeJumpHere(v, addrTop); + } } - sqlite3VdbeJumpHere(v, addrTop); sqlite3ReleaseTempReg(pParse, regRecord); /* Jump here when skipping the initialization */ @@ -164394,9 +170957,7 @@ static SQLITE_NOINLINE void constructAutomaticIndex( ** for pLevel. ** ** If there are inner loops within pLevel that have the WHERE_BLOOMFILTER -** flag set, initialize a Bloomfilter for them as well. Except don't do -** this recursive initialization if the SQLITE_BloomPulldown optimization has -** been turned off. +** flag set, initialize a Bloomfilter for them as well. ** ** When the Bloom filter is initialized, the WHERE_BLOOMFILTER flag is cleared ** from the loop, but the regFilter value is set to a register that implements @@ -164469,6 +171030,7 @@ static SQLITE_NOINLINE void sqlite3ConstructBloomFilter( }else if( sz>10000000 ){ sz = 10000000; } + assert( sqlite3WhereLoopBloomable(pLoop) ); sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter); addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v); @@ -164491,6 +171053,7 @@ static SQLITE_NOINLINE void sqlite3ConstructBloomFilter( int n = pLoop->u.btree.nEq; int r1 = sqlite3GetTempRange(pParse, n); int jj; + assert( pIdx!=0 ); for(jj=0; jj<n; jj++){ assert( pIdx->pTable==pItem->pSTab ); sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iCur, jj, r1+jj); @@ -164503,7 +171066,6 @@ static SQLITE_NOINLINE void sqlite3ConstructBloomFilter( VdbeCoverage(v); sqlite3VdbeJumpHere(v, addrTop); pLoop->wsFlags &= ~WHERE_BLOOMFILTER; - if( OptimizationDisabled(pParse->db, SQLITE_BloomPulldown) ) break; while( ++iLevel < pWInfo->nLevel ){ const SrcItem *pTabItem; pLevel = &pWInfo->a[iLevel]; @@ -164653,11 +171215,14 @@ static sqlite3_index_info *allocateIndexInfo( break; } if( i==n ){ + int bSortByGroup = (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)!=0; nOrderBy = n; if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY) && !pSrc->fg.rowidUsed ){ - eDistinct = 2 + ((pWInfo->wctrlFlags & WHERE_SORTBYGROUP)!=0); + eDistinct = 2 + bSortByGroup; }else if( pWInfo->wctrlFlags & WHERE_GROUPBY ){ - eDistinct = 1; + eDistinct = 1 - bSortByGroup; + }else if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ + eDistinct = 3; } } } @@ -164666,8 +171231,8 @@ static sqlite3_index_info *allocateIndexInfo( */ pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm - + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) - + sizeof(sqlite3_value*)*nTerm ); + + sizeof(*pIdxOrderBy)*nOrderBy + + SZ_HIDDENINDEXINFO(nTerm) ); if( pIdxInfo==0 ){ sqlite3ErrorMsg(pParse, "out of memory"); return 0; @@ -165504,7 +172069,7 @@ static int whereInScanEst( #endif /* SQLITE_ENABLE_STAT4 */ -#ifdef WHERETRACE_ENABLED +#if defined(WHERETRACE_ENABLED) || defined(SQLITE_DEBUG) /* ** Print the content of a WhereTerm object */ @@ -165529,6 +172094,7 @@ SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){ }else{ sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor); } + iTerm = pTerm->iTerm = MAX(iTerm,pTerm->iTerm); sqlite3DebugPrintf( "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x", iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags); @@ -165548,6 +172114,9 @@ SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){ sqlite3TreeViewExpr(0, pTerm->pExpr, 0); } } +SQLITE_PRIVATE void sqlite3ShowWhereTerm(WhereTerm *pTerm){ + sqlite3WhereTermPrint(pTerm, 0); +} #endif #ifdef WHERETRACE_ENABLED @@ -165579,17 +172148,24 @@ SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){ ** 1.002.001 t2.t2xy 2 f 010241 N 2 cost 0,56,31 */ SQLITE_PRIVATE void sqlite3WhereLoopPrint(const WhereLoop *p, const WhereClause *pWC){ + WhereInfo *pWInfo; if( pWC ){ - WhereInfo *pWInfo = pWC->pWInfo; - int nb = 1+(pWInfo->pTabList->nSrc+3)/4; - SrcItem *pItem = pWInfo->pTabList->a + p->iTab; - Table *pTab = pItem->pSTab; - Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1; + int nb; + SrcItem *pItem; + Table *pTab; + Bitmask mAll; + + pWInfo = pWC->pWInfo; + nb = 1+(pWInfo->pTabList->nSrc+3)/4; + pItem = pWInfo->pTabList->a + p->iTab; + pTab = pItem->pSTab; + mAll = (((Bitmask)1)<<(nb*4)) - 1; sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId, p->iTab, nb, p->maskSelf, nb, p->prereq & mAll); sqlite3DebugPrintf(" %12s", pItem->zAlias ? pItem->zAlias : pTab->zName); }else{ + pWInfo = 0; sqlite3DebugPrintf("%c%2d.%03llx.%03llx %c%d", p->cId, p->iTab, p->maskSelf, p->prereq & 0xfff, p->cId, p->iTab); } @@ -165621,7 +172197,12 @@ SQLITE_PRIVATE void sqlite3WhereLoopPrint(const WhereLoop *p, const WhereClause }else{ sqlite3DebugPrintf(" f %06x N %d", p->wsFlags, p->nLTerm); } - sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); + if( pWInfo && pWInfo->bStarUsed && p->rStarDelta!=0 ){ + sqlite3DebugPrintf(" cost %d,%d,%d delta=%d\n", + p->rSetup, p->rRun, p->nOut, p->rStarDelta); + }else{ + sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); + } if( p->nLTerm && (sqlite3WhereTrace & 0x4000)!=0 ){ int i; for(i=0; i<p->nLTerm; i++){ @@ -166057,6 +172638,67 @@ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ return rc; } +/* +** Callback for estLikePatternLength(). +** +** If this node is a string literal that is longer pWalker->sz, then set +** pWalker->sz to the byte length of that string literal. +** +** pWalker->eCode indicates how to count characters: +** +** eCode==0 Count as a GLOB pattern +** eCode==1 Count as a LIKE pattern +*/ +static int exprNodePatternLengthEst(Walker *pWalker, Expr *pExpr){ + if( pExpr->op==TK_STRING ){ + int sz = 0; /* Pattern size in bytes */ + u8 *z = (u8*)pExpr->u.zToken; /* The pattern */ + u8 c; /* Next character of the pattern */ + u8 c1, c2, c3; /* Wildcards */ + if( pWalker->eCode ){ + c1 = '%'; + c2 = '_'; + c3 = 0; + }else{ + c1 = '*'; + c2 = '?'; + c3 = '['; + } + while( (c = *(z++))!=0 ){ + if( c==c3 ){ + if( *z ) z++; + while( *z && *z!=']' ) z++; + }else if( c!=c1 && c!=c2 ){ + sz++; + } + } + if( sz>pWalker->u.sz ) pWalker->u.sz = sz; + } + return WRC_Continue; +} + +/* +** Return the length of the longest string literal in the given +** expression. +** +** eCode indicates how to count characters: +** +** eCode==0 Count as a GLOB pattern +** eCode==1 Count as a LIKE pattern +*/ +static int estLikePatternLength(Expr *p, u16 eCode){ + Walker w; + w.u.sz = 0; + w.eCode = eCode; + w.xExprCallback = exprNodePatternLengthEst; + w.xSelectCallback = sqlite3SelectWalkFail; +#ifdef SQLITE_DEBUG + w.xSelectCallback2 = sqlite3SelectWalkAssert2; +#endif + sqlite3WalkExpr(&w, p); + return w.u.sz; +} + /* ** Adjust the WhereLoop.nOut value downward to account for terms of the ** WHERE clause that reference the loop but which are not used by an @@ -166085,6 +172727,13 @@ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ ** "x" column is boolean or else -1 or 0 or 1 is a common default value ** on the "x" column and so in that case only cap the output row estimate ** at 1/2 instead of 1/4. +** +** Heuristic 3: If there is a LIKE or GLOB (or REGEXP or MATCH) operator +** with a large constant pattern, then reduce the size of the search +** space according to the length of the pattern, under the theory that +** longer patterns are less likely to match. This heuristic was added +** to give better output-row count estimates when preparing queries for +** the Join-Order Benchmarks. See forum thread 2026-01-30T09:57:54z */ static void whereLoopOutputAdjust( WhereClause *pWC, /* The WHERE clause */ @@ -166096,6 +172745,13 @@ static void whereLoopOutputAdjust( int i, j; LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */ + /* Skip all this if the FROM clause of the query is a single table and + ** there is no ORDER BY. In this case it doesn't matter how accurate + ** the WhereLoop.nOut values are. */ + if( pWC->pWInfo->pTabList->nSrc<=1 && pWC->pWInfo->pOrderBy==0 ){ + return; + } + assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); for(i=pWC->nBase, pTerm=pWC->a; i>0; i--, pTerm++){ assert( pTerm!=0 ); @@ -166134,14 +172790,16 @@ static void whereLoopOutputAdjust( }else{ /* In the absence of explicit truth probabilities, use heuristics to ** guess a reasonable truth probability. */ + Expr *pOpExpr = pTerm->pExpr; pLoop->nOut--; if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && (pTerm->wtFlags & TERM_HIGHTRUTH)==0 /* tag-20200224-1 */ ){ - Expr *pRight = pTerm->pExpr->pRight; + Expr *pRight = pOpExpr->pRight; + Parse *pParse = pWC->pWInfo->pParse; int k = 0; - testcase( pTerm->pExpr->op==TK_IS ); - if( sqlite3ExprIsInteger(pRight, &k, 0) && k>=(-1) && k<=1 ){ + testcase( pOpExpr->op==TK_IS ); + if( sqlite3ExprIsInteger(pRight, &k, pParse, 1) && k>=(-1) && k<=1 ){ k = 10; }else{ k = 20; @@ -166150,6 +172808,23 @@ static void whereLoopOutputAdjust( pTerm->wtFlags |= TERM_HEURTRUTH; iReduce = k; } + }else + if( ExprHasProperty(pOpExpr, EP_InfixFunc) + && pOpExpr->op==TK_FUNCTION + ){ + int eOp; + assert( ExprUseXList(pOpExpr) ); + assert( pOpExpr->x.pList->nExpr>=2 ); + eOp = sqlite3ExprIsLikeOperator(pOpExpr); + if( ALWAYS(eOp>0) ){ + int szPattern; + Expr *pRHS = pOpExpr->x.pList->a[0].pExpr; + eOp = eOp==SQLITE_INDEX_CONSTRAINT_LIKE; + szPattern = estLikePatternLength(pRHS, eOp); + if( szPattern>0 ){ + pLoop->nOut -= szPattern*2; + } + } } } } @@ -166221,6 +172896,7 @@ static int whereRangeVectorLen( idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn); if( aff!=idxaff ) break; + if( ExprHasProperty(pTerm->pExpr, EP_Commuted) ) SWAP(Expr*, pRhs, pLhs); pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); if( pColl==0 ) break; if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break; @@ -166293,11 +172969,8 @@ static int whereLoopAddBtreeIndex( assert( pNew->u.btree.nBtm==0 ); opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS; } - if( pProbe->bUnordered || pProbe->bLowQual ){ - if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE); - if( pProbe->bLowQual && pSrc->fg.isIndexedBy==0 ){ - opMask &= ~(WO_EQ|WO_IN|WO_IS); - } + if( pProbe->bUnordered ){ + opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE); } assert( pNew->u.btree.nEq<pProbe->nColumn ); @@ -166370,6 +173043,7 @@ static int whereLoopAddBtreeIndex( if( ExprUseXSelect(pExpr) ){ /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */ int i; + int bRedundant = 0; nIn = 46; assert( 46==sqlite3LogEst(25) ); /* The expression may actually be of the form (x, y) IN (SELECT...). @@ -166378,7 +173052,20 @@ static int whereLoopAddBtreeIndex( ** for each such term. The following loop checks that pTerm is the ** first such term in use, and sets nIn back to 0 if it is not. */ for(i=0; i<pNew->nLTerm-1; i++){ - if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0; + if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ){ + nIn = 0; + if( pNew->aLTerm[i]->u.x.iField == pTerm->u.x.iField ){ + /* Detect when two or more columns of an index match the same + ** column of a vector IN operater, and avoid adding the column + ** to the WhereLoop more than once. See tag-20250707-01 + ** in test/rowvalue.test */ + bRedundant = 1; + } + } + } + if( bRedundant ){ + pNew->nLTerm--; + continue; } }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){ /* "x IN (value, value, ...)" */ @@ -166599,6 +173286,7 @@ static int whereLoopAddBtreeIndex( pNew->rRun += nInMul + nIn; pNew->nOut += nInMul + nIn; whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize); + if( pSrc->fg.fromExists ) pNew->nOut = 0; rc = whereLoopInsert(pBuilder, pNew); if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ @@ -166610,7 +173298,7 @@ static int whereLoopAddBtreeIndex( if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 && pNew->u.btree.nEq<pProbe->nColumn && (pNew->u.btree.nEq<pProbe->nKeyCol || - pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY) + pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY) ){ if( pNew->u.btree.nEq>3 ){ sqlite3ProgressCheck(pParse); @@ -166649,6 +173337,7 @@ static int whereLoopAddBtreeIndex( && pProbe->hasStat1!=0 && OptimizationEnabled(db, SQLITE_SkipScan) && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */ + && pSrc->fg.fromExists==0 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK ){ LogEst nIter; @@ -166733,13 +173422,13 @@ static int whereUsablePartialIndex( if( !whereUsablePartialIndex(iTab,jointype,pWC,pWhere->pLeft) ) return 0; pWhere = pWhere->pRight; } - if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0; for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ Expr *pExpr; pExpr = pTerm->pExpr; if( (!ExprHasProperty(pExpr, EP_OuterON) || pExpr->w.iJoin==iTab) && ((jointype & JT_OUTER)==0 || ExprHasProperty(pExpr, EP_OuterON)) && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab) + && !sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, -1) && (pTerm->wtFlags & TERM_VNULL)==0 ){ return 1; @@ -167088,7 +173777,6 @@ static int whereLoopAddBtree( && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0 && !pSrc->fg.isIndexedBy /* Has no INDEXED BY clause */ && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */ - && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */ && !pSrc->fg.isCorrelated /* Not a correlated subquery */ && !pSrc->fg.isRecursive /* Not a recursive common table expression. */ && (pSrc->fg.jointype & JT_RIGHT)==0 /* Not the right tab of a RIGHT JOIN */ @@ -167154,6 +173842,7 @@ static int whereLoopAddBtree( pNew->u.btree.nEq = 0; pNew->u.btree.nBtm = 0; pNew->u.btree.nTop = 0; + pNew->u.btree.nDistinctCol = 0; pNew->nSkip = 0; pNew->nLTerm = 0; pNew->iSortIdx = 0; @@ -167193,7 +173882,14 @@ static int whereLoopAddBtree( whereLoopOutputAdjust(pWC, pNew, rSize); if( pSrc->fg.isSubquery ){ if( pSrc->fg.viaCoroutine ) pNew->wsFlags |= WHERE_COROUTINE; - pNew->u.btree.pOrderBy = pSrc->u4.pSubq->pSelect->pOrderBy; + /* Do not set btree.pOrderBy for a recursive CTE. In this case + ** the ORDER BY clause does not determine the overall order that + ** rows are emitted from the CTE in. */ + if( (pSrc->u4.pSubq->pSelect->selFlags & SF_Recursive)==0 ){ + pNew->u.btree.pOrderBy = pSrc->u4.pSubq->pSelect->pOrderBy; + } + }else if( pSrc->fg.fromExists ){ + pNew->nOut = 0; } rc = whereLoopInsert(pBuilder, pNew); pNew->nOut = rSize; @@ -167236,7 +173932,7 @@ static int whereLoopAddBtree( && (HasRowid(pTab) || pWInfo->pSelect!=0 || sqlite3FaultSim(700)) ){ WHERETRACE(0x200, - ("-> %s a covering index according to bitmasks\n", + ("-> %s is a covering index according to bitmasks\n", pProbe->zName, m==0 ? "is" : "is not")); pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED; } @@ -167296,6 +173992,7 @@ static int whereLoopAddBtree( ** positioned to the correct row during the right-join no-match ** loop. */ }else{ + if( pSrc->fg.fromExists ) pNew->nOut = 0; rc = whereLoopInsert(pBuilder, pNew); } pNew->nOut = rSize; @@ -167958,7 +174655,7 @@ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ sqlite3 *db = pWInfo->pParse->db; int rc = SQLITE_OK; int bFirstPastRJ = 0; - int hasRightJoin = 0; + int hasRightCrossJoin = 0; WhereLoop *pNew; @@ -167985,22 +174682,41 @@ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ ** prevents the right operand of a RIGHT JOIN from being swapped with ** other elements even further to the right. ** - ** The JT_LTORJ case and the hasRightJoin flag work together to - ** prevent FROM-clause terms from moving from the right side of - ** a LEFT JOIN over to the left side of that join if the LEFT JOIN - ** is itself on the left side of a RIGHT JOIN. + ** The hasRightCrossJoin flag prevent FROM-clause terms from moving + ** from the right side of a LEFT JOIN or CROSS JOIN over to the + ** left side of that same join. This is a required restriction in + ** the case of LEFT JOIN - an incorrect answer may results if it is + ** not enforced. This restriction is not required for CROSS JOIN. + ** It is provided merely as a means of controlling join order, under + ** the theory that no real-world queries that care about performance + ** actually use the CROSS JOIN syntax. */ - if( pItem->fg.jointype & JT_LTORJ ) hasRightJoin = 1; + if( pItem->fg.jointype & (JT_LTORJ|JT_CROSS) ){ + testcase( pItem->fg.jointype & JT_LTORJ ); + testcase( pItem->fg.jointype & JT_CROSS ); + hasRightCrossJoin = 1; + } mPrereq |= mPrior; bFirstPastRJ = (pItem->fg.jointype & JT_RIGHT)!=0; - }else if( !hasRightJoin ){ + }else if( pItem->fg.fromExists ){ + /* joins that result from the EXISTS-to-JOIN optimization should not + ** be moved to the left of any of their dependencies */ + WhereClause *pWC = &pWInfo->sWC; + WhereTerm *pTerm; + int i; + for(i=pWC->nBase, pTerm=pWC->a; i>0; i--, pTerm++){ + if( (pNew->maskSelf & pTerm->prereqAll)!=0 ){ + mPrereq |= (pTerm->prereqAll & (pNew->maskSelf-1)); + } + } + }else if( !hasRightCrossJoin ){ mPrereq = 0; } #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pItem->pSTab) ){ SrcItem *p; for(p=&pItem[1]; p<pEnd; p++){ - if( mUnusable || (p->fg.jointype & (JT_OUTER|JT_CROSS)) ){ + if( (p->fg.jointype & (JT_OUTER|JT_CROSS)) ){ mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor); } } @@ -168069,13 +174785,13 @@ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ ** direction because there is no way to run a co-routine backwards. */ static SQLITE_NOINLINE int wherePathMatchSubqueryOB( - WhereInfo *pWInfo, /* The WHERE clause */ WhereLoop *pLoop, /* The nested loop term that is a subquery */ int iLoop, /* Which level of the nested loop. 0==outermost */ int iCur, /* Cursor used by the this loop */ ExprList *pOrderBy, /* The ORDER BY clause on the whole query */ Bitmask *pRevMask, /* When loops need to go in reverse order */ - Bitmask *pOBSat /* Which terms of pOrderBy are satisfied so far */ + Bitmask *pOBSat, /* Which terms of pOrderBy are satisfied so far */ + u16 wctrlFlags /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */ ){ int iOB; /* Index into pOrderBy->a[] */ int jSub; /* Index into pSubOB->a[] */ @@ -168093,7 +174809,7 @@ static SQLITE_NOINLINE int wherePathMatchSubqueryOB( if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) break; if( pOBExpr->iTable!=iCur ) break; if( pOBExpr->iColumn!=pSubOB->a[jSub].u.x.iOrderByCol-1 ) break; - if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){ + if( (wctrlFlags & WHERE_GROUPBY)==0 ){ u8 sfOB = pOrderBy->a[iOB].fg.sortFlags; /* sortFlags for iOB */ u8 sfSub = pSubOB->a[jSub].fg.sortFlags; /* sortFlags for jSub */ if( (sfSub & KEYINFO_ORDER_BIGNULL) != (sfOB & KEYINFO_ORDER_BIGNULL) ){ @@ -168216,14 +174932,14 @@ static i8 wherePathSatisfiesOrderBy( pLoop = pLast; } if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){ - if( pLoop->u.vtab.isOrdered - && ((wctrlFlags&(WHERE_DISTINCTBY|WHERE_SORTBYGROUP))!=WHERE_DISTINCTBY) - ){ + if( pLoop->u.vtab.isOrdered && pWInfo->pOrderBy==pOrderBy ){ obSat = obDone; + }else{ + /* No further ORDER BY terms may be matched. So this call should + ** return >=0, not -1. Clear isOrderDistinct to ensure it does so. */ + isOrderDistinct = 0; } break; - }else if( wctrlFlags & WHERE_DISTINCTBY ){ - pLoop->u.btree.nDistinctCol = 0; } iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor; @@ -168253,12 +174969,20 @@ static i8 wherePathSatisfiesOrderBy( if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){ Parse *pParse = pWInfo->pParse; CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr); - CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr); + const Expr *pCExpr = pTerm->pExpr; + CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pCExpr); + char affRight; assert( pColl1 ); if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){ continue; } - testcase( pTerm->pExpr->op==TK_IS ); + affRight = sqlite3ExprAffinity(pCExpr->pRight); + /* Left operand must be a column, hence always has affinity */ + assert( sqlite3ExprAffinity(pCExpr->pLeft)!=0 ); + if( affRight!=0 && affRight!=sqlite3ExprAffinity(pCExpr->pLeft) ){ + continue; /* An affinity conversion would be required */ + } + testcase( pCExpr->op==TK_IS ); } obSat |= MASKBIT(i); } @@ -168267,8 +174991,8 @@ static i8 wherePathSatisfiesOrderBy( if( pLoop->wsFlags & WHERE_IPK ){ if( pLoop->u.btree.pOrderBy && OptimizationEnabled(db, SQLITE_OrderBySubq) - && wherePathMatchSubqueryOB(pWInfo,pLoop,iLoop,iCur, - pOrderBy,pRevMask, &obSat) + && wherePathMatchSubqueryOB(pLoop,iLoop,iCur, + pOrderBy,pRevMask, &obSat, wctrlFlags) ){ nColumn = 0; isOrderDistinct = 0; @@ -168591,68 +175315,226 @@ static LogEst whereSortingCost( ** 18 for star queries ** 12 otherwise ** -** For the purposes of SQLite, a star-query is defined as a query -** with a large central table that is joined against four or more -** smaller tables. The central table is called the "fact" table. -** The smaller tables that get joined are "dimension tables". +** For the purposes of this heuristic, a star-query is defined as a query +** with a central "fact" table that is joined against multiple +** "dimension" tables, subject to the following constraints: +** +** (aa) Only a five-way or larger join is considered for this +** optimization. If there are fewer than four terms in the FROM +** clause, this heuristic does not apply. +** +** (bb) The join between the fact table and the dimension tables must +** be an INNER join. CROSS and OUTER JOINs do not qualify. +** +** (cc) A table must have 3 or more dimension tables in order to be +** considered a fact table. (Was 4 prior to 2026-02-10.) +** +** (dd) A table that is a self-join cannot be a dimension table. +** Dimension tables are joined against fact tables. ** ** SIDE EFFECT: (and really the whole point of this subroutine) ** -** If pWInfo describes a star-query, then the cost on WhereLoops for the -** fact table is reduced. This heuristic helps keep fact tables in -** outer loops. Without this heuristic, paths with fact tables in outer -** loops tend to get pruned by the mxChoice limit on the number of paths, -** resulting in poor query plans. The total amount of heuristic cost -** adjustment is stored in pWInfo->nOutStarDelta and the cost adjustment -** for each WhereLoop is stored in its rStarDelta field. +** If pWInfo describes a star-query, then the cost for SCANs of dimension +** WhereLoops is increased to be slightly larger than the cost of a SCAN +** in the fact table. Only SCAN costs are increased. SEARCH costs are +** unchanged. This heuristic helps keep fact tables in outer loops. Without +** this heuristic, paths with fact tables in outer loops tend to get pruned +** by the mxChoice limit on the number of paths, resulting in poor query +** plans. See the starschema1.test test module for examples of queries +** that need this heuristic to find good query plans. +** +** This heuristic can be completely disabled, so that no query is +** considered a star-query, using SQLITE_TESTCTRL_OPTIMIZATION to +** disable the SQLITE_StarQuery optimization. In the CLI, the command +** to do that is: ".testctrl opt -starquery". +** +** HISTORICAL NOTES: +** +** This optimization was first added on 2024-05-09 by check-in 38db9b5c83d. +** The original optimization reduced the cost and output size estimate for +** fact tables to help them move to outer loops. But months later (as people +** started upgrading) performance regression reports started caming in, +** including: +** +** forum post b18ef983e68d06d1 (2024-12-21) +** forum post 0025389d0860af82 (2025-01-14) +** forum post d87570a145599033 (2025-01-17) +** +** To address these, the criteria for a star-query was tightened to exclude +** cases where the fact and dimensions are separated by an outer join, and +** the affect of star-schema detection was changed to increase the rRun cost +** on just full table scans of dimension tables, rather than reducing costs +** in the all access methods of the fact table. */ -static int computeMxChoice(WhereInfo *pWInfo, LogEst nRowEst){ +static int computeMxChoice(WhereInfo *pWInfo){ int nLoop = pWInfo->nLevel; /* Number of terms in the join */ - if( nRowEst==0 && nLoop>=5 ){ - /* Check to see if we are dealing with a star schema and if so, reduce - ** the cost of fact tables relative to dimension tables, as a heuristic - ** to help keep the fact tables in outer loops. + WhereLoop *pWLoop; /* For looping over WhereLoops */ + +#ifdef SQLITE_DEBUG + /* The star-query detection code below makes use of the following + ** properties of the WhereLoop list, so verify them before + ** continuing: + ** (1) .maskSelf is the bitmask corresponding to .iTab + ** (2) The WhereLoop list is in ascending .iTab order + */ + for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ + assert( pWLoop->maskSelf==MASKBIT(pWLoop->iTab) ); + assert( pWLoop->pNextLoop==0 || pWLoop->iTab<=pWLoop->pNextLoop->iTab ); + } +#endif /* SQLITE_DEBUG */ + + if( nLoop>=4 /* Constraint (aa) */ + && !pWInfo->bStarDone + && OptimizationEnabled(pWInfo->pParse->db, SQLITE_StarQuery) + ){ + SrcItem *aFromTabs; /* All terms of the FROM clause */ + int iFromIdx; /* Term of FROM clause is the candidate fact-table */ + Bitmask m; /* Bitmask for candidate fact-table */ + Bitmask mSelfJoin = 0; /* Tables that cannot be dimension tables */ + WhereLoop *pStart; /* Where to start searching for dimension-tables */ + + pWInfo->bStarDone = 1; /* Only do this computation once */ + + /* Look for fact tables with three or more dimensions where the + ** dimension tables are not separately from the fact tables by an outer + ** or cross join. Adjust cost weights if found. */ - int iLoop; /* Counter over join terms */ - Bitmask m; /* Bitmask for current loop */ - assert( pWInfo->nOutStarDelta==0 ); - for(iLoop=0, m=1; iLoop<nLoop; iLoop++, m<<=1){ - WhereLoop *pWLoop; /* For looping over WhereLoops */ + assert( !pWInfo->bStarUsed ); + aFromTabs = pWInfo->pTabList->a; + pStart = pWInfo->pLoops; + for(iFromIdx=0, m=1; iFromIdx<nLoop; iFromIdx++, m<<=1){ int nDep = 0; /* Number of dimension tables */ - LogEst rDelta; /* Heuristic cost adjustment */ + LogEst mxRun; /* Maximum SCAN cost of a fact table */ Bitmask mSeen = 0; /* Mask of dimension tables */ - for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ - if( (pWLoop->prereq & m)!=0 && (pWLoop->maskSelf & mSeen)==0 ){ - nDep++; - mSeen |= pWLoop->maskSelf; + SrcItem *pFactTab; /* The candidate fact table */ + + pFactTab = aFromTabs + iFromIdx; + if( (pFactTab->fg.jointype & (JT_OUTER|JT_CROSS))!=0 ){ + /* If the candidate fact-table is the right table of an outer join + ** restrict the search for dimension-tables to be tables to the right + ** of the fact-table. Constraint (bb) */ + if( iFromIdx+3 > nLoop ){ + break; /* ^-- Impossible to reach nDep>=2 - Constraint (cc) */ + } + while( pStart && pStart->iTab<=iFromIdx ){ + pStart = pStart->pNextLoop; } } - if( nDep<=3 ) continue; - rDelta = 15*(nDep-3); -#ifdef WHERETRACE_ENABLED /* 0x4 */ - if( sqlite3WhereTrace&0x4 ){ - SrcItem *pItem = pWInfo->pTabList->a + iLoop; - sqlite3DebugPrintf("Fact-table %s: %d dimensions, cost reduced %d\n", - pItem->zAlias ? pItem->zAlias : pItem->pSTab->zName, - nDep, rDelta); + for(pWLoop=pStart; pWLoop; pWLoop=pWLoop->pNextLoop){ + if( (aFromTabs[pWLoop->iTab].fg.jointype & (JT_OUTER|JT_CROSS))!=0 ){ + break; /* Constraint (bb) */ + } + if( (pWLoop->prereq & m)!=0 /* pWInfo depends on iFromIdx */ + && (pWLoop->maskSelf & mSeen)==0 /* pWInfo not already a dependency */ + && (pWLoop->maskSelf & mSelfJoin)==0 /* Not a self-join */ + ){ + if( aFromTabs[pWLoop->iTab].pSTab==pFactTab->pSTab ){ + mSelfJoin |= m; + }else{ + nDep++; + mSeen |= pWLoop->maskSelf; + } + } } -#endif - if( pWInfo->nOutStarDelta==0 ){ + if( nDep<=2 ){ + continue; /* Constraint (cc) */ + } + + /* If we reach this point, it means that pFactTab is a fact table + ** with four or more dimensions connected by inner joins. Proceed + ** to make cost adjustments. */ + +#ifdef WHERETRACE_ENABLED + /* Make sure rStarDelta values are initialized */ + if( !pWInfo->bStarUsed ){ for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ pWLoop->rStarDelta = 0; } } - pWInfo->nOutStarDelta += rDelta; +#endif +#ifdef WHERETRACE_ENABLED /* 0x80000 */ + if( sqlite3WhereTrace & 0x80000 ){ + Bitmask mShow = mSeen; + sqlite3DebugPrintf("Fact table %s(%d), dimensions:", + pFactTab->zAlias ? pFactTab->zAlias : pFactTab->pSTab->zName, + iFromIdx); + for(pWLoop=pStart; pWLoop; pWLoop=pWLoop->pNextLoop){ + if( mShow & pWLoop->maskSelf ){ + SrcItem *pDim = aFromTabs + pWLoop->iTab; + mShow &= ~pWLoop->maskSelf; + sqlite3DebugPrintf(" %s(%d)", + pDim->zAlias ? pDim->zAlias: pDim->pSTab->zName, pWLoop->iTab); + } + } + sqlite3DebugPrintf("\n"); + } +#endif + pWInfo->bStarUsed = 1; + + /* Compute the maximum cost of any WhereLoop for the + ** fact table plus one epsilon */ + mxRun = LOGEST_MIN; + for(pWLoop=pStart; pWLoop; pWLoop=pWLoop->pNextLoop){ + if( pWLoop->iTab<iFromIdx ) continue; + if( pWLoop->iTab>iFromIdx ) break; + if( pWLoop->rRun>mxRun ) mxRun = pWLoop->rRun; + } + if( ALWAYS(mxRun<LOGEST_MAX) ) mxRun++; + + /* Increase the cost of table scans for dimension tables to be + ** slightly more than the maximum cost of the fact table */ + for(pWLoop=pStart; pWLoop; pWLoop=pWLoop->pNextLoop){ + if( (pWLoop->maskSelf & mSeen)==0 ) continue; + if( pWLoop->nLTerm ) continue; + if( pWLoop->rRun<mxRun ){ +#ifdef WHERETRACE_ENABLED /* 0x80000 */ + if( sqlite3WhereTrace & 0x80000 ){ + SrcItem *pDim = aFromTabs + pWLoop->iTab; + sqlite3DebugPrintf( + "Increase SCAN cost of %s to %d\n", + pDim->zAlias ? pDim->zAlias: pDim->pSTab->zName, mxRun + ); + } + pWLoop->rStarDelta = mxRun - pWLoop->rRun; +#endif /* WHERETRACE_ENABLED */ + pWLoop->rRun = mxRun; + } + } + } +#ifdef WHERETRACE_ENABLED /* 0x80000 */ + if( (sqlite3WhereTrace & 0x80000)!=0 && pWInfo->bStarUsed ){ + sqlite3DebugPrintf("WhereLoops changed by star-query heuristic:\n"); for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ - if( pWLoop->maskSelf==m ){ - pWLoop->rRun -= rDelta; - pWLoop->nOut -= rDelta; - pWLoop->rStarDelta = rDelta; + if( pWLoop->rStarDelta ){ + sqlite3WhereLoopPrint(pWLoop, &pWInfo->sWC); } } } +#endif } - return pWInfo->nOutStarDelta>0 ? 18 : 12; + return pWInfo->bStarUsed ? 18 : 12; +} + +/* +** Two WhereLoop objects, pCandidate and pBaseline, are known to have the +** same cost. Look deep into each to see if pCandidate is even slightly +** better than pBaseline. Return false if it is, if pCandidate is is preferred. +** Return true if pBaseline is preferred or if we cannot tell the difference. +** +** Result Meaning +** -------- ---------------------------------------------------------- +** true We cannot tell the difference in pCandidate and pBaseline +** false pCandidate seems like a better choice than pBaseline +*/ +static SQLITE_NOINLINE int whereLoopIsNoBetter( + const WhereLoop *pCandidate, + const WhereLoop *pBaseline +){ + if( (pCandidate->wsFlags & WHERE_INDEXED)==0 ) return 1; + if( (pBaseline->wsFlags & WHERE_INDEXED)==0 ) return 1; + if( pCandidate->u.btree.pIndex->szIdxRow < + pBaseline->u.btree.pIndex->szIdxRow ) return 0; + return 1; } /* @@ -168676,7 +175558,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ int mxI = 0; /* Index of next entry to replace */ int nOrderBy; /* Number of ORDER BY clause terms */ LogEst mxCost = 0; /* Maximum cost of a set of paths */ - LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */ + LogEst mxUnsort = 0; /* Maximum unsorted cost of a set of path */ int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */ WherePath *aFrom; /* All nFrom paths at the previous level */ WherePath *aTo; /* The nTo best paths at the current level */ @@ -168705,8 +175587,10 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ mxChoice = 1; }else if( nLoop==2 ){ mxChoice = 5; + }else if( pParse->nErr ){ + mxChoice = 1; }else{ - mxChoice = computeMxChoice(pWInfo, nRowEst); + mxChoice = computeMxChoice(pWInfo); } assert( nLoop<=pWInfo->pTabList->nSrc ); @@ -168773,7 +175657,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ LogEst nOut; /* Rows visited by (pFrom+pWLoop) */ LogEst rCost; /* Cost of path (pFrom+pWLoop) */ - LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */ + LogEst rUnsort; /* Unsorted cost of (pFrom+pWLoop) */ i8 isOrdered; /* isOrdered for (pFrom+pWLoop) */ Bitmask maskNew; /* Mask of src visited by (..) */ Bitmask revMask; /* Mask of rev-order loops for (..) */ @@ -168791,11 +175675,11 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ /* At this point, pWLoop is a candidate to be the next loop. ** Compute its cost */ - rUnsorted = pWLoop->rRun + pFrom->nRow; + rUnsort = pWLoop->rRun + pFrom->nRow; if( pWLoop->rSetup ){ - rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup, rUnsorted); + rUnsort = sqlite3LogEstAdd(pWLoop->rSetup, rUnsort); } - rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted); + rUnsort = sqlite3LogEstAdd(rUnsort, pFrom->rUnsort); nOut = pFrom->nRow + pWLoop->nOut; maskNew = pFrom->maskLoop | pWLoop->maskSelf; isOrdered = pFrom->isOrdered; @@ -168817,23 +175701,30 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ ** extra encouragement to the query planner to select a plan ** where the rows emerge in the correct order without any sorting ** required. */ - rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 3; + rCost = sqlite3LogEstAdd(rUnsort, aSortCost[isOrdered]) + 3; WHERETRACE(0x002, ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n", aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy, - rUnsorted, rCost)); + rUnsort, rCost)); }else{ - rCost = rUnsorted; - rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */ + rCost = rUnsort; + rUnsort -= 2; /* TUNING: Slight bias in favor of no-sort plans */ } /* Check to see if pWLoop should be added to the set of ** mxChoice best-so-far paths. ** ** First look for an existing path among best-so-far paths - ** that covers the same set of loops and has the same isOrdered - ** setting as the current path candidate. + ** that: + ** (1) covers the same set of loops, and + ** (2) has a compatible isOrdered value. + ** + ** "Compatible isOrdered value" means either + ** (A) both have isOrdered==-1, or + ** (B) both have isOrder>=0, or + ** (C) ordering does not matter because this is the last round + ** of the solver. ** ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range @@ -168842,7 +175733,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ testcase( nTo==0 ); for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){ if( pTo->maskLoop==maskNew - && ((pTo->isOrdered^isOrdered)&0x80)==0 + && ( ((pTo->isOrdered^isOrdered)&0x80)==0 || iLoop==nLoop-1 ) ){ testcase( jj==nTo-1 ); break; @@ -168851,7 +175742,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ if( jj>=nTo ){ /* None of the existing best-so-far paths match the candidate. */ if( nTo>=mxChoice - && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted)) + && (rCost>mxCost || (rCost==mxCost && rUnsort>=mxUnsort)) ){ /* The current candidate is no better than any of the mxChoice ** paths currently in the best-so-far buffer. So discard @@ -168859,7 +175750,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ #ifdef WHERETRACE_ENABLED /* 0x4 */ if( sqlite3WhereTrace&0x4 ){ sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n", - wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsort, isOrdered>=0 ? isOrdered+'0' : '?'); } #endif @@ -168878,7 +175769,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ #ifdef WHERETRACE_ENABLED /* 0x4 */ if( sqlite3WhereTrace&0x4 ){ sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n", - wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsort, isOrdered>=0 ? isOrdered+'0' : '?'); } #endif @@ -168889,24 +175780,23 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ ** pTo or if the candidate should be skipped. ** ** The conditional is an expanded vector comparison equivalent to: - ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted) + ** (pTo->rCost,pTo->nRow,pTo->rUnsort) <= (rCost,nOut,rUnsort) */ - if( pTo->rCost<rCost - || (pTo->rCost==rCost - && (pTo->nRow<nOut - || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted) - ) - ) + if( (pTo->rCost<rCost) + || (pTo->rCost==rCost && pTo->nRow<nOut) + || (pTo->rCost==rCost && pTo->nRow==nOut && pTo->rUnsort<rUnsort) + || (pTo->rCost==rCost && pTo->nRow==nOut && pTo->rUnsort==rUnsort + && whereLoopIsNoBetter(pWLoop, pTo->aLoop[iLoop]) ) ){ #ifdef WHERETRACE_ENABLED /* 0x4 */ if( sqlite3WhereTrace&0x4 ){ sqlite3DebugPrintf( "Skip %s cost=%-3d,%3d,%3d order=%c", - wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsort, isOrdered>=0 ? isOrdered+'0' : '?'); sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n", wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, - pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); + pTo->rUnsort, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); } #endif /* Discard the candidate path from further consideration */ @@ -168920,11 +175810,11 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ if( sqlite3WhereTrace&0x4 ){ sqlite3DebugPrintf( "Update %s cost=%-3d,%3d,%3d order=%c", - wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, + wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsort, isOrdered>=0 ? isOrdered+'0' : '?'); sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n", wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, - pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); + pTo->rUnsort, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); } #endif } @@ -168933,20 +175823,20 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ pTo->revLoop = revMask; pTo->nRow = nOut; pTo->rCost = rCost; - pTo->rUnsorted = rUnsorted; + pTo->rUnsort = rUnsort; pTo->isOrdered = isOrdered; memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop); pTo->aLoop[iLoop] = pWLoop; if( nTo>=mxChoice ){ mxI = 0; mxCost = aTo[0].rCost; - mxUnsorted = aTo[0].nRow; + mxUnsort = aTo[0].nRow; for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){ if( pTo->rCost>mxCost - || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted) + || (pTo->rCost==mxCost && pTo->rUnsort>mxUnsort) ){ mxCost = pTo->rCost; - mxUnsorted = pTo->rUnsorted; + mxUnsort = pTo->rUnsort; mxI = jj; } } @@ -168958,8 +175848,10 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ if( sqlite3WhereTrace & 0x02 ){ LogEst rMin, rFloor = 0; int nDone = 0; + int nProgress; sqlite3DebugPrintf("---- after round %d ----\n", iLoop); - while( nDone<nTo ){ + do{ + nProgress = 0; rMin = 0x7fff; for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){ if( pTo->rCost>rFloor && pTo->rCost<rMin ) rMin = pTo->rCost; @@ -168975,10 +175867,11 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ sqlite3DebugPrintf("\n"); } nDone++; + nProgress++; } } rFloor = rMin; - } + }while( nDone<nTo && nProgress>0 ); } #endif @@ -168995,11 +175888,10 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ return SQLITE_ERROR; } - /* Find the lowest cost path. pFrom will be left pointing to that path */ + /* Only one path is available, which is the best path */ + assert( nFrom==1 ); pFrom = aFrom; - for(ii=1; ii<nFrom; ii++){ - if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii]; - } + assert( pWInfo->nLevel==nLoop ); /* Load the lowest cost path into pWInfo */ for(iLoop=0; iLoop<nLoop; iLoop++){ @@ -169072,7 +175964,10 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ } } - pWInfo->nRowOut = pFrom->nRow + pWInfo->nOutStarDelta; + pWInfo->nRowOut = pFrom->nRow; +#ifdef WHERETRACE_ENABLED + pWInfo->rTotalCost = pFrom->rCost; +#endif /* Free temporary memory and return success */ sqlite3StackFreeNN(pParse->db, pSpace); @@ -169129,7 +176024,10 @@ static SQLITE_NOINLINE void whereInterstageHeuristic(WhereInfo *pWInfo){ for(i=0; i<pWInfo->nLevel; i++){ WhereLoop *p = pWInfo->a[i].pWLoop; if( p==0 ) break; - if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 ) continue; + if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ + /* Treat a vtab scan as similar to a full-table scan */ + break; + } if( (p->wsFlags & (WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0 ){ u8 iTab = p->iTab; WhereLoop *pLoop; @@ -169394,7 +176292,7 @@ static SQLITE_NOINLINE Bitmask whereOmitNoopJoin( } if( hasRightJoin && ExprHasProperty(pTerm->pExpr, EP_InnerON) - && pTerm->pExpr->w.iJoin==pItem->iCursor + && NEVER(pTerm->pExpr->w.iJoin==pItem->iCursor) ){ break; /* restriction (5) */ } @@ -169408,6 +176306,7 @@ static SQLITE_NOINLINE Bitmask whereOmitNoopJoin( for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){ if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){ pTerm->wtFlags |= TERM_CODED; + pTerm->prereqAll = 0; } } if( i!=pWInfo->nLevel-1 ){ @@ -169455,22 +176354,19 @@ static SQLITE_NOINLINE void whereCheckIfBloomFilterIsUseful( pTab->tabFlags |= TF_MaybeReanalyze; if( i>=1 && (pLoop->wsFlags & reqFlags)==reqFlags - /* vvvvvv--- Always the case if WHERE_COLUMN_EQ is defined */ - && ALWAYS((pLoop->wsFlags & (WHERE_IPK|WHERE_INDEXED))!=0) + && sqlite3WhereLoopBloomable(pLoop) + && nSearch > pTab->nRowLogEst ){ - if( nSearch > pTab->nRowLogEst ){ - testcase( pItem->fg.jointype & JT_LEFT ); - pLoop->wsFlags |= WHERE_BLOOMFILTER; - pLoop->wsFlags &= ~WHERE_IDX_ONLY; - WHERETRACE(0xffffffff, ( - "-> use Bloom-filter on loop %c because there are ~%.1e " - "lookups into %s which has only ~%.1e rows\n", - pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName, - (double)sqlite3LogEstToInt(pTab->nRowLogEst))); - } + testcase( pItem->fg.jointype & JT_LEFT ); + pLoop->wsFlags |= WHERE_BLOOMFILTER; + pLoop->wsFlags &= ~WHERE_IDX_ONLY; + WHERETRACE(0xffffffff, ( + "-> use Bloom-filter on loop %c because there are ~%.1e " + "lookups into %s which has only ~%.1e rows\n", + pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName, + (double)sqlite3LogEstToInt(pTab->nRowLogEst))); } nSearch += pLoop->nOut; - if( pWInfo->nOutStarDelta ) nSearch += pLoop->rStarDelta; } } @@ -169714,10 +176610,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( ** field (type Bitmask) it must be aligned on an 8-byte boundary on ** some architectures. Hence the ROUND8() below. */ - nByteWInfo = ROUND8P(sizeof(WhereInfo)); - if( nTabList>1 ){ - nByteWInfo = ROUND8P(nByteWInfo + (nTabList-1)*sizeof(WhereLevel)); - } + nByteWInfo = SZ_WHEREINFO(nTabList); pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop)); if( db->mallocFailed ){ sqlite3DbFree(db, pWInfo); @@ -169934,7 +176827,8 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( } /* TUNING: Assume that a DISTINCT clause on a subquery reduces - ** the output size by a factor of 8 (LogEst -30). + ** the output size by a factor of 8 (LogEst -30). Search for + ** tag-20250414a to see other cases. */ if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){ WHERETRACE(0x0080,("nRowOut reduced from %d to %d due to DISTINCT\n", @@ -169953,7 +176847,8 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( assert( db->mallocFailed==0 ); #ifdef WHERETRACE_ENABLED if( sqlite3WhereTrace ){ - sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut); + sqlite3DebugPrintf("---- Solution cost=%d, nRow=%d", + pWInfo->rTotalCost, pWInfo->nRowOut); if( pWInfo->nOBSat>0 ){ sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask); } @@ -170069,6 +176964,14 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( pTab = pTabItem->pSTab; iDb = sqlite3SchemaToIndex(db, pTab->pSchema); pLoop = pLevel->pWLoop; + pLevel->addrBrk = sqlite3VdbeMakeLabel(pParse); + if( ii==0 || (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){ + pLevel->addrHalt = pLevel->addrBrk; + }else if( pWInfo->a[ii-1].pRJ ){ + pLevel->addrHalt = pWInfo->a[ii-1].addrBrk; + }else{ + pLevel->addrHalt = pWInfo->a[ii-1].addrHalt; + } if( (pTab->tabFlags & TF_Ephemeral)!=0 || IsView(pTab) ){ /* Do nothing */ }else @@ -170117,9 +177020,16 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( sqlite3VdbeChangeP5(v, bFordelete); } #ifdef SQLITE_ENABLE_COLUMN_USED_MASK - sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0, - (const u8*)&pTabItem->colUsed, P4_INT64); + sqlite3VdbeAddOp3(v, OP_ColumnsUsed, pTabItem->iCursor, + LOWER32(pTabItem->colUsed), UPPER32(pTabItem->colUsed)); #endif + if( ii>=2 + && (pTabItem[0].fg.jointype & (JT_LTORJ|JT_LEFT))==0 + && pLevel->addrHalt==pWInfo->a[0].addrHalt + ){ + sqlite3VdbeAddOp2(v, OP_IfEmpty, pTabItem->iCursor, pWInfo->iBreak); + VdbeCoverage(v); + } }else{ sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); } @@ -170188,10 +177098,15 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue; colUsed |= ((u64)1)<<(ii<63 ? ii : 63); } - sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0, - (u8*)&colUsed, P4_INT64); + sqlite3VdbeAddOp3(v, OP_ColumnsUsed, iIndexCur, + LOWER32(colUsed),UPPER32(colUsed)); } #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */ +#ifdef SQLITE_ENABLE_CURSOR_HINTS + if( HasRowid(pTab) ){ + sqlite3VdbeAddOp3(v, OP_CursorHint, iIndexCur, 0, pTabItem->iCursor); + } +#endif } } if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb); @@ -170199,15 +177114,15 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( && (pLevel->pRJ = sqlite3WhereMalloc(pWInfo, sizeof(WhereRightJoin)))!=0 ){ WhereRightJoin *pRJ = pLevel->pRJ; + int bBloomable = 0; pRJ->iMatch = pParse->nTab++; - pRJ->regBloom = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom); pRJ->regReturn = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Null, 0, pRJ->regReturn); assert( pTab==pTabItem->pSTab ); if( HasRowid(pTab) ){ KeyInfo *pInfo; sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, 1); + bBloomable = 1; pInfo = sqlite3KeyInfoAlloc(pParse->db, 1, 0); if( pInfo ){ pInfo->aColl[0] = 0; @@ -170218,6 +177133,13 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( Index *pPk = sqlite3PrimaryKeyIndex(pTab); sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, pPk->nKeyCol); sqlite3VdbeSetP4KeyInfo(pParse, pPk); + bBloomable = sqlite3IndexBloomable(pPk,pPk->nKeyCol); + } + if( bBloomable ){ + pRJ->regBloom = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom); + }else{ + pRJ->regBloom = 0; } pLoop->wsFlags &= ~WHERE_IDX_ONLY; /* The nature of RIGHT JOIN processing is such that it messes up @@ -170314,6 +177236,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( ){ if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return; sqlite3VdbePrintOp(0, pc, pOp); + sqlite3ShowWhereTerm(0); /* So compiler won't complain about unused func */ } #endif @@ -170331,6 +177254,9 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ sqlite3 *db = pParse->db; int iEnd = sqlite3VdbeCurrentAddr(v); int nRJ = 0; +#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT + int addrSeek = 0; +#endif /* Generate loop termination code. */ @@ -170343,7 +177269,10 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ ** the RIGHT JOIN table */ WhereRightJoin *pRJ = pLevel->pRJ; sqlite3VdbeResolveLabel(v, pLevel->addrCont); - pLevel->addrCont = 0; + /* Replace addrCont with a new label that will never be used, just so + ** the subsequent call to resolve pLevel->addrCont will have something + ** to resolve. */ + pLevel->addrCont = sqlite3VdbeMakeLabel(pParse); pRJ->endSubrtn = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp3(v, OP_Return, pRJ->regReturn, pRJ->addrSubrtn, 1); VdbeCoverage(v); @@ -170352,7 +177281,6 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ pLoop = pLevel->pWLoop; if( pLevel->op!=OP_Noop ){ #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT - int addrSeek = 0; Index *pIdx; int n; if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED @@ -170364,6 +177292,10 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ ){ int r1 = pParse->nMem+1; int j, op; + int addrIfNull = 0; /* Init to avoid false-positive compiler warning */ + if( pLevel->iLeftJoin ){ + addrIfNull = sqlite3VdbeAddOp2(v, OP_IfNullRow, pLevel->iIdxCur, r1); + } for(j=0; j<n; j++){ sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j); } @@ -170373,26 +177305,37 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ VdbeCoverageIf(v, op==OP_SeekLT); VdbeCoverageIf(v, op==OP_SeekGT); sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2); + if( pLevel->iLeftJoin ){ + sqlite3VdbeJumpHere(v, addrIfNull); + } } #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */ - /* The common case: Advance to the next row */ - if( pLevel->addrCont ) sqlite3VdbeResolveLabel(v, pLevel->addrCont); + } + if( pTabList->a[pLevel->iFrom].fg.fromExists ){ + /* This is an EXISTS-to-JOIN optimization loop. If this loop sees a + ** successful row, it should break out of itself. */ + sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk); + VdbeComment((v, "EXISTS break %d", i)); + } + sqlite3VdbeResolveLabel(v, pLevel->addrCont); + if( pLevel->op!=OP_Noop ){ sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3); sqlite3VdbeChangeP5(v, pLevel->p5); VdbeCoverage(v); VdbeCoverageIf(v, pLevel->op==OP_Next); VdbeCoverageIf(v, pLevel->op==OP_Prev); VdbeCoverageIf(v, pLevel->op==OP_VNext); +#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT + if( addrSeek ){ + sqlite3VdbeJumpHere(v, addrSeek); + addrSeek = 0; + } +#endif if( pLevel->regBignull ){ sqlite3VdbeResolveLabel(v, pLevel->addrBignull); sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1); VdbeCoverage(v); } -#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT - if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek); -#endif - }else if( pLevel->addrCont ){ - sqlite3VdbeResolveLabel(v, pLevel->addrCont); } if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){ struct InLoop *pIn; @@ -170408,16 +177351,14 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0; if( pLevel->iLeftJoin ){ - /* For LEFT JOIN queries, cursor pIn->iCur may not have been - ** opened yet. This occurs for WHERE clauses such as - ** "a = ? AND b IN (...)", where the index is on (a, b). If - ** the RHS of the (a=?) is NULL, then the "b IN (...)" may - ** never have been coded, but the body of the loop run to - ** return the null-row. So, if the cursor is not open yet, - ** jump over the OP_Next or OP_Prev instruction about to - ** be coded. */ - sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur, - sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut); + /* For LEFT JOIN queries, cursor pIn->iCur might have been + ** disabled by OP_NullRow. This occurs for WHERE clauses such + ** as "a = ? AND b IN (...)", where the index is on (a, b). + ** When the OP_IfNullRow jump is taken, the pIn->iBase register + ** is NULLed out as a side effect. But as that register is not + ** used when the jump is taken, the side-effect is harmless. */ + sqlite3VdbeAddOp3(v, OP_IfNullRow, pIn->iCur, + sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut, pIn->iBase); VdbeCoverage(v); } if( bEarlyOut ){ @@ -170486,6 +177427,15 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ } sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); } + if( ws & WHERE_IN_ABLE ){ + int m; + for(m=0; m<pLevel->u.in.nIn; m++){ + struct InLoop *pIn = &pLevel->u.in.aInLoop[m]; + if( pIn->eEndLoopOp!=OP_Noop ){ + sqlite3VdbeAddOp1(v, OP_NullRow, pIn->iCur); + } + } + } if( pLevel->op==OP_Return ){ sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); }else{ @@ -170613,14 +177563,28 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ pOp->p2 = x; pOp->p1 = pLevel->iIdxCur; OpcodeRewriteTrace(db, k, pOp); - }else{ - /* Unable to translate the table reference into an index - ** reference. Verify that this is harmless - that the - ** table being referenced really is open. - */ + }else if( pLoop->wsFlags & (WHERE_IDX_ONLY|WHERE_EXPRIDX) ){ if( pLoop->wsFlags & WHERE_IDX_ONLY ){ + /* An error. pLoop is supposed to be a covering index loop, + ** and yet the VM code refers to a column of the table that + ** is not part of the index. */ sqlite3ErrorMsg(pParse, "internal query planner error"); pParse->rc = SQLITE_INTERNAL; + }else{ + /* The WHERE_EXPRIDX flag is set by the planner when it is likely + ** that pLoop is a covering index loop, but it is not possible + ** to be 100% sure. In this case, any OP_Explain opcode + ** corresponding to this loop describes the index as a "COVERING + ** INDEX". But, pOp proves that pLoop is not actually a covering + ** index loop. So clear the WHERE_EXPRIDX flag and rewrite the + ** text that accompanies the OP_Explain opcode, if any. */ + pLoop->wsFlags &= ~WHERE_EXPRIDX; + sqlite3WhereAddExplainText(pParse, + pLevel->addrBody-1, + pTabList, + pLevel, + pWInfo->wctrlFlags + ); } } }else if( pOp->opcode==OP_Rowid ){ @@ -170880,7 +177844,7 @@ static void nth_valueStepFunc( break; case SQLITE_FLOAT: { double fVal = sqlite3_value_double(apArg[1]); - if( ((i64)fVal)!=fVal ) goto error_out; + if( sqlite3RealToI64(fVal)!=fVal ) goto error_out; iVal = (i64)fVal; break; } @@ -171005,6 +177969,7 @@ static void percent_rankInvFunc( UNUSED_PARAMETER(nArg); assert( nArg==0 ); UNUSED_PARAMETER(apArg); p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); + assert( p!=0 ); p->nStep++; } static void percent_rankValueFunc(sqlite3_context *pCtx){ @@ -171050,6 +178015,7 @@ static void cume_distInvFunc( UNUSED_PARAMETER(nArg); assert( nArg==0 ); UNUSED_PARAMETER(apArg); p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p)); + assert( p!=0 ); p->nStep++; } static void cume_distValueFunc(sqlite3_context *pCtx){ @@ -171106,6 +178072,7 @@ static void ntileInvFunc( assert( nArg==1 ); UNUSED_PARAMETER(nArg); UNUSED_PARAMETER(apArg); p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p)); + assert( p!=0 ); p->iRow++; } static void ntileValueFunc(sqlite3_context *pCtx){ @@ -171375,7 +178342,7 @@ SQLITE_PRIVATE void sqlite3WindowUpdate( pWin->eEnd = aUp[i].eEnd; pWin->eExclude = 0; if( pWin->eStart==TK_FOLLOWING ){ - pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1"); + pWin->pStart = sqlite3ExprInt32(db, 1); } break; } @@ -171463,7 +178430,9 @@ static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){ p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup); } if( p->pSub ){ - int f = pExpr->flags & EP_Collate; + int f = pExpr->flags & (EP_Collate|EP_OuterON|EP_InnerON); + int iJoin = pExpr->w.iJoin; + assert( ExprHasProperty(pExpr, EP_Static)==0 ); ExprSetProperty(pExpr, EP_Static); sqlite3ExprDelete(pParse->db, pExpr); @@ -171475,6 +178444,7 @@ static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){ pExpr->iTable = p->pWin->iEphCsr; pExpr->y.pTab = p->pTab; pExpr->flags = f; + if( (f & (EP_OuterON|EP_InnerON)) ) pExpr->w.iJoin = iJoin; } if( pParse->db->mallocFailed ) return WRC_Abort; break; @@ -171567,7 +178537,7 @@ static ExprList *exprListAppendList( int iDummy; Expr *pSub; pSub = sqlite3ExprSkipCollateAndLikely(pDup); - if( sqlite3ExprIsInteger(pSub, &iDummy, 0) ){ + if( sqlite3ExprIsInteger(pSub, &iDummy, 0, 0) ){ pSub->op = TK_NULL; pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse); pSub->u.zToken = 0; @@ -171653,7 +178623,7 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){ p->pWhere = 0; p->pGroupBy = 0; p->pHaving = 0; - p->selFlags &= ~SF_Aggregate; + p->selFlags &= ~(u32)SF_Aggregate; p->selFlags |= SF_WinRewrite; /* Create the ORDER BY clause for the sub-select. This is the concatenation @@ -171720,9 +178690,7 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){ ** keep everything legal in this case. */ if( pSublist==0 ){ - pSublist = sqlite3ExprListAppend(pParse, 0, - sqlite3Expr(db, TK_INTEGER, "0") - ); + pSublist = sqlite3ExprListAppend(pParse, 0, sqlite3ExprInt32(db, 0)); } pSub = sqlite3SelectNew( @@ -172328,6 +179296,7 @@ static void windowAggStep( int regArg; int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin); int i; + int addrIf = 0; assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED ); @@ -172344,6 +179313,18 @@ static void windowAggStep( } regArg = reg; + if( pWin->pFilter ){ + int regTmp; + assert( ExprUseXList(pWin->pOwner) ); + assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr ); + assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 ); + regTmp = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp); + addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1); + VdbeCoverage(v); + sqlite3ReleaseTempReg(pParse, regTmp); + } + if( pMWin->regStartRowid==0 && (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && (pWin->eStart!=TK_UNBOUNDED) @@ -172363,25 +179344,13 @@ static void windowAggStep( } sqlite3VdbeJumpHere(v, addrIsNull); }else if( pWin->regApp ){ + assert( pWin->pFilter==0 ); assert( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ); assert( bInverse==0 || bInverse==1 ); sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1); }else if( pFunc->xSFunc!=noopStepFunc ){ - int addrIf = 0; - if( pWin->pFilter ){ - int regTmp; - assert( ExprUseXList(pWin->pOwner) ); - assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr ); - assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 ); - regTmp = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp); - addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1); - VdbeCoverage(v); - sqlite3ReleaseTempReg(pParse, regTmp); - } - if( pWin->bExprArgs ){ int iOp = sqlite3VdbeCurrentAddr(v); int iEnd; @@ -172408,12 +179377,13 @@ static void windowAggStep( sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep, bInverse, regArg, pWin->regAccum); sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, (u8)nArg); + sqlite3VdbeChangeP5(v, (u16)nArg); if( pWin->bExprArgs ){ sqlite3ReleaseTempRange(pParse, regArg, nArg); } - if( addrIf ) sqlite3VdbeJumpHere(v, addrIf); } + + if( addrIf ) sqlite3VdbeJumpHere(v, addrIf); } } @@ -173209,7 +180179,7 @@ static int windowExprGtZero(Parse *pParse, Expr *pExpr){ ** ** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING ** -** ... loop started by sqlite3WhereBegin() ... +** ... loop started by sqlite3WhereBegin() ... ** if( new partition ){ ** Gosub flush ** } @@ -173727,6 +180697,12 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep( addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1); }else{ assert( pMWin->eEnd==TK_FOLLOWING ); + /* assert( regStart>=0 ); + ** regEnd = regEnd - regStart; + ** regStart = 0; */ + sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regEnd); + sqlite3VdbeAddOp2(v, OP_Integer, 0, regStart); + addrStart = sqlite3VdbeCurrentAddr(v); addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1); addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1); @@ -173791,6 +180767,11 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep( /* #include "sqliteInt.h" */ +/* +** Verify that the pParse->isCreate field is set +*/ +#define ASSERT_IS_CREATE assert(pParse->isCreate) + /* ** Disable all error recovery processing in the parser push-down ** automaton. @@ -173840,6 +180821,13 @@ struct TrigEvent { int a; IdList * b; }; struct FrameBound { int eType; Expr *pExpr; }; +/* +** Generate a syntax error +*/ +static void parserSyntaxError(Parse *pParse, Token *p){ + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", p); +} + /* ** Disable lookaside memory allocation for objects that might be ** shared across database connections. @@ -173847,6 +180835,10 @@ struct FrameBound { int eType; Expr *pExpr; }; static void disableLookaside(Parse *pParse){ sqlite3 *db = pParse->db; pParse->disableLookaside++; +#ifdef SQLITE_DEBUG + pParse->isCreate = 1; +#endif + memset(&pParse->u1.cr, 0, sizeof(pParse->u1.cr)); DisableLookaside; } @@ -173922,8 +180914,23 @@ static void updateDeleteLimitError( ** sqlite3_realloc() that includes a call to sqlite3FaultSim() to facilitate ** testing. */ - static void *parserStackRealloc(void *pOld, sqlite3_uint64 newSize){ - return sqlite3FaultSim(700) ? 0 : sqlite3_realloc(pOld, newSize); + static void *parserStackRealloc( + void *pOld, /* Prior allocation */ + sqlite3_uint64 newSize, /* Requested new alloation size */ + Parse *pParse /* Parsing context */ + ){ + void *p = sqlite3FaultSim(700) ? 0 : sqlite3_realloc(pOld, newSize); + if( p==0 ) sqlite3OomFault(pParse->db); + return p; + } + static void parserStackFree(void *pOld, Parse *pParse){ + (void)pParse; + sqlite3_free(pOld); + } + + /* Return an integer that is the maximum allowed stack size */ + static int parserStackSizeLimit(Parse *pParse){ + return pParse->db->aLimit[SQLITE_LIMIT_PARSER_DEPTH]; } @@ -173962,15 +180969,46 @@ static void updateDeleteLimitError( } - /* A routine to convert a binary TK_IS or TK_ISNOT expression into a - ** unary TK_ISNULL or TK_NOTNULL expression. */ - static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){ - sqlite3 *db = pParse->db; - if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){ - pA->op = (u8)op; - sqlite3ExprDelete(db, pA->pRight); - pA->pRight = 0; + /* Create a TK_ISNULL or TK_NOTNULL expression, perhaps optimized to + ** to TK_TRUEFALSE, if possible */ + static Expr *sqlite3PExprIsNull( + Parse *pParse, /* Parsing context */ + int op, /* TK_ISNULL or TK_NOTNULL */ + Expr *pLeft /* Operand */ + ){ + Expr *p = pLeft; + assert( op==TK_ISNULL || op==TK_NOTNULL ); + assert( pLeft!=0 ); + while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ + p = p->pLeft; + assert( p!=0 ); + } + switch( p->op ){ + case TK_INTEGER: + case TK_STRING: + case TK_FLOAT: + case TK_BLOB: + sqlite3ExprDeferredDelete(pParse, pLeft); + return sqlite3ExprInt32(pParse->db, op==TK_NOTNULL); + default: + break; } + return sqlite3PExpr(pParse, op, pLeft, 0); + } + + /* Create a TK_IS or TK_ISNOT operator, perhaps optimized to + ** TK_ISNULL or TK_NOTNULL or TK_TRUEFALSE. */ + static Expr *sqlite3PExprIs( + Parse *pParse, /* Parsing context */ + int op, /* TK_IS or TK_ISNOT */ + Expr *pLeft, /* Left operand */ + Expr *pRight /* Right operand */ + ){ + if( pRight && pRight->op==TK_NULL ){ + sqlite3ExprDeferredDelete(pParse, pRight); + return sqlite3PExprIsNull(pParse, op==TK_IS ? TK_ISNULL : TK_NOTNULL, pLeft); + } + return sqlite3PExpr(pParse, op, pLeft, pRight); } /* Add a single new term to an ExprList that is used to store a @@ -174187,7 +181225,8 @@ static void updateDeleteLimitError( #define TK_ERROR 182 #define TK_QNUMBER 183 #define TK_SPACE 184 -#define TK_ILLEGAL 185 +#define TK_COMMENT 185 +#define TK_ILLEGAL 186 #endif /**************** End token definitions ***************************************/ @@ -174279,35 +181318,44 @@ typedef union { Select* yy555; } YYMINORTYPE; #ifndef YYSTACKDEPTH -#define YYSTACKDEPTH 100 +#define YYSTACKDEPTH 50 #endif #define sqlite3ParserARG_SDECL #define sqlite3ParserARG_PDECL #define sqlite3ParserARG_PARAM #define sqlite3ParserARG_FETCH #define sqlite3ParserARG_STORE +#undef YYREALLOC #define YYREALLOC parserStackRealloc -#define YYFREE sqlite3_free +#undef YYFREE +#define YYFREE parserStackFree +#undef YYDYNSTACK #define YYDYNSTACK 1 +#undef YYSIZELIMIT +#define YYSIZELIMIT parserStackSizeLimit +#define sqlite3ParserCTX(P) ((P)->pParse) #define sqlite3ParserCTX_SDECL Parse *pParse; #define sqlite3ParserCTX_PDECL ,Parse *pParse #define sqlite3ParserCTX_PARAM ,pParse #define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse; #define sqlite3ParserCTX_STORE yypParser->pParse=pParse; +#undef YYERRORSYMBOL +#undef YYERRSYMDT +#undef YYFALLBACK #define YYFALLBACK 1 -#define YYNSTATE 583 -#define YYNRULE 409 -#define YYNRULE_WITH_ACTION 344 -#define YYNTOKEN 186 -#define YY_MAX_SHIFT 582 -#define YY_MIN_SHIFTREDUCE 845 -#define YY_MAX_SHIFTREDUCE 1253 -#define YY_ERROR_ACTION 1254 -#define YY_ACCEPT_ACTION 1255 -#define YY_NO_ACTION 1256 -#define YY_MIN_REDUCE 1257 -#define YY_MAX_REDUCE 1665 -#define YY_MIN_DSTRCTR 205 +#define YYNSTATE 600 +#define YYNRULE 412 +#define YYNRULE_WITH_ACTION 348 +#define YYNTOKEN 187 +#define YY_MAX_SHIFT 599 +#define YY_MIN_SHIFTREDUCE 867 +#define YY_MAX_SHIFTREDUCE 1278 +#define YY_ERROR_ACTION 1279 +#define YY_ACCEPT_ACTION 1280 +#define YY_NO_ACTION 1281 +#define YY_MIN_REDUCE 1282 +#define YY_MAX_REDUCE 1693 +#define YY_MIN_DSTRCTR 206 #define YY_MAX_DSTRCTR 319 /************* End control #defines *******************************************/ #define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0]))) @@ -174391,643 +181439,680 @@ typedef union { ** yy_default[] Default action for each state. ** *********** Begin parsing tables **********************************************/ -#define YY_ACTTAB_COUNT (2207) +#define YY_ACTTAB_COUNT (2379) static const YYACTIONTYPE yy_action[] = { - /* 0 */ 130, 127, 234, 282, 282, 1328, 576, 1307, 460, 289, - /* 10 */ 289, 576, 1622, 381, 576, 1328, 573, 576, 562, 413, - /* 20 */ 1300, 1542, 573, 481, 562, 524, 460, 459, 558, 82, - /* 30 */ 82, 983, 294, 375, 51, 51, 498, 61, 61, 984, - /* 40 */ 82, 82, 1577, 137, 138, 91, 7, 1228, 1228, 1063, - /* 50 */ 1066, 1053, 1053, 135, 135, 136, 136, 136, 136, 413, - /* 60 */ 288, 288, 182, 288, 288, 481, 536, 288, 288, 130, - /* 70 */ 127, 234, 432, 573, 525, 562, 573, 557, 562, 1290, - /* 80 */ 573, 421, 562, 137, 138, 91, 559, 1228, 1228, 1063, - /* 90 */ 1066, 1053, 1053, 135, 135, 136, 136, 136, 136, 296, - /* 100 */ 460, 398, 1249, 134, 134, 134, 134, 133, 133, 132, - /* 110 */ 132, 132, 131, 128, 451, 44, 1050, 1050, 1064, 1067, - /* 120 */ 1255, 1, 1, 582, 2, 1259, 581, 1174, 1259, 1174, - /* 130 */ 321, 413, 155, 321, 1584, 155, 379, 112, 498, 1341, - /* 140 */ 456, 299, 1341, 134, 134, 134, 134, 133, 133, 132, - /* 150 */ 132, 132, 131, 128, 451, 137, 138, 91, 1105, 1228, - /* 160 */ 1228, 1063, 1066, 1053, 1053, 135, 135, 136, 136, 136, - /* 170 */ 136, 1204, 320, 567, 288, 288, 283, 288, 288, 523, - /* 180 */ 523, 1250, 139, 1541, 7, 214, 503, 573, 1169, 562, - /* 190 */ 573, 1054, 562, 136, 136, 136, 136, 129, 401, 547, - /* 200 */ 487, 1169, 245, 1568, 1169, 245, 133, 133, 132, 132, - /* 210 */ 132, 131, 128, 451, 261, 134, 134, 134, 134, 133, - /* 220 */ 133, 132, 132, 132, 131, 128, 451, 451, 1204, 1205, - /* 230 */ 1204, 130, 127, 234, 455, 413, 182, 455, 130, 127, - /* 240 */ 234, 134, 134, 134, 134, 133, 133, 132, 132, 132, - /* 250 */ 131, 128, 451, 136, 136, 136, 136, 538, 576, 137, - /* 260 */ 138, 91, 261, 1228, 1228, 1063, 1066, 1053, 1053, 135, - /* 270 */ 135, 136, 136, 136, 136, 44, 472, 346, 1204, 472, - /* 280 */ 346, 51, 51, 418, 93, 157, 134, 134, 134, 134, - /* 290 */ 133, 133, 132, 132, 132, 131, 128, 451, 166, 363, - /* 300 */ 298, 134, 134, 134, 134, 133, 133, 132, 132, 132, - /* 310 */ 131, 128, 451, 1293, 461, 1570, 423, 377, 275, 134, - /* 320 */ 134, 134, 134, 133, 133, 132, 132, 132, 131, 128, - /* 330 */ 451, 418, 320, 567, 1292, 1204, 1205, 1204, 257, 413, - /* 340 */ 483, 511, 508, 507, 94, 132, 132, 132, 131, 128, - /* 350 */ 451, 506, 1204, 548, 548, 388, 576, 384, 7, 413, - /* 360 */ 550, 229, 522, 137, 138, 91, 530, 1228, 1228, 1063, - /* 370 */ 1066, 1053, 1053, 135, 135, 136, 136, 136, 136, 51, - /* 380 */ 51, 1582, 380, 137, 138, 91, 331, 1228, 1228, 1063, - /* 390 */ 1066, 1053, 1053, 135, 135, 136, 136, 136, 136, 320, - /* 400 */ 567, 288, 288, 320, 567, 1602, 582, 2, 1259, 1204, - /* 410 */ 1205, 1204, 1628, 321, 573, 155, 562, 576, 1511, 264, - /* 420 */ 231, 520, 1341, 134, 134, 134, 134, 133, 133, 132, - /* 430 */ 132, 132, 131, 128, 451, 519, 1511, 1513, 1333, 1333, - /* 440 */ 82, 82, 498, 134, 134, 134, 134, 133, 133, 132, - /* 450 */ 132, 132, 131, 128, 451, 1435, 257, 288, 288, 511, - /* 460 */ 508, 507, 944, 1568, 413, 1019, 1204, 943, 360, 506, - /* 470 */ 573, 1598, 562, 44, 575, 551, 551, 557, 1107, 1582, - /* 480 */ 544, 576, 1107, 40, 417, 245, 531, 1505, 137, 138, - /* 490 */ 91, 219, 1228, 1228, 1063, 1066, 1053, 1053, 135, 135, - /* 500 */ 136, 136, 136, 136, 81, 81, 1281, 1204, 413, 553, - /* 510 */ 1511, 48, 512, 448, 447, 493, 578, 455, 578, 344, - /* 520 */ 45, 1204, 1233, 1204, 1205, 1204, 428, 1235, 158, 882, - /* 530 */ 320, 567, 137, 138, 91, 1234, 1228, 1228, 1063, 1066, - /* 540 */ 1053, 1053, 135, 135, 136, 136, 136, 136, 134, 134, - /* 550 */ 134, 134, 133, 133, 132, 132, 132, 131, 128, 451, - /* 560 */ 1236, 576, 1236, 329, 1204, 1205, 1204, 387, 492, 403, - /* 570 */ 1040, 382, 489, 123, 568, 1569, 4, 377, 1204, 1205, - /* 580 */ 1204, 570, 570, 570, 82, 82, 882, 1029, 1331, 1331, - /* 590 */ 571, 1028, 134, 134, 134, 134, 133, 133, 132, 132, - /* 600 */ 132, 131, 128, 451, 288, 288, 1281, 1204, 576, 423, - /* 610 */ 576, 1568, 413, 423, 452, 378, 886, 573, 1279, 562, - /* 620 */ 46, 557, 532, 1028, 1028, 1030, 565, 130, 127, 234, - /* 630 */ 556, 82, 82, 82, 82, 479, 137, 138, 91, 462, - /* 640 */ 1228, 1228, 1063, 1066, 1053, 1053, 135, 135, 136, 136, - /* 650 */ 136, 136, 1188, 487, 1506, 1040, 413, 6, 1204, 50, - /* 660 */ 879, 121, 121, 948, 1204, 1205, 1204, 358, 557, 122, - /* 670 */ 316, 452, 577, 452, 535, 1204, 1028, 439, 303, 212, - /* 680 */ 137, 138, 91, 213, 1228, 1228, 1063, 1066, 1053, 1053, - /* 690 */ 135, 135, 136, 136, 136, 136, 134, 134, 134, 134, - /* 700 */ 133, 133, 132, 132, 132, 131, 128, 451, 1028, 1028, - /* 710 */ 1030, 1031, 35, 288, 288, 1204, 1205, 1204, 1040, 1339, - /* 720 */ 533, 123, 568, 1569, 4, 377, 573, 1019, 562, 353, - /* 730 */ 1277, 356, 1204, 1205, 1204, 1029, 488, 1188, 571, 1028, - /* 740 */ 134, 134, 134, 134, 133, 133, 132, 132, 132, 131, - /* 750 */ 128, 451, 576, 343, 288, 288, 449, 449, 449, 971, - /* 760 */ 413, 1627, 452, 911, 1187, 288, 288, 573, 464, 562, - /* 770 */ 238, 1028, 1028, 1030, 565, 82, 82, 498, 573, 411, - /* 780 */ 562, 344, 467, 332, 137, 138, 91, 197, 1228, 1228, - /* 790 */ 1063, 1066, 1053, 1053, 135, 135, 136, 136, 136, 136, - /* 800 */ 1188, 528, 1169, 1040, 413, 1110, 1110, 495, 1041, 121, - /* 810 */ 121, 1204, 317, 540, 862, 1169, 1244, 122, 1169, 452, - /* 820 */ 577, 452, 1340, 198, 1028, 1204, 481, 526, 137, 138, - /* 830 */ 91, 560, 1228, 1228, 1063, 1066, 1053, 1053, 135, 135, - /* 840 */ 136, 136, 136, 136, 134, 134, 134, 134, 133, 133, - /* 850 */ 132, 132, 132, 131, 128, 451, 1028, 1028, 1030, 1031, - /* 860 */ 35, 1204, 288, 288, 1204, 477, 288, 288, 1204, 1205, - /* 870 */ 1204, 539, 481, 437, 470, 573, 1451, 562, 364, 573, - /* 880 */ 1153, 562, 1204, 1205, 1204, 1188, 5, 576, 134, 134, - /* 890 */ 134, 134, 133, 133, 132, 132, 132, 131, 128, 451, - /* 900 */ 221, 214, 302, 96, 1149, 1657, 232, 1657, 413, 392, - /* 910 */ 19, 19, 1024, 949, 406, 373, 1595, 1085, 1204, 1205, - /* 920 */ 1204, 1204, 1205, 1204, 1204, 426, 1149, 1658, 413, 1658, - /* 930 */ 1659, 399, 137, 138, 91, 3, 1228, 1228, 1063, 1066, - /* 940 */ 1053, 1053, 135, 135, 136, 136, 136, 136, 304, 1311, - /* 950 */ 514, 1204, 137, 138, 91, 1498, 1228, 1228, 1063, 1066, - /* 960 */ 1053, 1053, 135, 135, 136, 136, 136, 136, 434, 131, - /* 970 */ 128, 451, 375, 1204, 274, 291, 372, 517, 367, 516, - /* 980 */ 262, 1204, 1205, 1204, 1147, 227, 363, 448, 447, 1435, - /* 990 */ 1568, 1310, 134, 134, 134, 134, 133, 133, 132, 132, - /* 1000 */ 132, 131, 128, 451, 1568, 576, 1147, 487, 1204, 1205, - /* 1010 */ 1204, 442, 134, 134, 134, 134, 133, 133, 132, 132, - /* 1020 */ 132, 131, 128, 451, 386, 576, 485, 576, 19, 19, - /* 1030 */ 1204, 1205, 1204, 1345, 1236, 970, 1236, 574, 47, 936, - /* 1040 */ 936, 473, 413, 431, 1552, 573, 1125, 562, 19, 19, - /* 1050 */ 19, 19, 49, 336, 850, 851, 852, 111, 1368, 315, - /* 1060 */ 429, 576, 413, 433, 341, 306, 137, 138, 91, 115, - /* 1070 */ 1228, 1228, 1063, 1066, 1053, 1053, 135, 135, 136, 136, - /* 1080 */ 136, 136, 576, 1309, 82, 82, 137, 138, 91, 529, - /* 1090 */ 1228, 1228, 1063, 1066, 1053, 1053, 135, 135, 136, 136, - /* 1100 */ 136, 136, 1569, 222, 377, 19, 19, 305, 1126, 1169, - /* 1110 */ 398, 1148, 22, 22, 498, 333, 1569, 335, 377, 576, - /* 1120 */ 438, 445, 1169, 1127, 486, 1169, 134, 134, 134, 134, - /* 1130 */ 133, 133, 132, 132, 132, 131, 128, 451, 1128, 576, - /* 1140 */ 902, 576, 145, 145, 6, 576, 134, 134, 134, 134, - /* 1150 */ 133, 133, 132, 132, 132, 131, 128, 451, 214, 1336, - /* 1160 */ 922, 576, 19, 19, 19, 19, 1282, 419, 19, 19, - /* 1170 */ 923, 412, 515, 141, 576, 1169, 413, 206, 465, 207, - /* 1180 */ 903, 215, 1575, 552, 147, 147, 7, 227, 1169, 411, - /* 1190 */ 1250, 1169, 120, 307, 117, 307, 413, 66, 66, 334, - /* 1200 */ 137, 138, 91, 119, 1228, 1228, 1063, 1066, 1053, 1053, - /* 1210 */ 135, 135, 136, 136, 136, 136, 413, 285, 209, 969, - /* 1220 */ 137, 138, 91, 471, 1228, 1228, 1063, 1066, 1053, 1053, - /* 1230 */ 135, 135, 136, 136, 136, 136, 435, 10, 1450, 267, - /* 1240 */ 137, 126, 91, 1435, 1228, 1228, 1063, 1066, 1053, 1053, - /* 1250 */ 135, 135, 136, 136, 136, 136, 1435, 1435, 410, 409, - /* 1260 */ 134, 134, 134, 134, 133, 133, 132, 132, 132, 131, - /* 1270 */ 128, 451, 576, 969, 576, 1224, 498, 373, 1595, 1554, - /* 1280 */ 134, 134, 134, 134, 133, 133, 132, 132, 132, 131, - /* 1290 */ 128, 451, 532, 457, 576, 82, 82, 82, 82, 111, - /* 1300 */ 134, 134, 134, 134, 133, 133, 132, 132, 132, 131, - /* 1310 */ 128, 451, 109, 233, 430, 1576, 546, 67, 67, 7, - /* 1320 */ 413, 351, 550, 1550, 260, 259, 258, 494, 443, 569, - /* 1330 */ 419, 983, 446, 1224, 450, 545, 1207, 576, 969, 984, - /* 1340 */ 413, 475, 1449, 1574, 1180, 138, 91, 7, 1228, 1228, - /* 1350 */ 1063, 1066, 1053, 1053, 135, 135, 136, 136, 136, 136, - /* 1360 */ 21, 21, 267, 576, 300, 1126, 91, 233, 1228, 1228, - /* 1370 */ 1063, 1066, 1053, 1053, 135, 135, 136, 136, 136, 136, - /* 1380 */ 1127, 373, 1595, 161, 1573, 16, 53, 53, 7, 108, - /* 1390 */ 533, 38, 969, 125, 1207, 1128, 1180, 576, 1224, 123, - /* 1400 */ 568, 893, 4, 324, 134, 134, 134, 134, 133, 133, - /* 1410 */ 132, 132, 132, 131, 128, 451, 571, 564, 534, 576, - /* 1420 */ 68, 68, 576, 39, 134, 134, 134, 134, 133, 133, - /* 1430 */ 132, 132, 132, 131, 128, 451, 576, 160, 1571, 1223, - /* 1440 */ 452, 576, 54, 54, 576, 69, 69, 576, 1366, 576, - /* 1450 */ 420, 184, 565, 463, 297, 576, 1224, 463, 297, 70, - /* 1460 */ 70, 576, 44, 474, 71, 71, 576, 72, 72, 576, - /* 1470 */ 73, 73, 55, 55, 411, 874, 242, 576, 56, 56, - /* 1480 */ 576, 1040, 576, 478, 57, 57, 576, 121, 121, 59, - /* 1490 */ 59, 23, 60, 60, 411, 122, 319, 452, 577, 452, - /* 1500 */ 74, 74, 1028, 75, 75, 76, 76, 411, 290, 20, - /* 1510 */ 20, 108, 287, 231, 553, 123, 568, 325, 4, 320, - /* 1520 */ 567, 97, 218, 944, 1144, 328, 400, 576, 943, 576, - /* 1530 */ 1380, 424, 571, 874, 1028, 1028, 1030, 1031, 35, 293, - /* 1540 */ 534, 576, 1104, 576, 1104, 9, 576, 342, 576, 111, - /* 1550 */ 77, 77, 143, 143, 576, 205, 452, 222, 1379, 889, - /* 1560 */ 576, 901, 900, 1188, 144, 144, 78, 78, 565, 62, - /* 1570 */ 62, 79, 79, 323, 1021, 576, 266, 63, 63, 908, - /* 1580 */ 909, 1589, 542, 80, 80, 576, 371, 541, 123, 568, - /* 1590 */ 480, 4, 266, 482, 244, 266, 370, 1040, 64, 64, - /* 1600 */ 576, 466, 576, 121, 121, 571, 1557, 576, 170, 170, - /* 1610 */ 576, 122, 576, 452, 577, 452, 576, 889, 1028, 576, - /* 1620 */ 165, 576, 111, 171, 171, 87, 87, 337, 1616, 452, - /* 1630 */ 65, 65, 1530, 83, 83, 146, 146, 986, 987, 84, - /* 1640 */ 84, 565, 168, 168, 148, 148, 1092, 347, 1032, 111, - /* 1650 */ 1028, 1028, 1030, 1031, 35, 542, 1103, 576, 1103, 576, - /* 1660 */ 543, 123, 568, 504, 4, 263, 576, 361, 1529, 111, - /* 1670 */ 1040, 1088, 576, 263, 576, 490, 121, 121, 571, 1188, - /* 1680 */ 142, 142, 169, 169, 122, 576, 452, 577, 452, 162, - /* 1690 */ 162, 1028, 576, 563, 576, 152, 152, 151, 151, 348, - /* 1700 */ 1376, 974, 452, 266, 1092, 942, 1032, 125, 149, 149, - /* 1710 */ 939, 576, 125, 576, 565, 150, 150, 86, 86, 872, - /* 1720 */ 352, 159, 576, 1028, 1028, 1030, 1031, 35, 542, 941, - /* 1730 */ 576, 125, 355, 541, 88, 88, 85, 85, 357, 359, - /* 1740 */ 1324, 1308, 366, 1040, 376, 52, 52, 499, 1389, 121, - /* 1750 */ 121, 1434, 1188, 58, 58, 1362, 1374, 122, 1439, 452, - /* 1760 */ 577, 452, 1289, 167, 1028, 1280, 280, 1268, 1267, 1269, - /* 1770 */ 1609, 1359, 312, 313, 12, 314, 397, 1421, 224, 1416, - /* 1780 */ 295, 237, 1409, 339, 340, 1426, 301, 345, 484, 228, - /* 1790 */ 1371, 1307, 1372, 1370, 1425, 404, 1028, 1028, 1030, 1031, - /* 1800 */ 35, 1601, 1192, 454, 509, 369, 292, 1502, 210, 1501, - /* 1810 */ 1369, 396, 396, 395, 277, 393, 211, 566, 859, 1612, - /* 1820 */ 1244, 123, 568, 391, 4, 1188, 223, 270, 1549, 1547, - /* 1830 */ 1241, 239, 186, 327, 422, 96, 195, 220, 571, 235, - /* 1840 */ 180, 326, 188, 468, 190, 1507, 191, 192, 92, 193, - /* 1850 */ 469, 95, 1422, 13, 502, 247, 1430, 109, 199, 402, - /* 1860 */ 476, 405, 452, 1496, 1428, 1427, 14, 491, 251, 102, - /* 1870 */ 497, 1518, 241, 281, 565, 253, 203, 354, 500, 254, - /* 1880 */ 175, 1270, 407, 43, 350, 518, 1327, 436, 255, 1326, - /* 1890 */ 1325, 1318, 104, 893, 1626, 229, 408, 440, 1625, 441, - /* 1900 */ 240, 310, 1296, 1040, 311, 1317, 527, 1594, 1297, 121, - /* 1910 */ 121, 368, 1295, 1624, 268, 269, 1580, 122, 1579, 452, - /* 1920 */ 577, 452, 374, 444, 1028, 1394, 1393, 140, 553, 90, - /* 1930 */ 568, 11, 4, 1483, 383, 414, 385, 110, 116, 216, - /* 1940 */ 320, 567, 1350, 555, 42, 318, 571, 537, 1349, 389, - /* 1950 */ 390, 579, 1198, 276, 279, 278, 1028, 1028, 1030, 1031, - /* 1960 */ 35, 580, 415, 1265, 458, 1260, 416, 185, 1534, 172, - /* 1970 */ 452, 1535, 173, 156, 308, 846, 1533, 1532, 453, 217, - /* 1980 */ 225, 89, 565, 174, 322, 1188, 226, 236, 1102, 154, - /* 1990 */ 1100, 330, 176, 187, 1223, 189, 925, 338, 243, 1116, - /* 2000 */ 246, 194, 177, 178, 425, 427, 98, 99, 196, 100, - /* 2010 */ 101, 1040, 179, 1119, 248, 1115, 249, 121, 121, 24, - /* 2020 */ 163, 250, 349, 1108, 266, 122, 1238, 452, 577, 452, - /* 2030 */ 1192, 454, 1028, 200, 292, 496, 252, 201, 861, 396, - /* 2040 */ 396, 395, 277, 393, 15, 501, 859, 370, 292, 256, - /* 2050 */ 202, 554, 505, 396, 396, 395, 277, 393, 103, 239, - /* 2060 */ 859, 327, 25, 26, 1028, 1028, 1030, 1031, 35, 326, - /* 2070 */ 362, 510, 891, 239, 365, 327, 513, 904, 105, 309, - /* 2080 */ 164, 181, 27, 326, 106, 521, 107, 1185, 1069, 1155, - /* 2090 */ 17, 1154, 284, 1188, 286, 978, 265, 204, 125, 1171, - /* 2100 */ 241, 230, 972, 1175, 28, 1160, 29, 1179, 175, 1173, - /* 2110 */ 30, 43, 31, 1178, 241, 32, 41, 549, 8, 33, - /* 2120 */ 208, 111, 175, 1083, 1070, 43, 113, 1068, 240, 114, - /* 2130 */ 1072, 34, 1073, 561, 1124, 118, 271, 36, 18, 1194, - /* 2140 */ 1033, 873, 240, 935, 124, 37, 272, 273, 1617, 572, - /* 2150 */ 183, 153, 394, 1193, 1256, 1256, 1256, 1256, 1256, 1256, - /* 2160 */ 1256, 1256, 1256, 414, 1256, 1256, 1256, 1256, 320, 567, - /* 2170 */ 1256, 1256, 1256, 1256, 1256, 1256, 1256, 414, 1256, 1256, - /* 2180 */ 1256, 1256, 320, 567, 1256, 1256, 1256, 1256, 1256, 1256, - /* 2190 */ 1256, 1256, 458, 1256, 1256, 1256, 1256, 1256, 1256, 1256, - /* 2200 */ 1256, 1256, 1256, 1256, 1256, 1256, 458, + /* 0 */ 134, 131, 238, 290, 290, 1353, 593, 1332, 478, 1606, + /* 10 */ 593, 1315, 593, 7, 593, 1353, 590, 593, 579, 424, + /* 20 */ 1566, 134, 131, 238, 1318, 541, 478, 477, 575, 84, + /* 30 */ 84, 1005, 303, 84, 84, 51, 51, 63, 63, 1006, + /* 40 */ 84, 84, 498, 141, 142, 93, 442, 1254, 1254, 1085, + /* 50 */ 1088, 1075, 1075, 139, 139, 140, 140, 140, 140, 424, + /* 60 */ 296, 296, 498, 296, 296, 567, 553, 296, 296, 1306, + /* 70 */ 574, 1358, 1358, 590, 542, 579, 590, 574, 579, 548, + /* 80 */ 590, 1304, 579, 141, 142, 93, 576, 1254, 1254, 1085, + /* 90 */ 1088, 1075, 1075, 139, 139, 140, 140, 140, 140, 399, + /* 100 */ 478, 395, 6, 138, 138, 138, 138, 137, 137, 136, + /* 110 */ 136, 136, 135, 132, 463, 44, 342, 593, 305, 1127, + /* 120 */ 1280, 1, 1, 599, 2, 1284, 598, 1200, 1284, 1200, + /* 130 */ 330, 424, 158, 330, 1613, 158, 390, 116, 308, 1366, + /* 140 */ 51, 51, 1366, 138, 138, 138, 138, 137, 137, 136, + /* 150 */ 136, 136, 135, 132, 463, 141, 142, 93, 515, 1254, + /* 160 */ 1254, 1085, 1088, 1075, 1075, 139, 139, 140, 140, 140, + /* 170 */ 140, 1230, 329, 584, 296, 296, 212, 296, 296, 568, + /* 180 */ 568, 488, 143, 1072, 1072, 1086, 1089, 590, 1195, 579, + /* 190 */ 590, 340, 579, 140, 140, 140, 140, 133, 392, 564, + /* 200 */ 536, 1195, 250, 425, 1195, 250, 137, 137, 136, 136, + /* 210 */ 136, 135, 132, 463, 291, 138, 138, 138, 138, 137, + /* 220 */ 137, 136, 136, 136, 135, 132, 463, 966, 1230, 1231, + /* 230 */ 1230, 412, 965, 467, 412, 424, 467, 489, 357, 1611, + /* 240 */ 391, 138, 138, 138, 138, 137, 137, 136, 136, 136, + /* 250 */ 135, 132, 463, 463, 134, 131, 238, 555, 1076, 141, + /* 260 */ 142, 93, 593, 1254, 1254, 1085, 1088, 1075, 1075, 139, + /* 270 */ 139, 140, 140, 140, 140, 1317, 134, 131, 238, 424, + /* 280 */ 549, 1597, 1531, 333, 97, 83, 83, 140, 140, 140, + /* 290 */ 140, 138, 138, 138, 138, 137, 137, 136, 136, 136, + /* 300 */ 135, 132, 463, 141, 142, 93, 1657, 1254, 1254, 1085, + /* 310 */ 1088, 1075, 1075, 139, 139, 140, 140, 140, 140, 138, + /* 320 */ 138, 138, 138, 137, 137, 136, 136, 136, 135, 132, + /* 330 */ 463, 591, 1230, 958, 958, 138, 138, 138, 138, 137, + /* 340 */ 137, 136, 136, 136, 135, 132, 463, 44, 398, 547, + /* 350 */ 1306, 136, 136, 136, 135, 132, 463, 386, 593, 442, + /* 360 */ 595, 145, 595, 138, 138, 138, 138, 137, 137, 136, + /* 370 */ 136, 136, 135, 132, 463, 500, 1230, 112, 550, 460, + /* 380 */ 459, 51, 51, 424, 296, 296, 479, 334, 1259, 1230, + /* 390 */ 1231, 1230, 1599, 1261, 388, 312, 444, 590, 246, 579, + /* 400 */ 546, 1260, 271, 235, 329, 584, 551, 141, 142, 93, + /* 410 */ 429, 1254, 1254, 1085, 1088, 1075, 1075, 139, 139, 140, + /* 420 */ 140, 140, 140, 22, 22, 1230, 1262, 424, 1262, 216, + /* 430 */ 296, 296, 98, 1230, 1231, 1230, 264, 884, 45, 528, + /* 440 */ 525, 524, 1041, 590, 1269, 579, 421, 420, 393, 523, + /* 450 */ 44, 141, 142, 93, 498, 1254, 1254, 1085, 1088, 1075, + /* 460 */ 1075, 139, 139, 140, 140, 140, 140, 138, 138, 138, + /* 470 */ 138, 137, 137, 136, 136, 136, 135, 132, 463, 593, + /* 480 */ 1611, 561, 1230, 1231, 1230, 23, 264, 515, 200, 528, + /* 490 */ 525, 524, 127, 585, 509, 4, 355, 487, 506, 523, + /* 500 */ 593, 498, 84, 84, 134, 131, 238, 329, 584, 588, + /* 510 */ 1627, 138, 138, 138, 138, 137, 137, 136, 136, 136, + /* 520 */ 135, 132, 463, 19, 19, 435, 1230, 1460, 297, 297, + /* 530 */ 311, 424, 1565, 464, 1631, 599, 2, 1284, 437, 574, + /* 540 */ 1107, 590, 330, 579, 158, 582, 489, 357, 573, 593, + /* 550 */ 592, 1366, 409, 1274, 1230, 141, 142, 93, 1364, 1254, + /* 560 */ 1254, 1085, 1088, 1075, 1075, 139, 139, 140, 140, 140, + /* 570 */ 140, 389, 84, 84, 1062, 567, 1230, 313, 1523, 593, + /* 580 */ 125, 125, 970, 1230, 1231, 1230, 296, 296, 126, 46, + /* 590 */ 464, 594, 464, 296, 296, 1050, 1230, 218, 439, 590, + /* 600 */ 1604, 579, 84, 84, 7, 403, 590, 515, 579, 325, + /* 610 */ 417, 1230, 1231, 1230, 250, 138, 138, 138, 138, 137, + /* 620 */ 137, 136, 136, 136, 135, 132, 463, 1050, 1050, 1052, + /* 630 */ 1053, 35, 1275, 1230, 1231, 1230, 424, 1370, 993, 574, + /* 640 */ 371, 414, 274, 412, 1597, 467, 1302, 552, 451, 590, + /* 650 */ 543, 579, 1530, 1230, 1231, 1230, 1214, 201, 409, 1174, + /* 660 */ 141, 142, 93, 223, 1254, 1254, 1085, 1088, 1075, 1075, + /* 670 */ 139, 139, 140, 140, 140, 140, 296, 296, 1250, 593, + /* 680 */ 424, 296, 296, 236, 529, 296, 296, 515, 100, 590, + /* 690 */ 1600, 579, 48, 1605, 590, 1230, 579, 7, 590, 577, + /* 700 */ 579, 904, 84, 84, 141, 142, 93, 496, 1254, 1254, + /* 710 */ 1085, 1088, 1075, 1075, 139, 139, 140, 140, 140, 140, + /* 720 */ 138, 138, 138, 138, 137, 137, 136, 136, 136, 135, + /* 730 */ 132, 463, 1365, 1230, 296, 296, 1250, 115, 1275, 326, + /* 740 */ 233, 539, 1062, 40, 282, 127, 585, 590, 4, 579, + /* 750 */ 329, 584, 1230, 1231, 1230, 1598, 593, 388, 904, 1051, + /* 760 */ 1356, 1356, 588, 1050, 138, 138, 138, 138, 137, 137, + /* 770 */ 136, 136, 136, 135, 132, 463, 185, 593, 1230, 19, + /* 780 */ 19, 1230, 971, 1597, 424, 1651, 464, 129, 908, 1195, + /* 790 */ 1230, 1231, 1230, 1325, 443, 1050, 1050, 1052, 582, 1603, + /* 800 */ 149, 149, 1195, 7, 5, 1195, 1687, 410, 141, 142, + /* 810 */ 93, 1536, 1254, 1254, 1085, 1088, 1075, 1075, 139, 139, + /* 820 */ 140, 140, 140, 140, 1214, 397, 593, 1062, 424, 1536, + /* 830 */ 1538, 50, 901, 125, 125, 1230, 1231, 1230, 1230, 1231, + /* 840 */ 1230, 126, 1230, 464, 594, 464, 515, 1230, 1050, 84, + /* 850 */ 84, 3, 141, 142, 93, 924, 1254, 1254, 1085, 1088, + /* 860 */ 1075, 1075, 139, 139, 140, 140, 140, 140, 138, 138, + /* 870 */ 138, 138, 137, 137, 136, 136, 136, 135, 132, 463, + /* 880 */ 1050, 1050, 1052, 1053, 35, 442, 457, 532, 433, 1230, + /* 890 */ 1062, 1361, 540, 540, 1598, 925, 388, 7, 1129, 1230, + /* 900 */ 1231, 1230, 1129, 1536, 1230, 1231, 1230, 1051, 570, 1214, + /* 910 */ 593, 1050, 138, 138, 138, 138, 137, 137, 136, 136, + /* 920 */ 136, 135, 132, 463, 6, 185, 1195, 1230, 231, 593, + /* 930 */ 382, 992, 424, 151, 151, 510, 1213, 557, 482, 1195, + /* 940 */ 381, 160, 1195, 1050, 1050, 1052, 1230, 1231, 1230, 422, + /* 950 */ 593, 447, 84, 84, 593, 217, 141, 142, 93, 593, + /* 960 */ 1254, 1254, 1085, 1088, 1075, 1075, 139, 139, 140, 140, + /* 970 */ 140, 140, 1214, 19, 19, 593, 424, 19, 19, 442, + /* 980 */ 1063, 442, 19, 19, 1230, 1231, 1230, 515, 445, 458, + /* 990 */ 1597, 386, 315, 1175, 1685, 556, 1685, 450, 84, 84, + /* 1000 */ 141, 142, 93, 505, 1254, 1254, 1085, 1088, 1075, 1075, + /* 1010 */ 139, 139, 140, 140, 140, 140, 138, 138, 138, 138, + /* 1020 */ 137, 137, 136, 136, 136, 135, 132, 463, 442, 1147, + /* 1030 */ 454, 1597, 362, 1041, 593, 462, 1460, 1233, 47, 1393, + /* 1040 */ 324, 565, 565, 115, 1148, 449, 7, 460, 459, 307, + /* 1050 */ 375, 354, 593, 113, 593, 329, 584, 19, 19, 1149, + /* 1060 */ 138, 138, 138, 138, 137, 137, 136, 136, 136, 135, + /* 1070 */ 132, 463, 209, 1173, 563, 19, 19, 19, 19, 49, + /* 1080 */ 424, 944, 1175, 1686, 1046, 1686, 218, 355, 484, 343, + /* 1090 */ 210, 945, 569, 562, 1262, 1233, 1262, 490, 314, 423, + /* 1100 */ 424, 1598, 1206, 388, 141, 142, 93, 440, 1254, 1254, + /* 1110 */ 1085, 1088, 1075, 1075, 139, 139, 140, 140, 140, 140, + /* 1120 */ 352, 316, 531, 316, 141, 142, 93, 549, 1254, 1254, + /* 1130 */ 1085, 1088, 1075, 1075, 139, 139, 140, 140, 140, 140, + /* 1140 */ 446, 10, 1598, 274, 388, 915, 281, 299, 383, 534, + /* 1150 */ 378, 533, 269, 593, 1206, 587, 587, 587, 374, 293, + /* 1160 */ 1579, 991, 1173, 302, 138, 138, 138, 138, 137, 137, + /* 1170 */ 136, 136, 136, 135, 132, 463, 53, 53, 520, 1250, + /* 1180 */ 593, 1147, 1576, 431, 138, 138, 138, 138, 137, 137, + /* 1190 */ 136, 136, 136, 135, 132, 463, 1148, 301, 593, 1577, + /* 1200 */ 593, 1307, 431, 54, 54, 593, 268, 593, 461, 461, + /* 1210 */ 461, 1149, 347, 492, 424, 135, 132, 463, 1146, 1195, + /* 1220 */ 474, 68, 68, 69, 69, 550, 332, 287, 21, 21, + /* 1230 */ 55, 55, 1195, 581, 424, 1195, 309, 1250, 141, 142, + /* 1240 */ 93, 119, 1254, 1254, 1085, 1088, 1075, 1075, 139, 139, + /* 1250 */ 140, 140, 140, 140, 593, 237, 480, 1476, 141, 142, + /* 1260 */ 93, 593, 1254, 1254, 1085, 1088, 1075, 1075, 139, 139, + /* 1270 */ 140, 140, 140, 140, 344, 430, 346, 70, 70, 494, + /* 1280 */ 991, 1132, 1132, 512, 56, 56, 1269, 593, 268, 593, + /* 1290 */ 369, 374, 593, 481, 215, 384, 1624, 481, 138, 138, + /* 1300 */ 138, 138, 137, 137, 136, 136, 136, 135, 132, 463, + /* 1310 */ 71, 71, 72, 72, 225, 73, 73, 593, 138, 138, + /* 1320 */ 138, 138, 137, 137, 136, 136, 136, 135, 132, 463, + /* 1330 */ 586, 431, 593, 872, 873, 874, 593, 911, 593, 1602, + /* 1340 */ 74, 74, 593, 7, 1460, 242, 593, 306, 424, 1578, + /* 1350 */ 472, 306, 364, 219, 367, 75, 75, 430, 345, 57, + /* 1360 */ 57, 58, 58, 432, 187, 59, 59, 593, 424, 61, + /* 1370 */ 61, 1475, 141, 142, 93, 123, 1254, 1254, 1085, 1088, + /* 1380 */ 1075, 1075, 139, 139, 140, 140, 140, 140, 424, 570, + /* 1390 */ 62, 62, 141, 142, 93, 911, 1254, 1254, 1085, 1088, + /* 1400 */ 1075, 1075, 139, 139, 140, 140, 140, 140, 161, 384, + /* 1410 */ 1624, 1474, 141, 130, 93, 441, 1254, 1254, 1085, 1088, + /* 1420 */ 1075, 1075, 139, 139, 140, 140, 140, 140, 267, 266, + /* 1430 */ 265, 1460, 138, 138, 138, 138, 137, 137, 136, 136, + /* 1440 */ 136, 135, 132, 463, 593, 1336, 593, 1269, 1460, 384, + /* 1450 */ 1624, 231, 138, 138, 138, 138, 137, 137, 136, 136, + /* 1460 */ 136, 135, 132, 463, 593, 163, 593, 76, 76, 77, + /* 1470 */ 77, 593, 138, 138, 138, 138, 137, 137, 136, 136, + /* 1480 */ 136, 135, 132, 463, 475, 593, 483, 78, 78, 20, + /* 1490 */ 20, 1249, 424, 491, 79, 79, 495, 422, 295, 235, + /* 1500 */ 1574, 38, 511, 896, 422, 335, 240, 422, 147, 147, + /* 1510 */ 112, 593, 424, 593, 101, 222, 991, 142, 93, 455, + /* 1520 */ 1254, 1254, 1085, 1088, 1075, 1075, 139, 139, 140, 140, + /* 1530 */ 140, 140, 593, 39, 148, 148, 80, 80, 93, 551, + /* 1540 */ 1254, 1254, 1085, 1088, 1075, 1075, 139, 139, 140, 140, + /* 1550 */ 140, 140, 328, 923, 922, 64, 64, 502, 1656, 1005, + /* 1560 */ 933, 896, 124, 422, 121, 254, 593, 1006, 593, 226, + /* 1570 */ 593, 127, 585, 164, 4, 16, 138, 138, 138, 138, + /* 1580 */ 137, 137, 136, 136, 136, 135, 132, 463, 588, 81, + /* 1590 */ 81, 65, 65, 82, 82, 593, 138, 138, 138, 138, + /* 1600 */ 137, 137, 136, 136, 136, 135, 132, 463, 593, 226, + /* 1610 */ 237, 966, 464, 593, 298, 593, 965, 593, 66, 66, + /* 1620 */ 593, 1170, 593, 411, 582, 353, 469, 115, 593, 471, + /* 1630 */ 169, 173, 173, 593, 44, 991, 174, 174, 89, 89, + /* 1640 */ 67, 67, 593, 85, 85, 150, 150, 1114, 1043, 593, + /* 1650 */ 273, 86, 86, 1062, 593, 503, 171, 171, 593, 125, + /* 1660 */ 125, 497, 593, 273, 336, 152, 152, 126, 1335, 464, + /* 1670 */ 594, 464, 146, 146, 1050, 593, 545, 172, 172, 593, + /* 1680 */ 1054, 165, 165, 256, 339, 156, 156, 127, 585, 1586, + /* 1690 */ 4, 329, 584, 499, 358, 273, 115, 348, 155, 155, + /* 1700 */ 930, 931, 153, 153, 588, 1114, 1050, 1050, 1052, 1053, + /* 1710 */ 35, 1554, 521, 593, 270, 1008, 1009, 9, 593, 372, + /* 1720 */ 593, 115, 593, 168, 593, 115, 593, 1110, 464, 270, + /* 1730 */ 996, 964, 273, 129, 1645, 1214, 154, 154, 1054, 1404, + /* 1740 */ 582, 88, 88, 90, 90, 87, 87, 52, 52, 60, + /* 1750 */ 60, 1405, 504, 537, 559, 1179, 961, 507, 129, 558, + /* 1760 */ 127, 585, 1126, 4, 1126, 1125, 894, 1125, 162, 1062, + /* 1770 */ 963, 359, 129, 1401, 363, 125, 125, 588, 366, 368, + /* 1780 */ 370, 1349, 1334, 126, 1333, 464, 594, 464, 377, 387, + /* 1790 */ 1050, 1391, 1414, 1618, 1459, 1387, 1399, 208, 580, 1464, + /* 1800 */ 1314, 464, 243, 516, 1305, 1293, 1384, 1292, 1294, 1638, + /* 1810 */ 288, 170, 228, 582, 12, 408, 321, 322, 241, 323, + /* 1820 */ 245, 1446, 1050, 1050, 1052, 1053, 35, 559, 304, 350, + /* 1830 */ 351, 501, 560, 127, 585, 1441, 4, 1451, 1434, 310, + /* 1840 */ 1450, 526, 1062, 1332, 415, 380, 232, 1527, 125, 125, + /* 1850 */ 588, 1214, 1396, 356, 1526, 583, 126, 1397, 464, 594, + /* 1860 */ 464, 1641, 535, 1050, 1581, 1395, 1269, 1583, 1582, 213, + /* 1870 */ 402, 277, 214, 227, 464, 1573, 239, 1571, 1266, 1394, + /* 1880 */ 434, 198, 100, 224, 96, 183, 582, 191, 485, 193, + /* 1890 */ 486, 194, 195, 196, 519, 1050, 1050, 1052, 1053, 35, + /* 1900 */ 559, 113, 252, 413, 1447, 558, 493, 13, 1455, 416, + /* 1910 */ 1453, 1452, 14, 202, 1521, 1062, 1532, 508, 258, 106, + /* 1920 */ 514, 125, 125, 99, 1214, 1543, 289, 260, 206, 126, + /* 1930 */ 365, 464, 594, 464, 361, 517, 1050, 261, 448, 1295, + /* 1940 */ 262, 418, 1352, 1351, 108, 1350, 1655, 1654, 1343, 915, + /* 1950 */ 419, 1322, 233, 452, 319, 379, 1321, 453, 1623, 320, + /* 1960 */ 1320, 275, 1653, 544, 276, 1609, 1608, 1342, 1050, 1050, + /* 1970 */ 1052, 1053, 35, 1630, 1218, 466, 385, 456, 300, 1419, + /* 1980 */ 144, 1418, 570, 407, 407, 406, 284, 404, 11, 1508, + /* 1990 */ 881, 396, 120, 127, 585, 394, 4, 1214, 327, 114, + /* 2000 */ 1375, 1374, 220, 247, 400, 338, 401, 554, 42, 1224, + /* 2010 */ 588, 596, 283, 337, 285, 286, 188, 597, 1290, 1285, + /* 2020 */ 175, 1558, 176, 1559, 1557, 1556, 159, 317, 229, 177, + /* 2030 */ 868, 230, 91, 465, 464, 221, 331, 468, 1165, 470, + /* 2040 */ 473, 94, 244, 95, 249, 189, 582, 1124, 1122, 341, + /* 2050 */ 427, 190, 178, 1249, 179, 43, 192, 947, 349, 428, + /* 2060 */ 1138, 197, 251, 180, 181, 436, 102, 182, 438, 103, + /* 2070 */ 104, 199, 248, 1140, 253, 1062, 105, 255, 1137, 166, + /* 2080 */ 24, 125, 125, 257, 1264, 273, 360, 513, 259, 126, + /* 2090 */ 15, 464, 594, 464, 204, 883, 1050, 518, 263, 373, + /* 2100 */ 381, 92, 585, 1130, 4, 203, 205, 426, 107, 522, + /* 2110 */ 25, 26, 329, 584, 913, 572, 527, 376, 588, 926, + /* 2120 */ 530, 109, 184, 318, 167, 110, 27, 538, 1050, 1050, + /* 2130 */ 1052, 1053, 35, 1211, 1091, 17, 476, 111, 1181, 234, + /* 2140 */ 292, 1180, 464, 294, 207, 994, 129, 1201, 272, 1000, + /* 2150 */ 28, 1197, 29, 30, 582, 1199, 1205, 1214, 31, 1204, + /* 2160 */ 32, 1186, 41, 566, 33, 1105, 211, 8, 115, 1092, + /* 2170 */ 1090, 1094, 34, 278, 578, 1095, 117, 122, 118, 1145, + /* 2180 */ 36, 18, 128, 1062, 1055, 895, 957, 37, 589, 125, + /* 2190 */ 125, 279, 186, 280, 1646, 157, 405, 126, 1220, 464, + /* 2200 */ 594, 464, 1218, 466, 1050, 1219, 300, 1281, 1281, 1281, + /* 2210 */ 1281, 407, 407, 406, 284, 404, 1281, 1281, 881, 1281, + /* 2220 */ 300, 1281, 1281, 571, 1281, 407, 407, 406, 284, 404, + /* 2230 */ 1281, 247, 881, 338, 1281, 1281, 1050, 1050, 1052, 1053, + /* 2240 */ 35, 337, 1281, 1281, 1281, 247, 1281, 338, 1281, 1281, + /* 2250 */ 1281, 1281, 1281, 1281, 1281, 337, 1281, 1281, 1281, 1281, + /* 2260 */ 1281, 1281, 1281, 1281, 1281, 1214, 1281, 1281, 1281, 1281, + /* 2270 */ 1281, 1281, 249, 1281, 1281, 1281, 1281, 1281, 1281, 1281, + /* 2280 */ 178, 1281, 1281, 43, 1281, 1281, 249, 1281, 1281, 1281, + /* 2290 */ 1281, 1281, 1281, 1281, 178, 1281, 1281, 43, 1281, 1281, + /* 2300 */ 248, 1281, 1281, 1281, 1281, 1281, 1281, 1281, 1281, 1281, + /* 2310 */ 1281, 1281, 1281, 1281, 248, 1281, 1281, 1281, 1281, 1281, + /* 2320 */ 1281, 1281, 1281, 1281, 1281, 1281, 1281, 1281, 1281, 1281, + /* 2330 */ 1281, 1281, 1281, 1281, 1281, 426, 1281, 1281, 1281, 1281, + /* 2340 */ 329, 584, 1281, 1281, 1281, 1281, 1281, 1281, 1281, 426, + /* 2350 */ 1281, 1281, 1281, 1281, 329, 584, 1281, 1281, 1281, 1281, + /* 2360 */ 1281, 1281, 1281, 1281, 476, 1281, 1281, 1281, 1281, 1281, + /* 2370 */ 1281, 1281, 1281, 1281, 1281, 1281, 1281, 1281, 476, }; static const YYCODETYPE yy_lookahead[] = { - /* 0 */ 276, 277, 278, 240, 241, 224, 194, 226, 194, 240, - /* 10 */ 241, 194, 216, 220, 194, 234, 253, 194, 255, 19, - /* 20 */ 224, 297, 253, 194, 255, 205, 212, 213, 205, 217, - /* 30 */ 218, 31, 205, 194, 217, 218, 194, 217, 218, 39, - /* 40 */ 217, 218, 312, 43, 44, 45, 316, 47, 48, 49, + /* 0 */ 277, 278, 279, 241, 242, 225, 195, 227, 195, 312, + /* 10 */ 195, 218, 195, 316, 195, 235, 254, 195, 256, 19, + /* 20 */ 297, 277, 278, 279, 218, 206, 213, 214, 206, 218, + /* 30 */ 219, 31, 206, 218, 219, 218, 219, 218, 219, 39, + /* 40 */ 218, 219, 195, 43, 44, 45, 195, 47, 48, 49, /* 50 */ 50, 51, 52, 53, 54, 55, 56, 57, 58, 19, - /* 60 */ 240, 241, 194, 240, 241, 194, 254, 240, 241, 276, - /* 70 */ 277, 278, 233, 253, 254, 255, 253, 254, 255, 217, - /* 80 */ 253, 239, 255, 43, 44, 45, 263, 47, 48, 49, - /* 90 */ 50, 51, 52, 53, 54, 55, 56, 57, 58, 270, - /* 100 */ 286, 22, 23, 103, 104, 105, 106, 107, 108, 109, - /* 110 */ 110, 111, 112, 113, 114, 82, 47, 48, 49, 50, - /* 120 */ 186, 187, 188, 189, 190, 191, 189, 87, 191, 89, - /* 130 */ 196, 19, 198, 196, 317, 198, 319, 25, 194, 205, - /* 140 */ 298, 270, 205, 103, 104, 105, 106, 107, 108, 109, - /* 150 */ 110, 111, 112, 113, 114, 43, 44, 45, 11, 47, + /* 60 */ 241, 242, 195, 241, 242, 195, 255, 241, 242, 195, + /* 70 */ 255, 237, 238, 254, 255, 256, 254, 255, 256, 264, + /* 80 */ 254, 207, 256, 43, 44, 45, 264, 47, 48, 49, + /* 90 */ 50, 51, 52, 53, 54, 55, 56, 57, 58, 251, + /* 100 */ 287, 253, 215, 103, 104, 105, 106, 107, 108, 109, + /* 110 */ 110, 111, 112, 113, 114, 82, 265, 195, 271, 11, + /* 120 */ 187, 188, 189, 190, 191, 192, 190, 87, 192, 89, + /* 130 */ 197, 19, 199, 197, 317, 199, 319, 25, 271, 206, + /* 140 */ 218, 219, 206, 103, 104, 105, 106, 107, 108, 109, + /* 150 */ 110, 111, 112, 113, 114, 43, 44, 45, 195, 47, /* 160 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, - /* 170 */ 58, 60, 139, 140, 240, 241, 214, 240, 241, 311, - /* 180 */ 312, 102, 70, 239, 316, 194, 19, 253, 77, 255, - /* 190 */ 253, 122, 255, 55, 56, 57, 58, 59, 207, 88, - /* 200 */ 194, 90, 268, 194, 93, 268, 107, 108, 109, 110, - /* 210 */ 111, 112, 113, 114, 47, 103, 104, 105, 106, 107, - /* 220 */ 108, 109, 110, 111, 112, 113, 114, 114, 117, 118, - /* 230 */ 119, 276, 277, 278, 300, 19, 194, 300, 276, 277, - /* 240 */ 278, 103, 104, 105, 106, 107, 108, 109, 110, 111, - /* 250 */ 112, 113, 114, 55, 56, 57, 58, 146, 194, 43, - /* 260 */ 44, 45, 47, 47, 48, 49, 50, 51, 52, 53, - /* 270 */ 54, 55, 56, 57, 58, 82, 129, 130, 60, 129, - /* 280 */ 130, 217, 218, 116, 68, 25, 103, 104, 105, 106, - /* 290 */ 107, 108, 109, 110, 111, 112, 113, 114, 23, 132, - /* 300 */ 294, 103, 104, 105, 106, 107, 108, 109, 110, 111, - /* 310 */ 112, 113, 114, 217, 121, 306, 194, 308, 26, 103, + /* 170 */ 58, 60, 139, 140, 241, 242, 289, 241, 242, 309, + /* 180 */ 310, 294, 70, 47, 48, 49, 50, 254, 77, 256, + /* 190 */ 254, 195, 256, 55, 56, 57, 58, 59, 221, 88, + /* 200 */ 109, 90, 269, 240, 93, 269, 107, 108, 109, 110, + /* 210 */ 111, 112, 113, 114, 215, 103, 104, 105, 106, 107, + /* 220 */ 108, 109, 110, 111, 112, 113, 114, 136, 117, 118, + /* 230 */ 119, 298, 141, 300, 298, 19, 300, 129, 130, 317, + /* 240 */ 318, 103, 104, 105, 106, 107, 108, 109, 110, 111, + /* 250 */ 112, 113, 114, 114, 277, 278, 279, 146, 122, 43, + /* 260 */ 44, 45, 195, 47, 48, 49, 50, 51, 52, 53, + /* 270 */ 54, 55, 56, 57, 58, 218, 277, 278, 279, 19, + /* 280 */ 19, 195, 286, 23, 68, 218, 219, 55, 56, 57, + /* 290 */ 58, 103, 104, 105, 106, 107, 108, 109, 110, 111, + /* 300 */ 112, 113, 114, 43, 44, 45, 232, 47, 48, 49, + /* 310 */ 50, 51, 52, 53, 54, 55, 56, 57, 58, 103, /* 320 */ 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, - /* 330 */ 114, 116, 139, 140, 217, 117, 118, 119, 120, 19, - /* 340 */ 194, 123, 124, 125, 24, 109, 110, 111, 112, 113, - /* 350 */ 114, 133, 60, 311, 312, 250, 194, 252, 316, 19, - /* 360 */ 194, 166, 167, 43, 44, 45, 205, 47, 48, 49, - /* 370 */ 50, 51, 52, 53, 54, 55, 56, 57, 58, 217, - /* 380 */ 218, 317, 318, 43, 44, 45, 264, 47, 48, 49, - /* 390 */ 50, 51, 52, 53, 54, 55, 56, 57, 58, 139, - /* 400 */ 140, 240, 241, 139, 140, 188, 189, 190, 191, 117, - /* 410 */ 118, 119, 231, 196, 253, 198, 255, 194, 194, 258, - /* 420 */ 259, 146, 205, 103, 104, 105, 106, 107, 108, 109, - /* 430 */ 110, 111, 112, 113, 114, 109, 212, 213, 236, 237, - /* 440 */ 217, 218, 194, 103, 104, 105, 106, 107, 108, 109, - /* 450 */ 110, 111, 112, 113, 114, 194, 120, 240, 241, 123, - /* 460 */ 124, 125, 136, 194, 19, 74, 60, 141, 23, 133, - /* 470 */ 253, 194, 255, 82, 194, 309, 310, 254, 29, 317, - /* 480 */ 318, 194, 33, 22, 199, 268, 263, 239, 43, 44, - /* 490 */ 45, 151, 47, 48, 49, 50, 51, 52, 53, 54, - /* 500 */ 55, 56, 57, 58, 217, 218, 194, 60, 19, 146, - /* 510 */ 286, 242, 23, 107, 108, 66, 204, 300, 206, 128, - /* 520 */ 73, 60, 116, 117, 118, 119, 265, 121, 165, 60, - /* 530 */ 139, 140, 43, 44, 45, 129, 47, 48, 49, 50, - /* 540 */ 51, 52, 53, 54, 55, 56, 57, 58, 103, 104, - /* 550 */ 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, - /* 560 */ 154, 194, 156, 194, 117, 118, 119, 280, 283, 205, - /* 570 */ 101, 220, 287, 19, 20, 306, 22, 308, 117, 118, - /* 580 */ 119, 211, 212, 213, 217, 218, 117, 118, 236, 237, - /* 590 */ 36, 122, 103, 104, 105, 106, 107, 108, 109, 110, - /* 600 */ 111, 112, 113, 114, 240, 241, 194, 60, 194, 194, - /* 610 */ 194, 194, 19, 194, 60, 194, 23, 253, 206, 255, - /* 620 */ 73, 254, 19, 154, 155, 156, 72, 276, 277, 278, - /* 630 */ 263, 217, 218, 217, 218, 271, 43, 44, 45, 271, - /* 640 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, - /* 650 */ 57, 58, 183, 194, 285, 101, 19, 214, 60, 242, - /* 660 */ 23, 107, 108, 109, 117, 118, 119, 16, 254, 115, - /* 670 */ 254, 117, 118, 119, 194, 60, 122, 263, 205, 264, - /* 680 */ 43, 44, 45, 264, 47, 48, 49, 50, 51, 52, - /* 690 */ 53, 54, 55, 56, 57, 58, 103, 104, 105, 106, - /* 700 */ 107, 108, 109, 110, 111, 112, 113, 114, 154, 155, - /* 710 */ 156, 157, 158, 240, 241, 117, 118, 119, 101, 205, - /* 720 */ 117, 19, 20, 306, 22, 308, 253, 74, 255, 78, - /* 730 */ 205, 80, 117, 118, 119, 118, 293, 183, 36, 122, - /* 740 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, - /* 750 */ 113, 114, 194, 294, 240, 241, 211, 212, 213, 144, - /* 760 */ 19, 23, 60, 25, 23, 240, 241, 253, 245, 255, - /* 770 */ 15, 154, 155, 156, 72, 217, 218, 194, 253, 256, - /* 780 */ 255, 128, 129, 130, 43, 44, 45, 22, 47, 48, - /* 790 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - /* 800 */ 183, 19, 77, 101, 19, 128, 129, 130, 23, 107, - /* 810 */ 108, 60, 254, 88, 21, 90, 61, 115, 93, 117, - /* 820 */ 118, 119, 239, 22, 122, 60, 194, 205, 43, 44, - /* 830 */ 45, 205, 47, 48, 49, 50, 51, 52, 53, 54, - /* 840 */ 55, 56, 57, 58, 103, 104, 105, 106, 107, 108, - /* 850 */ 109, 110, 111, 112, 113, 114, 154, 155, 156, 157, - /* 860 */ 158, 60, 240, 241, 60, 116, 240, 241, 117, 118, - /* 870 */ 119, 146, 194, 19, 81, 253, 275, 255, 24, 253, - /* 880 */ 98, 255, 117, 118, 119, 183, 22, 194, 103, 104, - /* 890 */ 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, - /* 900 */ 151, 194, 270, 152, 22, 23, 194, 25, 19, 202, - /* 910 */ 217, 218, 23, 109, 207, 314, 315, 124, 117, 118, - /* 920 */ 119, 117, 118, 119, 60, 232, 22, 23, 19, 25, - /* 930 */ 303, 304, 43, 44, 45, 22, 47, 48, 49, 50, - /* 940 */ 51, 52, 53, 54, 55, 56, 57, 58, 270, 227, - /* 950 */ 96, 60, 43, 44, 45, 162, 47, 48, 49, 50, - /* 960 */ 51, 52, 53, 54, 55, 56, 57, 58, 114, 112, - /* 970 */ 113, 114, 194, 60, 120, 121, 122, 123, 124, 125, - /* 980 */ 126, 117, 118, 119, 102, 25, 132, 107, 108, 194, - /* 990 */ 194, 227, 103, 104, 105, 106, 107, 108, 109, 110, - /* 1000 */ 111, 112, 113, 114, 194, 194, 102, 194, 117, 118, - /* 1010 */ 119, 233, 103, 104, 105, 106, 107, 108, 109, 110, - /* 1020 */ 111, 112, 113, 114, 194, 194, 19, 194, 217, 218, - /* 1030 */ 117, 118, 119, 241, 154, 144, 156, 135, 242, 137, - /* 1040 */ 138, 130, 19, 232, 194, 253, 23, 255, 217, 218, - /* 1050 */ 217, 218, 242, 16, 7, 8, 9, 25, 261, 262, - /* 1060 */ 265, 194, 19, 232, 153, 232, 43, 44, 45, 160, - /* 1070 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, - /* 1080 */ 57, 58, 194, 227, 217, 218, 43, 44, 45, 194, - /* 1090 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, - /* 1100 */ 57, 58, 306, 143, 308, 217, 218, 294, 12, 77, - /* 1110 */ 22, 23, 217, 218, 194, 78, 306, 80, 308, 194, - /* 1120 */ 232, 254, 90, 27, 117, 93, 103, 104, 105, 106, - /* 1130 */ 107, 108, 109, 110, 111, 112, 113, 114, 42, 194, - /* 1140 */ 35, 194, 217, 218, 214, 194, 103, 104, 105, 106, - /* 1150 */ 107, 108, 109, 110, 111, 112, 113, 114, 194, 239, - /* 1160 */ 64, 194, 217, 218, 217, 218, 209, 210, 217, 218, - /* 1170 */ 74, 207, 67, 22, 194, 77, 19, 232, 245, 232, - /* 1180 */ 75, 24, 312, 232, 217, 218, 316, 25, 90, 256, - /* 1190 */ 102, 93, 159, 229, 161, 231, 19, 217, 218, 162, - /* 1200 */ 43, 44, 45, 160, 47, 48, 49, 50, 51, 52, - /* 1210 */ 53, 54, 55, 56, 57, 58, 19, 23, 288, 25, - /* 1220 */ 43, 44, 45, 293, 47, 48, 49, 50, 51, 52, - /* 1230 */ 53, 54, 55, 56, 57, 58, 131, 22, 275, 24, - /* 1240 */ 43, 44, 45, 194, 47, 48, 49, 50, 51, 52, - /* 1250 */ 53, 54, 55, 56, 57, 58, 194, 194, 107, 108, - /* 1260 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, - /* 1270 */ 113, 114, 194, 25, 194, 60, 194, 314, 315, 194, - /* 1280 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, - /* 1290 */ 113, 114, 19, 194, 194, 217, 218, 217, 218, 25, - /* 1300 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, - /* 1310 */ 113, 114, 150, 119, 265, 312, 67, 217, 218, 316, - /* 1320 */ 19, 239, 194, 194, 128, 129, 130, 265, 265, 209, - /* 1330 */ 210, 31, 254, 118, 254, 86, 60, 194, 144, 39, - /* 1340 */ 19, 130, 275, 312, 95, 44, 45, 316, 47, 48, - /* 1350 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - /* 1360 */ 217, 218, 24, 194, 153, 12, 45, 119, 47, 48, - /* 1370 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - /* 1380 */ 27, 314, 315, 22, 312, 24, 217, 218, 316, 116, - /* 1390 */ 117, 22, 144, 25, 118, 42, 147, 194, 60, 19, - /* 1400 */ 20, 127, 22, 194, 103, 104, 105, 106, 107, 108, - /* 1410 */ 109, 110, 111, 112, 113, 114, 36, 64, 145, 194, - /* 1420 */ 217, 218, 194, 54, 103, 104, 105, 106, 107, 108, - /* 1430 */ 109, 110, 111, 112, 113, 114, 194, 22, 310, 25, - /* 1440 */ 60, 194, 217, 218, 194, 217, 218, 194, 260, 194, - /* 1450 */ 301, 302, 72, 262, 262, 194, 118, 266, 266, 217, - /* 1460 */ 218, 194, 82, 245, 217, 218, 194, 217, 218, 194, - /* 1470 */ 217, 218, 217, 218, 256, 60, 24, 194, 217, 218, - /* 1480 */ 194, 101, 194, 245, 217, 218, 194, 107, 108, 217, - /* 1490 */ 218, 22, 217, 218, 256, 115, 245, 117, 118, 119, - /* 1500 */ 217, 218, 122, 217, 218, 217, 218, 256, 22, 217, - /* 1510 */ 218, 116, 258, 259, 146, 19, 20, 194, 22, 139, - /* 1520 */ 140, 150, 151, 136, 23, 194, 25, 194, 141, 194, - /* 1530 */ 194, 62, 36, 118, 154, 155, 156, 157, 158, 100, - /* 1540 */ 145, 194, 154, 194, 156, 49, 194, 23, 194, 25, - /* 1550 */ 217, 218, 217, 218, 194, 257, 60, 143, 194, 60, - /* 1560 */ 194, 121, 122, 183, 217, 218, 217, 218, 72, 217, - /* 1570 */ 218, 217, 218, 134, 23, 194, 25, 217, 218, 7, - /* 1580 */ 8, 321, 86, 217, 218, 194, 122, 91, 19, 20, - /* 1590 */ 23, 22, 25, 23, 142, 25, 132, 101, 217, 218, - /* 1600 */ 194, 194, 194, 107, 108, 36, 194, 194, 217, 218, - /* 1610 */ 194, 115, 194, 117, 118, 119, 194, 118, 122, 194, - /* 1620 */ 23, 194, 25, 217, 218, 217, 218, 194, 142, 60, - /* 1630 */ 217, 218, 194, 217, 218, 217, 218, 84, 85, 217, - /* 1640 */ 218, 72, 217, 218, 217, 218, 60, 23, 60, 25, - /* 1650 */ 154, 155, 156, 157, 158, 86, 154, 194, 156, 194, - /* 1660 */ 91, 19, 20, 23, 22, 25, 194, 23, 194, 25, - /* 1670 */ 101, 23, 194, 25, 194, 194, 107, 108, 36, 183, - /* 1680 */ 217, 218, 217, 218, 115, 194, 117, 118, 119, 217, - /* 1690 */ 218, 122, 194, 237, 194, 217, 218, 217, 218, 194, - /* 1700 */ 194, 23, 60, 25, 118, 23, 118, 25, 217, 218, - /* 1710 */ 23, 194, 25, 194, 72, 217, 218, 217, 218, 23, - /* 1720 */ 194, 25, 194, 154, 155, 156, 157, 158, 86, 23, - /* 1730 */ 194, 25, 194, 91, 217, 218, 217, 218, 194, 194, - /* 1740 */ 194, 194, 194, 101, 194, 217, 218, 290, 194, 107, - /* 1750 */ 108, 194, 183, 217, 218, 194, 194, 115, 194, 117, - /* 1760 */ 118, 119, 194, 243, 122, 194, 289, 194, 194, 194, - /* 1770 */ 194, 257, 257, 257, 244, 257, 192, 273, 215, 269, - /* 1780 */ 246, 299, 269, 295, 247, 273, 247, 246, 295, 230, - /* 1790 */ 261, 226, 261, 261, 273, 273, 154, 155, 156, 157, - /* 1800 */ 158, 0, 1, 2, 221, 220, 5, 220, 250, 220, - /* 1810 */ 261, 10, 11, 12, 13, 14, 250, 282, 17, 197, - /* 1820 */ 61, 19, 20, 246, 22, 183, 244, 142, 201, 201, - /* 1830 */ 38, 30, 299, 32, 201, 152, 22, 151, 36, 299, - /* 1840 */ 43, 40, 235, 18, 238, 285, 238, 238, 296, 238, - /* 1850 */ 201, 296, 274, 272, 18, 200, 235, 150, 235, 247, - /* 1860 */ 247, 247, 60, 247, 274, 274, 272, 201, 200, 159, - /* 1870 */ 63, 292, 71, 201, 72, 200, 22, 201, 222, 200, - /* 1880 */ 79, 201, 222, 82, 291, 116, 219, 65, 200, 219, - /* 1890 */ 219, 228, 22, 127, 225, 166, 222, 24, 225, 114, - /* 1900 */ 99, 284, 221, 101, 284, 228, 307, 315, 219, 107, - /* 1910 */ 108, 219, 219, 219, 201, 92, 320, 115, 320, 117, - /* 1920 */ 118, 119, 222, 83, 122, 267, 267, 149, 146, 19, - /* 1930 */ 20, 22, 22, 279, 250, 134, 201, 148, 159, 249, - /* 1940 */ 139, 140, 251, 141, 25, 281, 36, 147, 251, 248, - /* 1950 */ 247, 203, 13, 195, 6, 195, 154, 155, 156, 157, - /* 1960 */ 158, 193, 305, 193, 163, 193, 305, 302, 214, 208, - /* 1970 */ 60, 214, 208, 223, 223, 4, 214, 214, 3, 22, - /* 1980 */ 215, 214, 72, 208, 164, 183, 215, 15, 23, 16, - /* 1990 */ 23, 140, 131, 152, 25, 143, 20, 16, 24, 1, - /* 2000 */ 145, 143, 131, 131, 62, 37, 54, 54, 152, 54, - /* 2010 */ 54, 101, 131, 117, 34, 1, 142, 107, 108, 22, - /* 2020 */ 5, 116, 162, 69, 25, 115, 76, 117, 118, 119, - /* 2030 */ 1, 2, 122, 69, 5, 41, 142, 116, 20, 10, - /* 2040 */ 11, 12, 13, 14, 24, 19, 17, 132, 5, 126, - /* 2050 */ 22, 141, 68, 10, 11, 12, 13, 14, 22, 30, - /* 2060 */ 17, 32, 22, 22, 154, 155, 156, 157, 158, 40, - /* 2070 */ 23, 68, 60, 30, 24, 32, 97, 28, 22, 68, - /* 2080 */ 23, 37, 34, 40, 150, 22, 25, 23, 23, 23, - /* 2090 */ 22, 98, 23, 183, 23, 117, 34, 22, 25, 89, - /* 2100 */ 71, 142, 144, 76, 34, 23, 34, 76, 79, 87, - /* 2110 */ 34, 82, 34, 94, 71, 34, 22, 24, 44, 34, - /* 2120 */ 25, 25, 79, 23, 23, 82, 143, 23, 99, 143, - /* 2130 */ 23, 22, 11, 25, 23, 25, 22, 22, 22, 1, - /* 2140 */ 23, 23, 99, 136, 22, 22, 142, 142, 142, 25, - /* 2150 */ 25, 23, 15, 1, 322, 322, 322, 322, 322, 322, - /* 2160 */ 322, 322, 322, 134, 322, 322, 322, 322, 139, 140, - /* 2170 */ 322, 322, 322, 322, 322, 322, 322, 134, 322, 322, - /* 2180 */ 322, 322, 139, 140, 322, 322, 322, 322, 322, 322, - /* 2190 */ 322, 322, 163, 322, 322, 322, 322, 322, 322, 322, - /* 2200 */ 322, 322, 322, 322, 322, 322, 163, 322, 322, 322, - /* 2210 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, - /* 2220 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, - /* 2230 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, - /* 2240 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, - /* 2250 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, - /* 2260 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, - /* 2270 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, - /* 2280 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, - /* 2290 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, - /* 2300 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, - /* 2310 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, + /* 330 */ 114, 135, 60, 137, 138, 103, 104, 105, 106, 107, + /* 340 */ 108, 109, 110, 111, 112, 113, 114, 82, 281, 206, + /* 350 */ 195, 109, 110, 111, 112, 113, 114, 195, 195, 195, + /* 360 */ 205, 22, 207, 103, 104, 105, 106, 107, 108, 109, + /* 370 */ 110, 111, 112, 113, 114, 195, 60, 116, 117, 107, + /* 380 */ 108, 218, 219, 19, 241, 242, 121, 23, 116, 117, + /* 390 */ 118, 119, 306, 121, 308, 206, 234, 254, 15, 256, + /* 400 */ 195, 129, 259, 260, 139, 140, 145, 43, 44, 45, + /* 410 */ 200, 47, 48, 49, 50, 51, 52, 53, 54, 55, + /* 420 */ 56, 57, 58, 218, 219, 60, 154, 19, 156, 265, + /* 430 */ 241, 242, 24, 117, 118, 119, 120, 21, 73, 123, + /* 440 */ 124, 125, 74, 254, 61, 256, 107, 108, 221, 133, + /* 450 */ 82, 43, 44, 45, 195, 47, 48, 49, 50, 51, + /* 460 */ 52, 53, 54, 55, 56, 57, 58, 103, 104, 105, + /* 470 */ 106, 107, 108, 109, 110, 111, 112, 113, 114, 195, + /* 480 */ 317, 318, 117, 118, 119, 22, 120, 195, 22, 123, + /* 490 */ 124, 125, 19, 20, 284, 22, 128, 81, 288, 133, + /* 500 */ 195, 195, 218, 219, 277, 278, 279, 139, 140, 36, + /* 510 */ 195, 103, 104, 105, 106, 107, 108, 109, 110, 111, + /* 520 */ 112, 113, 114, 218, 219, 62, 60, 195, 241, 242, + /* 530 */ 271, 19, 240, 60, 189, 190, 191, 192, 233, 255, + /* 540 */ 124, 254, 197, 256, 199, 72, 129, 130, 264, 195, + /* 550 */ 195, 206, 22, 23, 60, 43, 44, 45, 206, 47, + /* 560 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, + /* 570 */ 58, 195, 218, 219, 101, 195, 60, 271, 162, 195, + /* 580 */ 107, 108, 109, 117, 118, 119, 241, 242, 115, 73, + /* 590 */ 117, 118, 119, 241, 242, 122, 60, 195, 266, 254, + /* 600 */ 312, 256, 218, 219, 316, 203, 254, 195, 256, 255, + /* 610 */ 208, 117, 118, 119, 269, 103, 104, 105, 106, 107, + /* 620 */ 108, 109, 110, 111, 112, 113, 114, 154, 155, 156, + /* 630 */ 157, 158, 102, 117, 118, 119, 19, 242, 144, 255, + /* 640 */ 23, 206, 24, 298, 195, 300, 206, 195, 264, 254, + /* 650 */ 206, 256, 240, 117, 118, 119, 183, 22, 22, 23, + /* 660 */ 43, 44, 45, 151, 47, 48, 49, 50, 51, 52, + /* 670 */ 53, 54, 55, 56, 57, 58, 241, 242, 60, 195, + /* 680 */ 19, 241, 242, 195, 23, 241, 242, 195, 152, 254, + /* 690 */ 310, 256, 243, 312, 254, 60, 256, 316, 254, 206, + /* 700 */ 256, 60, 218, 219, 43, 44, 45, 272, 47, 48, + /* 710 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, + /* 720 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, + /* 730 */ 113, 114, 240, 60, 241, 242, 118, 25, 102, 255, + /* 740 */ 166, 167, 101, 22, 26, 19, 20, 254, 22, 256, + /* 750 */ 139, 140, 117, 118, 119, 306, 195, 308, 117, 118, + /* 760 */ 237, 238, 36, 122, 103, 104, 105, 106, 107, 108, + /* 770 */ 109, 110, 111, 112, 113, 114, 195, 195, 60, 218, + /* 780 */ 219, 60, 109, 195, 19, 217, 60, 25, 23, 77, + /* 790 */ 117, 118, 119, 225, 233, 154, 155, 156, 72, 312, + /* 800 */ 218, 219, 90, 316, 22, 93, 303, 304, 43, 44, + /* 810 */ 45, 195, 47, 48, 49, 50, 51, 52, 53, 54, + /* 820 */ 55, 56, 57, 58, 183, 195, 195, 101, 19, 213, + /* 830 */ 214, 243, 23, 107, 108, 117, 118, 119, 117, 118, + /* 840 */ 119, 115, 60, 117, 118, 119, 195, 60, 122, 218, + /* 850 */ 219, 22, 43, 44, 45, 35, 47, 48, 49, 50, + /* 860 */ 51, 52, 53, 54, 55, 56, 57, 58, 103, 104, + /* 870 */ 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, + /* 880 */ 154, 155, 156, 157, 158, 195, 255, 67, 195, 60, + /* 890 */ 101, 240, 311, 312, 306, 75, 308, 316, 29, 117, + /* 900 */ 118, 119, 33, 287, 117, 118, 119, 118, 146, 183, + /* 910 */ 195, 122, 103, 104, 105, 106, 107, 108, 109, 110, + /* 920 */ 111, 112, 113, 114, 215, 195, 77, 60, 25, 195, + /* 930 */ 122, 144, 19, 218, 219, 66, 23, 88, 246, 90, + /* 940 */ 132, 25, 93, 154, 155, 156, 117, 118, 119, 257, + /* 950 */ 195, 131, 218, 219, 195, 265, 43, 44, 45, 195, + /* 960 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, + /* 970 */ 57, 58, 183, 218, 219, 195, 19, 218, 219, 195, + /* 980 */ 23, 195, 218, 219, 117, 118, 119, 195, 233, 255, + /* 990 */ 195, 195, 233, 22, 23, 146, 25, 233, 218, 219, + /* 1000 */ 43, 44, 45, 294, 47, 48, 49, 50, 51, 52, + /* 1010 */ 53, 54, 55, 56, 57, 58, 103, 104, 105, 106, + /* 1020 */ 107, 108, 109, 110, 111, 112, 113, 114, 195, 12, + /* 1030 */ 234, 195, 240, 74, 195, 255, 195, 60, 243, 262, + /* 1040 */ 263, 311, 312, 25, 27, 19, 316, 107, 108, 265, + /* 1050 */ 24, 265, 195, 150, 195, 139, 140, 218, 219, 42, + /* 1060 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, + /* 1070 */ 113, 114, 233, 102, 67, 218, 219, 218, 219, 243, + /* 1080 */ 19, 64, 22, 23, 23, 25, 195, 128, 129, 130, + /* 1090 */ 233, 74, 233, 86, 154, 118, 156, 130, 265, 208, + /* 1100 */ 19, 306, 95, 308, 43, 44, 45, 266, 47, 48, + /* 1110 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, + /* 1120 */ 153, 230, 96, 232, 43, 44, 45, 19, 47, 48, + /* 1130 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, + /* 1140 */ 114, 22, 306, 24, 308, 127, 120, 121, 122, 123, + /* 1150 */ 124, 125, 126, 195, 147, 212, 213, 214, 132, 23, + /* 1160 */ 195, 25, 102, 100, 103, 104, 105, 106, 107, 108, + /* 1170 */ 109, 110, 111, 112, 113, 114, 218, 219, 19, 60, + /* 1180 */ 195, 12, 210, 211, 103, 104, 105, 106, 107, 108, + /* 1190 */ 109, 110, 111, 112, 113, 114, 27, 134, 195, 195, + /* 1200 */ 195, 210, 211, 218, 219, 195, 47, 195, 212, 213, + /* 1210 */ 214, 42, 16, 130, 19, 112, 113, 114, 23, 77, + /* 1220 */ 195, 218, 219, 218, 219, 117, 163, 164, 218, 219, + /* 1230 */ 218, 219, 90, 64, 19, 93, 153, 118, 43, 44, + /* 1240 */ 45, 160, 47, 48, 49, 50, 51, 52, 53, 54, + /* 1250 */ 55, 56, 57, 58, 195, 119, 272, 276, 43, 44, + /* 1260 */ 45, 195, 47, 48, 49, 50, 51, 52, 53, 54, + /* 1270 */ 55, 56, 57, 58, 78, 116, 80, 218, 219, 116, + /* 1280 */ 144, 128, 129, 130, 218, 219, 61, 195, 47, 195, + /* 1290 */ 16, 132, 195, 263, 195, 314, 315, 267, 103, 104, + /* 1300 */ 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, + /* 1310 */ 218, 219, 218, 219, 151, 218, 219, 195, 103, 104, + /* 1320 */ 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, + /* 1330 */ 210, 211, 195, 7, 8, 9, 195, 60, 195, 312, + /* 1340 */ 218, 219, 195, 316, 195, 120, 195, 263, 19, 195, + /* 1350 */ 125, 267, 78, 24, 80, 218, 219, 116, 162, 218, + /* 1360 */ 219, 218, 219, 301, 302, 218, 219, 195, 19, 218, + /* 1370 */ 219, 276, 43, 44, 45, 160, 47, 48, 49, 50, + /* 1380 */ 51, 52, 53, 54, 55, 56, 57, 58, 19, 146, + /* 1390 */ 218, 219, 43, 44, 45, 118, 47, 48, 49, 50, + /* 1400 */ 51, 52, 53, 54, 55, 56, 57, 58, 165, 314, + /* 1410 */ 315, 276, 43, 44, 45, 266, 47, 48, 49, 50, + /* 1420 */ 51, 52, 53, 54, 55, 56, 57, 58, 128, 129, + /* 1430 */ 130, 195, 103, 104, 105, 106, 107, 108, 109, 110, + /* 1440 */ 111, 112, 113, 114, 195, 228, 195, 61, 195, 314, + /* 1450 */ 315, 25, 103, 104, 105, 106, 107, 108, 109, 110, + /* 1460 */ 111, 112, 113, 114, 195, 22, 195, 218, 219, 218, + /* 1470 */ 219, 195, 103, 104, 105, 106, 107, 108, 109, 110, + /* 1480 */ 111, 112, 113, 114, 195, 195, 246, 218, 219, 218, + /* 1490 */ 219, 25, 19, 246, 218, 219, 246, 257, 259, 260, + /* 1500 */ 195, 22, 266, 60, 257, 195, 120, 257, 218, 219, + /* 1510 */ 116, 195, 19, 195, 150, 151, 25, 44, 45, 266, + /* 1520 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, + /* 1530 */ 57, 58, 195, 54, 218, 219, 218, 219, 45, 145, + /* 1540 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, + /* 1550 */ 57, 58, 246, 121, 122, 218, 219, 19, 23, 31, + /* 1560 */ 25, 118, 159, 257, 161, 24, 195, 39, 195, 143, + /* 1570 */ 195, 19, 20, 22, 22, 24, 103, 104, 105, 106, + /* 1580 */ 107, 108, 109, 110, 111, 112, 113, 114, 36, 218, + /* 1590 */ 219, 218, 219, 218, 219, 195, 103, 104, 105, 106, + /* 1600 */ 107, 108, 109, 110, 111, 112, 113, 114, 195, 143, + /* 1610 */ 119, 136, 60, 195, 22, 195, 141, 195, 218, 219, + /* 1620 */ 195, 23, 195, 25, 72, 23, 131, 25, 195, 134, + /* 1630 */ 23, 218, 219, 195, 82, 144, 218, 219, 218, 219, + /* 1640 */ 218, 219, 195, 218, 219, 218, 219, 60, 23, 195, + /* 1650 */ 25, 218, 219, 101, 195, 117, 218, 219, 195, 107, + /* 1660 */ 108, 23, 195, 25, 195, 218, 219, 115, 228, 117, + /* 1670 */ 118, 119, 218, 219, 122, 195, 19, 218, 219, 195, + /* 1680 */ 60, 218, 219, 142, 195, 218, 219, 19, 20, 195, + /* 1690 */ 22, 139, 140, 23, 23, 25, 25, 195, 218, 219, + /* 1700 */ 7, 8, 218, 219, 36, 118, 154, 155, 156, 157, + /* 1710 */ 158, 195, 23, 195, 25, 84, 85, 49, 195, 23, + /* 1720 */ 195, 25, 195, 23, 195, 25, 195, 23, 60, 25, + /* 1730 */ 23, 23, 25, 25, 142, 183, 218, 219, 118, 195, + /* 1740 */ 72, 218, 219, 218, 219, 218, 219, 218, 219, 218, + /* 1750 */ 219, 195, 195, 146, 86, 98, 23, 195, 25, 91, + /* 1760 */ 19, 20, 154, 22, 156, 154, 23, 156, 25, 101, + /* 1770 */ 23, 195, 25, 195, 195, 107, 108, 36, 195, 195, + /* 1780 */ 195, 195, 228, 115, 195, 117, 118, 119, 195, 195, + /* 1790 */ 122, 261, 195, 321, 195, 195, 195, 258, 238, 195, + /* 1800 */ 195, 60, 299, 291, 195, 195, 258, 195, 195, 195, + /* 1810 */ 290, 244, 216, 72, 245, 193, 258, 258, 299, 258, + /* 1820 */ 299, 274, 154, 155, 156, 157, 158, 86, 247, 295, + /* 1830 */ 248, 295, 91, 19, 20, 270, 22, 274, 270, 248, + /* 1840 */ 274, 222, 101, 227, 274, 221, 231, 221, 107, 108, + /* 1850 */ 36, 183, 262, 247, 221, 283, 115, 262, 117, 118, + /* 1860 */ 119, 198, 116, 122, 220, 262, 61, 220, 220, 251, + /* 1870 */ 247, 142, 251, 245, 60, 202, 299, 202, 38, 262, + /* 1880 */ 202, 22, 152, 151, 296, 43, 72, 236, 18, 239, + /* 1890 */ 202, 239, 239, 239, 18, 154, 155, 156, 157, 158, + /* 1900 */ 86, 150, 201, 248, 275, 91, 248, 273, 236, 248, + /* 1910 */ 275, 275, 273, 236, 248, 101, 286, 202, 201, 159, + /* 1920 */ 63, 107, 108, 296, 183, 293, 202, 201, 22, 115, + /* 1930 */ 202, 117, 118, 119, 292, 223, 122, 201, 65, 202, + /* 1940 */ 201, 223, 220, 220, 22, 220, 226, 226, 229, 127, + /* 1950 */ 223, 220, 166, 24, 285, 220, 222, 114, 315, 285, + /* 1960 */ 220, 202, 220, 307, 92, 320, 320, 229, 154, 155, + /* 1970 */ 156, 157, 158, 0, 1, 2, 223, 83, 5, 268, + /* 1980 */ 149, 268, 146, 10, 11, 12, 13, 14, 22, 280, + /* 1990 */ 17, 202, 159, 19, 20, 251, 22, 183, 282, 148, + /* 2000 */ 252, 252, 250, 30, 249, 32, 248, 147, 25, 13, + /* 2010 */ 36, 204, 196, 40, 196, 6, 302, 194, 194, 194, + /* 2020 */ 209, 215, 209, 215, 215, 215, 224, 224, 216, 209, + /* 2030 */ 4, 216, 215, 3, 60, 22, 122, 19, 122, 19, + /* 2040 */ 125, 22, 15, 22, 71, 16, 72, 23, 23, 140, + /* 2050 */ 305, 152, 79, 25, 131, 82, 143, 20, 16, 305, + /* 2060 */ 1, 143, 145, 131, 131, 62, 54, 131, 37, 54, + /* 2070 */ 54, 152, 99, 117, 34, 101, 54, 24, 1, 5, + /* 2080 */ 22, 107, 108, 116, 76, 25, 162, 41, 142, 115, + /* 2090 */ 24, 117, 118, 119, 116, 20, 122, 19, 126, 23, + /* 2100 */ 132, 19, 20, 69, 22, 69, 22, 134, 22, 68, + /* 2110 */ 22, 22, 139, 140, 60, 141, 68, 24, 36, 28, + /* 2120 */ 97, 22, 37, 68, 23, 150, 34, 22, 154, 155, + /* 2130 */ 156, 157, 158, 23, 23, 22, 163, 25, 23, 142, + /* 2140 */ 23, 98, 60, 23, 22, 144, 25, 76, 34, 117, + /* 2150 */ 34, 89, 34, 34, 72, 87, 76, 183, 34, 94, + /* 2160 */ 34, 23, 22, 24, 34, 23, 25, 44, 25, 23, + /* 2170 */ 23, 23, 22, 22, 25, 11, 143, 25, 143, 23, + /* 2180 */ 22, 22, 22, 101, 23, 23, 136, 22, 25, 107, + /* 2190 */ 108, 142, 25, 142, 142, 23, 15, 115, 1, 117, + /* 2200 */ 118, 119, 1, 2, 122, 1, 5, 322, 322, 322, + /* 2210 */ 322, 10, 11, 12, 13, 14, 322, 322, 17, 322, + /* 2220 */ 5, 322, 322, 141, 322, 10, 11, 12, 13, 14, + /* 2230 */ 322, 30, 17, 32, 322, 322, 154, 155, 156, 157, + /* 2240 */ 158, 40, 322, 322, 322, 30, 322, 32, 322, 322, + /* 2250 */ 322, 322, 322, 322, 322, 40, 322, 322, 322, 322, + /* 2260 */ 322, 322, 322, 322, 322, 183, 322, 322, 322, 322, + /* 2270 */ 322, 322, 71, 322, 322, 322, 322, 322, 322, 322, + /* 2280 */ 79, 322, 322, 82, 322, 322, 71, 322, 322, 322, + /* 2290 */ 322, 322, 322, 322, 79, 322, 322, 82, 322, 322, + /* 2300 */ 99, 322, 322, 322, 322, 322, 322, 322, 322, 322, + /* 2310 */ 322, 322, 322, 322, 99, 322, 322, 322, 322, 322, /* 2320 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, - /* 2330 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, - /* 2340 */ 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, - /* 2350 */ 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, - /* 2360 */ 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, - /* 2370 */ 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, - /* 2380 */ 186, 186, 186, 186, 186, 186, 186, 186, 186, 186, - /* 2390 */ 186, 186, 186, + /* 2330 */ 322, 322, 322, 322, 322, 134, 322, 322, 322, 322, + /* 2340 */ 139, 140, 322, 322, 322, 322, 322, 322, 322, 134, + /* 2350 */ 322, 322, 322, 322, 139, 140, 322, 322, 322, 322, + /* 2360 */ 322, 322, 322, 322, 163, 322, 322, 322, 322, 322, + /* 2370 */ 322, 322, 322, 322, 322, 322, 322, 322, 163, 322, + /* 2380 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, + /* 2390 */ 322, 322, 322, 322, 322, 322, 322, 322, 322, 322, + /* 2400 */ 322, 322, 322, 322, 322, 322, 322, 322, 187, 187, + /* 2410 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2420 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2430 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2440 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2450 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2460 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2470 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2480 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2490 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2500 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2510 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2520 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2530 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2540 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2550 */ 187, 187, 187, 187, 187, 187, 187, 187, 187, 187, + /* 2560 */ 187, 187, 187, 187, 187, 187, }; -#define YY_SHIFT_COUNT (582) +#define YY_SHIFT_COUNT (599) #define YY_SHIFT_MIN (0) -#define YY_SHIFT_MAX (2152) +#define YY_SHIFT_MAX (2215) static const unsigned short int yy_shift_ofst[] = { - /* 0 */ 2029, 1801, 2043, 1380, 1380, 33, 391, 1496, 1569, 1642, - /* 10 */ 702, 702, 702, 193, 33, 33, 33, 33, 33, 0, - /* 20 */ 0, 216, 1177, 702, 702, 702, 702, 702, 702, 702, - /* 30 */ 702, 702, 702, 702, 702, 702, 702, 702, 406, 406, - /* 40 */ 111, 111, 218, 447, 547, 598, 598, 260, 260, 260, - /* 50 */ 260, 40, 112, 320, 340, 445, 489, 593, 637, 741, - /* 60 */ 785, 889, 909, 1023, 1043, 1157, 1177, 1177, 1177, 1177, - /* 70 */ 1177, 1177, 1177, 1177, 1177, 1177, 1177, 1177, 1177, 1177, - /* 80 */ 1177, 1177, 1177, 1177, 1197, 1177, 1301, 1321, 1321, 554, - /* 90 */ 1802, 1910, 702, 702, 702, 702, 702, 702, 702, 702, - /* 100 */ 702, 702, 702, 702, 702, 702, 702, 702, 702, 702, - /* 110 */ 702, 702, 702, 702, 702, 702, 702, 702, 702, 702, - /* 120 */ 702, 702, 702, 702, 702, 702, 702, 702, 702, 702, - /* 130 */ 702, 702, 702, 702, 702, 702, 702, 702, 702, 702, - /* 140 */ 702, 702, 138, 198, 198, 198, 198, 198, 198, 198, - /* 150 */ 183, 99, 236, 292, 598, 793, 167, 598, 598, 880, - /* 160 */ 880, 598, 857, 150, 195, 195, 195, 264, 113, 113, - /* 170 */ 2207, 2207, 854, 854, 854, 751, 765, 765, 765, 765, - /* 180 */ 1096, 1096, 725, 292, 882, 904, 598, 598, 598, 598, - /* 190 */ 598, 598, 598, 598, 598, 598, 598, 598, 598, 598, - /* 200 */ 598, 598, 598, 598, 598, 1273, 1032, 1032, 598, 147, - /* 210 */ 1098, 1098, 603, 603, 1276, 1276, 363, 2207, 2207, 2207, - /* 220 */ 2207, 2207, 2207, 2207, 469, 617, 617, 801, 336, 461, - /* 230 */ 804, 864, 615, 891, 913, 598, 598, 598, 598, 598, - /* 240 */ 598, 598, 598, 598, 598, 653, 598, 598, 598, 598, - /* 250 */ 598, 598, 598, 598, 598, 598, 598, 598, 1105, 1105, - /* 260 */ 1105, 598, 598, 598, 1194, 598, 598, 598, 1215, 1249, - /* 270 */ 598, 1353, 598, 598, 598, 598, 598, 598, 598, 598, - /* 280 */ 677, 449, 902, 1338, 1338, 1338, 1338, 1248, 902, 902, - /* 290 */ 326, 1151, 1047, 755, 749, 1371, 960, 1371, 1007, 1162, - /* 300 */ 749, 749, 1162, 749, 960, 1007, 1274, 738, 215, 1300, - /* 310 */ 1300, 1300, 1395, 1395, 1395, 1395, 1368, 1368, 1033, 1414, - /* 320 */ 1387, 1361, 1759, 1759, 1685, 1685, 1792, 1792, 1685, 1683, - /* 330 */ 1686, 1814, 1797, 1825, 1825, 1825, 1825, 1685, 1836, 1707, - /* 340 */ 1686, 1686, 1707, 1814, 1797, 1707, 1797, 1707, 1685, 1836, - /* 350 */ 1710, 1807, 1685, 1836, 1854, 1685, 1836, 1685, 1836, 1854, - /* 360 */ 1769, 1769, 1769, 1822, 1870, 1870, 1854, 1769, 1766, 1769, - /* 370 */ 1822, 1769, 1769, 1729, 1873, 1785, 1785, 1854, 1685, 1823, - /* 380 */ 1823, 1840, 1840, 1778, 1782, 1909, 1685, 1779, 1778, 1789, - /* 390 */ 1800, 1707, 1919, 1939, 1939, 1948, 1948, 1948, 2207, 2207, - /* 400 */ 2207, 2207, 2207, 2207, 2207, 2207, 2207, 2207, 2207, 2207, - /* 410 */ 2207, 2207, 2207, 69, 1037, 79, 1088, 651, 1196, 1415, - /* 420 */ 1501, 1439, 1369, 1452, 911, 1211, 1524, 1469, 1551, 1567, - /* 430 */ 1570, 1624, 1640, 1644, 1499, 1440, 1572, 1464, 1597, 275, - /* 440 */ 782, 1586, 1648, 1678, 1553, 1682, 1687, 1388, 1502, 1696, - /* 450 */ 1706, 1588, 1486, 1971, 1975, 1957, 1820, 1972, 1973, 1965, - /* 460 */ 1967, 1851, 1841, 1861, 1969, 1969, 1974, 1852, 1976, 1855, - /* 470 */ 1981, 1998, 1858, 1871, 1969, 1872, 1942, 1968, 1969, 1856, - /* 480 */ 1952, 1953, 1955, 1956, 1881, 1896, 1980, 1874, 2014, 2015, - /* 490 */ 1997, 1905, 1860, 1954, 1999, 1964, 1950, 1994, 1894, 1921, - /* 500 */ 2020, 2018, 2026, 1915, 1923, 2028, 1984, 2036, 2040, 2047, - /* 510 */ 2041, 2003, 2012, 2050, 1979, 2049, 2056, 2011, 2044, 2057, - /* 520 */ 2048, 1934, 2063, 2064, 2065, 2061, 2066, 2068, 1993, 1959, - /* 530 */ 2069, 2071, 1978, 2062, 2075, 1958, 2073, 2070, 2072, 2076, - /* 540 */ 2078, 2010, 2027, 2022, 2074, 2031, 2019, 2081, 2082, 2094, - /* 550 */ 2093, 2095, 2096, 2085, 1983, 1986, 2100, 2073, 2101, 2104, - /* 560 */ 2107, 2109, 2108, 2110, 2111, 2114, 2121, 2115, 2116, 2117, - /* 570 */ 2118, 2122, 2123, 2124, 2007, 2004, 2005, 2006, 2125, 2128, - /* 580 */ 2137, 2138, 2152, + /* 0 */ 2201, 1973, 2215, 1552, 1552, 33, 368, 1668, 1741, 1814, + /* 10 */ 726, 726, 726, 265, 33, 33, 33, 33, 33, 0, + /* 20 */ 0, 216, 1349, 726, 726, 726, 726, 726, 726, 726, + /* 30 */ 726, 726, 726, 726, 726, 726, 726, 726, 272, 272, + /* 40 */ 111, 111, 316, 365, 516, 867, 867, 916, 916, 916, + /* 50 */ 916, 40, 112, 260, 364, 408, 512, 617, 661, 765, + /* 60 */ 809, 913, 957, 1061, 1081, 1195, 1215, 1329, 1349, 1349, + /* 70 */ 1349, 1349, 1349, 1349, 1349, 1349, 1349, 1349, 1349, 1349, + /* 80 */ 1349, 1349, 1349, 1349, 1349, 1349, 1369, 1349, 1473, 1493, + /* 90 */ 1493, 473, 1974, 2082, 726, 726, 726, 726, 726, 726, + /* 100 */ 726, 726, 726, 726, 726, 726, 726, 726, 726, 726, + /* 110 */ 726, 726, 726, 726, 726, 726, 726, 726, 726, 726, + /* 120 */ 726, 726, 726, 726, 726, 726, 726, 726, 726, 726, + /* 130 */ 726, 726, 726, 726, 726, 726, 726, 726, 726, 726, + /* 140 */ 726, 726, 726, 726, 726, 726, 138, 232, 232, 232, + /* 150 */ 232, 232, 232, 232, 188, 99, 242, 718, 416, 1159, + /* 160 */ 867, 867, 940, 940, 867, 1103, 417, 574, 574, 574, + /* 170 */ 611, 139, 139, 2379, 2379, 1026, 1026, 1026, 536, 466, + /* 180 */ 466, 466, 466, 1017, 1017, 849, 718, 971, 1060, 867, + /* 190 */ 867, 867, 867, 867, 867, 867, 867, 867, 867, 867, + /* 200 */ 867, 867, 867, 867, 867, 867, 867, 867, 261, 712, + /* 210 */ 712, 867, 108, 1142, 1142, 977, 1108, 1108, 977, 977, + /* 220 */ 1243, 2379, 2379, 2379, 2379, 2379, 2379, 2379, 641, 789, + /* 230 */ 789, 635, 366, 721, 673, 782, 494, 787, 829, 867, + /* 240 */ 867, 867, 867, 867, 867, 867, 867, 867, 867, 867, + /* 250 */ 959, 867, 867, 867, 867, 867, 867, 867, 867, 867, + /* 260 */ 867, 867, 867, 867, 867, 820, 820, 820, 867, 867, + /* 270 */ 867, 1136, 867, 867, 867, 1119, 1007, 867, 1169, 867, + /* 280 */ 867, 867, 867, 867, 867, 867, 867, 1225, 1153, 869, + /* 290 */ 196, 618, 618, 618, 618, 1491, 196, 196, 91, 339, + /* 300 */ 1326, 1386, 383, 1163, 1364, 1426, 1364, 1538, 903, 1163, + /* 310 */ 1163, 903, 1163, 1426, 1538, 1018, 1535, 1241, 1528, 1528, + /* 320 */ 1528, 1394, 1394, 1394, 1394, 762, 762, 1403, 1466, 1475, + /* 330 */ 1551, 1746, 1805, 1746, 1746, 1729, 1729, 1840, 1840, 1729, + /* 340 */ 1730, 1732, 1859, 1842, 1870, 1870, 1870, 1870, 1729, 1876, + /* 350 */ 1751, 1732, 1732, 1751, 1859, 1842, 1751, 1842, 1751, 1729, + /* 360 */ 1876, 1760, 1857, 1729, 1876, 1906, 1729, 1876, 1729, 1876, + /* 370 */ 1906, 1746, 1746, 1746, 1873, 1922, 1922, 1906, 1746, 1822, + /* 380 */ 1746, 1873, 1746, 1746, 1786, 1929, 1843, 1843, 1906, 1729, + /* 390 */ 1872, 1872, 1894, 1894, 1831, 1836, 1966, 1729, 1833, 1831, + /* 400 */ 1851, 1860, 1751, 1983, 1996, 1996, 2009, 2009, 2009, 2379, + /* 410 */ 2379, 2379, 2379, 2379, 2379, 2379, 2379, 2379, 2379, 2379, + /* 420 */ 2379, 2379, 2379, 2379, 136, 1063, 1196, 530, 636, 1274, + /* 430 */ 1300, 1443, 1598, 1495, 1479, 967, 1083, 1602, 463, 1625, + /* 440 */ 1638, 1670, 1541, 1671, 1689, 1696, 1277, 1432, 1693, 808, + /* 450 */ 1700, 1607, 1657, 1587, 1704, 1707, 1631, 1708, 1733, 1608, + /* 460 */ 1611, 1743, 1747, 1620, 1592, 2026, 2030, 2013, 1914, 2018, + /* 470 */ 1916, 2020, 2019, 2021, 1915, 2027, 2029, 2024, 2025, 1909, + /* 480 */ 1899, 1923, 2028, 2028, 1913, 2037, 1917, 2042, 2059, 1918, + /* 490 */ 1932, 2028, 1933, 2003, 2031, 2028, 1919, 2012, 2015, 2016, + /* 500 */ 2022, 1936, 1956, 2040, 2053, 2077, 2074, 2058, 1967, 1924, + /* 510 */ 2034, 2060, 2036, 2008, 2046, 1946, 1978, 2066, 2075, 2078, + /* 520 */ 1968, 1972, 2084, 2041, 2086, 2088, 2076, 2089, 2048, 2054, + /* 530 */ 2093, 2023, 2091, 2099, 2055, 2085, 2101, 2092, 1975, 2105, + /* 540 */ 2110, 2111, 2112, 2115, 2113, 2043, 1997, 2117, 2120, 2032, + /* 550 */ 2114, 2122, 2001, 2121, 2116, 2118, 2119, 2124, 2062, 2071, + /* 560 */ 2068, 2123, 2080, 2065, 2126, 2138, 2140, 2139, 2141, 2143, + /* 570 */ 2130, 2033, 2035, 2142, 2121, 2146, 2147, 2148, 2150, 2149, + /* 580 */ 2152, 2156, 2151, 2164, 2158, 2159, 2161, 2162, 2160, 2165, + /* 590 */ 2163, 2050, 2049, 2051, 2052, 2167, 2172, 2181, 2197, 2204, }; -#define YY_REDUCE_COUNT (412) -#define YY_REDUCE_MIN (-276) -#define YY_REDUCE_MAX (1775) +#define YY_REDUCE_COUNT (423) +#define YY_REDUCE_MIN (-303) +#define YY_REDUCE_MAX (1825) static const short yy_reduce_ofst[] = { - /* 0 */ -66, 217, -63, -177, -180, 161, 364, 64, -183, 162, - /* 10 */ 223, 367, 414, -173, 473, 514, 525, 622, 626, -207, - /* 20 */ 351, -276, -38, 693, 811, 831, 833, 888, -188, 945, - /* 30 */ 947, 416, 558, 951, 867, 287, 1078, 1080, -186, 224, - /* 40 */ -132, 42, 964, 269, 417, 796, 810, -237, -231, -237, - /* 50 */ -231, -45, -45, -45, -45, -45, -45, -45, -45, -45, - /* 60 */ -45, -45, -45, -45, -45, -45, -45, -45, -45, -45, - /* 70 */ -45, -45, -45, -45, -45, -45, -45, -45, -45, -45, - /* 80 */ -45, -45, -45, -45, -45, -45, -45, -45, -45, 895, - /* 90 */ 925, 967, 980, 1100, 1143, 1169, 1203, 1225, 1228, 1242, - /* 100 */ 1247, 1250, 1253, 1255, 1261, 1267, 1272, 1275, 1283, 1286, - /* 110 */ 1288, 1292, 1333, 1335, 1347, 1349, 1352, 1354, 1360, 1366, - /* 120 */ 1381, 1391, 1406, 1408, 1413, 1416, 1418, 1422, 1425, 1427, - /* 130 */ 1463, 1465, 1472, 1478, 1480, 1491, 1498, 1500, 1517, 1519, - /* 140 */ 1528, 1536, -45, -45, -45, -45, -45, -45, -45, -45, - /* 150 */ -45, -45, -45, 312, -158, 285, -219, 9, 166, 370, - /* 160 */ 545, 707, -45, 930, 601, 963, 1067, 792, -45, -45, - /* 170 */ -45, -45, -204, -204, -204, 369, -171, -129, 632, 678, - /* 180 */ 202, 352, -270, 412, 627, 627, -9, 122, 415, 419, - /* 190 */ -56, 248, 583, 920, 6, 261, 459, 795, 1049, 813, - /* 200 */ 1062, 1082, -161, 778, 1063, 797, 870, 1003, 1128, 443, - /* 210 */ 1031, 1072, 1191, 1192, 957, 1120, 105, 1149, 523, 933, - /* 220 */ 1218, 1238, 1254, 1251, -138, 96, 117, 146, 181, 277, - /* 230 */ 280, 421, 480, 712, 830, 850, 1085, 1099, 1129, 1209, - /* 240 */ 1323, 1331, 1336, 1364, 1407, 368, 1412, 1433, 1438, 1474, - /* 250 */ 1481, 1505, 1506, 1526, 1538, 1544, 1545, 1546, 722, 764, - /* 260 */ 856, 1547, 1548, 1550, 1188, 1554, 1557, 1561, 1298, 1260, - /* 270 */ 1562, 1456, 1564, 280, 1568, 1571, 1573, 1574, 1575, 1576, - /* 280 */ 1457, 1477, 1520, 1514, 1515, 1516, 1518, 1188, 1520, 1520, - /* 290 */ 1530, 1563, 1584, 1482, 1504, 1510, 1534, 1513, 1488, 1537, - /* 300 */ 1512, 1521, 1539, 1522, 1541, 1493, 1583, 1559, 1565, 1585, - /* 310 */ 1587, 1589, 1529, 1531, 1532, 1549, 1558, 1566, 1535, 1577, - /* 320 */ 1582, 1622, 1533, 1540, 1627, 1628, 1552, 1555, 1633, 1560, - /* 330 */ 1578, 1581, 1607, 1606, 1608, 1609, 1611, 1649, 1655, 1612, - /* 340 */ 1590, 1591, 1613, 1594, 1621, 1614, 1623, 1616, 1666, 1668, - /* 350 */ 1579, 1593, 1672, 1675, 1656, 1676, 1679, 1680, 1688, 1660, - /* 360 */ 1667, 1670, 1671, 1663, 1669, 1673, 1674, 1689, 1681, 1692, - /* 370 */ 1677, 1693, 1694, 1592, 1599, 1617, 1620, 1700, 1713, 1596, - /* 380 */ 1598, 1658, 1659, 1691, 1684, 1654, 1735, 1664, 1697, 1690, - /* 390 */ 1701, 1703, 1748, 1758, 1760, 1768, 1770, 1772, 1657, 1661, - /* 400 */ 1665, 1761, 1754, 1757, 1762, 1763, 1764, 1750, 1751, 1765, - /* 410 */ 1771, 1767, 1775, + /* 0 */ -67, 345, -64, -178, -181, 143, 435, -78, -183, 163, + /* 10 */ -185, 284, 384, -174, 189, 352, 440, 444, 493, -23, + /* 20 */ 227, -277, -1, 305, 561, 755, 759, 764, -189, 839, + /* 30 */ 857, 354, 484, 859, 631, 67, 734, 780, -187, 616, + /* 40 */ 581, 730, 891, 449, 588, 795, 836, -238, 287, -238, + /* 50 */ 287, -256, -256, -256, -256, -256, -256, -256, -256, -256, + /* 60 */ -256, -256, -256, -256, -256, -256, -256, -256, -256, -256, + /* 70 */ -256, -256, -256, -256, -256, -256, -256, -256, -256, -256, + /* 80 */ -256, -256, -256, -256, -256, -256, -256, -256, -256, -256, + /* 90 */ -256, 205, 582, 715, 958, 985, 1003, 1005, 1010, 1012, + /* 100 */ 1059, 1066, 1092, 1094, 1097, 1122, 1137, 1141, 1143, 1147, + /* 110 */ 1151, 1172, 1249, 1251, 1269, 1271, 1276, 1290, 1316, 1318, + /* 120 */ 1337, 1371, 1373, 1375, 1400, 1413, 1418, 1420, 1422, 1425, + /* 130 */ 1427, 1433, 1438, 1447, 1454, 1459, 1463, 1467, 1480, 1484, + /* 140 */ 1518, 1523, 1525, 1527, 1529, 1531, -256, -256, -256, -256, + /* 150 */ -256, -256, -256, -256, -256, -256, -256, 155, 210, -220, + /* 160 */ 86, -130, 943, 996, 402, -256, -113, 981, 1095, 1135, + /* 170 */ 395, -256, -256, -256, -256, 568, 568, 568, -4, -153, + /* 180 */ -133, 259, 306, -166, 523, -303, -126, 503, 503, -37, + /* 190 */ -149, 164, 690, 292, 412, 492, 651, 784, 332, 786, + /* 200 */ 841, 1149, 833, 1236, 792, 162, 796, 1253, 777, 288, + /* 210 */ 381, 380, 709, 487, 1027, 972, 1030, 1084, 991, 1120, + /* 220 */ -152, 1062, 692, 1240, 1247, 1250, 1239, 1306, -207, -194, + /* 230 */ 57, 180, 74, 315, 355, 376, 452, 488, 630, 693, + /* 240 */ 965, 1004, 1025, 1099, 1154, 1289, 1305, 1310, 1469, 1489, + /* 250 */ 984, 1494, 1502, 1516, 1544, 1556, 1557, 1562, 1576, 1578, + /* 260 */ 1579, 1583, 1584, 1585, 1586, 1217, 1440, 1554, 1589, 1593, + /* 270 */ 1594, 1530, 1597, 1599, 1600, 1539, 1472, 1601, 1560, 1604, + /* 280 */ 355, 1605, 1609, 1610, 1612, 1613, 1614, 1503, 1512, 1520, + /* 290 */ 1567, 1548, 1558, 1559, 1561, 1530, 1567, 1567, 1569, 1596, + /* 300 */ 1622, 1519, 1521, 1547, 1565, 1581, 1568, 1534, 1582, 1563, + /* 310 */ 1566, 1591, 1570, 1606, 1536, 1619, 1615, 1616, 1624, 1626, + /* 320 */ 1633, 1590, 1595, 1603, 1617, 1618, 1621, 1572, 1623, 1628, + /* 330 */ 1663, 1644, 1577, 1647, 1648, 1673, 1675, 1588, 1627, 1678, + /* 340 */ 1630, 1629, 1634, 1651, 1650, 1652, 1653, 1654, 1688, 1701, + /* 350 */ 1655, 1635, 1636, 1658, 1639, 1672, 1661, 1677, 1666, 1715, + /* 360 */ 1717, 1632, 1642, 1724, 1726, 1712, 1728, 1736, 1737, 1739, + /* 370 */ 1718, 1722, 1723, 1725, 1719, 1720, 1721, 1727, 1731, 1734, + /* 380 */ 1735, 1738, 1740, 1742, 1643, 1656, 1669, 1674, 1753, 1759, + /* 390 */ 1645, 1646, 1711, 1713, 1748, 1744, 1709, 1789, 1716, 1749, + /* 400 */ 1752, 1755, 1758, 1807, 1816, 1818, 1823, 1824, 1825, 1745, + /* 410 */ 1754, 1714, 1811, 1806, 1808, 1809, 1810, 1813, 1802, 1803, + /* 420 */ 1812, 1815, 1817, 1820, }; static const YYACTIONTYPE yy_default[] = { - /* 0 */ 1663, 1663, 1663, 1491, 1254, 1367, 1254, 1254, 1254, 1254, - /* 10 */ 1491, 1491, 1491, 1254, 1254, 1254, 1254, 1254, 1254, 1397, - /* 20 */ 1397, 1544, 1287, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 30 */ 1254, 1254, 1254, 1254, 1254, 1490, 1254, 1254, 1254, 1254, - /* 40 */ 1578, 1578, 1254, 1254, 1254, 1254, 1254, 1563, 1562, 1254, - /* 50 */ 1254, 1254, 1406, 1254, 1413, 1254, 1254, 1254, 1254, 1254, - /* 60 */ 1492, 1493, 1254, 1254, 1254, 1254, 1543, 1545, 1508, 1420, - /* 70 */ 1419, 1418, 1417, 1526, 1385, 1411, 1404, 1408, 1487, 1488, - /* 80 */ 1486, 1641, 1493, 1492, 1254, 1407, 1455, 1471, 1454, 1254, - /* 90 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 100 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 110 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 120 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 130 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 140 */ 1254, 1254, 1463, 1470, 1469, 1468, 1477, 1467, 1464, 1457, - /* 150 */ 1456, 1458, 1459, 1278, 1254, 1275, 1329, 1254, 1254, 1254, - /* 160 */ 1254, 1254, 1460, 1287, 1448, 1447, 1446, 1254, 1474, 1461, - /* 170 */ 1473, 1472, 1551, 1615, 1614, 1509, 1254, 1254, 1254, 1254, - /* 180 */ 1254, 1254, 1578, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 190 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 200 */ 1254, 1254, 1254, 1254, 1254, 1387, 1578, 1578, 1254, 1287, - /* 210 */ 1578, 1578, 1388, 1388, 1283, 1283, 1391, 1558, 1358, 1358, - /* 220 */ 1358, 1358, 1367, 1358, 1254, 1254, 1254, 1254, 1254, 1254, - /* 230 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1548, - /* 240 */ 1546, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 250 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 260 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1363, 1254, - /* 270 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1608, - /* 280 */ 1254, 1521, 1343, 1363, 1363, 1363, 1363, 1365, 1344, 1342, - /* 290 */ 1357, 1288, 1261, 1655, 1423, 1412, 1364, 1412, 1652, 1410, - /* 300 */ 1423, 1423, 1410, 1423, 1364, 1652, 1304, 1630, 1299, 1397, - /* 310 */ 1397, 1397, 1387, 1387, 1387, 1387, 1391, 1391, 1489, 1364, - /* 320 */ 1357, 1254, 1655, 1655, 1373, 1373, 1654, 1654, 1373, 1509, - /* 330 */ 1638, 1432, 1332, 1338, 1338, 1338, 1338, 1373, 1272, 1410, - /* 340 */ 1638, 1638, 1410, 1432, 1332, 1410, 1332, 1410, 1373, 1272, - /* 350 */ 1525, 1649, 1373, 1272, 1499, 1373, 1272, 1373, 1272, 1499, - /* 360 */ 1330, 1330, 1330, 1319, 1254, 1254, 1499, 1330, 1304, 1330, - /* 370 */ 1319, 1330, 1330, 1596, 1254, 1503, 1503, 1499, 1373, 1588, - /* 380 */ 1588, 1400, 1400, 1405, 1391, 1494, 1373, 1254, 1405, 1403, - /* 390 */ 1401, 1410, 1322, 1611, 1611, 1607, 1607, 1607, 1660, 1660, - /* 400 */ 1558, 1623, 1287, 1287, 1287, 1287, 1623, 1306, 1306, 1288, - /* 410 */ 1288, 1287, 1623, 1254, 1254, 1254, 1254, 1254, 1254, 1618, - /* 420 */ 1254, 1553, 1510, 1377, 1254, 1254, 1254, 1254, 1254, 1254, - /* 430 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 440 */ 1564, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 450 */ 1254, 1254, 1437, 1254, 1257, 1555, 1254, 1254, 1254, 1254, - /* 460 */ 1254, 1254, 1254, 1254, 1414, 1415, 1378, 1254, 1254, 1254, - /* 470 */ 1254, 1254, 1254, 1254, 1429, 1254, 1254, 1254, 1424, 1254, - /* 480 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1651, 1254, 1254, - /* 490 */ 1254, 1254, 1254, 1254, 1524, 1523, 1254, 1254, 1375, 1254, - /* 500 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 510 */ 1254, 1254, 1302, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 520 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 530 */ 1254, 1254, 1254, 1254, 1254, 1254, 1402, 1254, 1254, 1254, - /* 540 */ 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 550 */ 1254, 1593, 1392, 1254, 1254, 1254, 1254, 1642, 1254, 1254, - /* 560 */ 1254, 1254, 1352, 1254, 1254, 1254, 1254, 1254, 1254, 1254, - /* 570 */ 1254, 1254, 1254, 1634, 1346, 1438, 1254, 1441, 1276, 1254, - /* 580 */ 1266, 1254, 1254, + /* 0 */ 1691, 1691, 1691, 1516, 1279, 1392, 1279, 1279, 1279, 1279, + /* 10 */ 1516, 1516, 1516, 1279, 1279, 1279, 1279, 1279, 1279, 1422, + /* 20 */ 1422, 1568, 1312, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 30 */ 1279, 1279, 1279, 1279, 1279, 1515, 1279, 1279, 1279, 1279, + /* 40 */ 1607, 1607, 1279, 1279, 1279, 1279, 1279, 1592, 1591, 1279, + /* 50 */ 1279, 1279, 1431, 1279, 1279, 1279, 1438, 1279, 1279, 1279, + /* 60 */ 1279, 1279, 1517, 1518, 1279, 1279, 1279, 1279, 1567, 1569, + /* 70 */ 1533, 1445, 1444, 1443, 1442, 1551, 1410, 1436, 1429, 1433, + /* 80 */ 1512, 1513, 1511, 1670, 1518, 1517, 1279, 1432, 1480, 1496, + /* 90 */ 1479, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 100 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 110 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 120 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 130 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 140 */ 1279, 1279, 1279, 1279, 1279, 1279, 1488, 1495, 1494, 1493, + /* 150 */ 1502, 1492, 1489, 1482, 1481, 1483, 1484, 1303, 1300, 1354, + /* 160 */ 1279, 1279, 1279, 1279, 1279, 1485, 1312, 1473, 1472, 1471, + /* 170 */ 1279, 1499, 1486, 1498, 1497, 1575, 1644, 1643, 1534, 1279, + /* 180 */ 1279, 1279, 1279, 1279, 1279, 1607, 1279, 1279, 1279, 1279, + /* 190 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 200 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1412, 1607, + /* 210 */ 1607, 1279, 1312, 1607, 1607, 1308, 1413, 1413, 1308, 1308, + /* 220 */ 1416, 1587, 1383, 1383, 1383, 1383, 1392, 1383, 1279, 1279, + /* 230 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 240 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1572, 1570, 1279, + /* 250 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 260 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 270 */ 1279, 1279, 1279, 1279, 1279, 1388, 1279, 1279, 1279, 1279, + /* 280 */ 1279, 1279, 1279, 1279, 1279, 1279, 1637, 1683, 1279, 1546, + /* 290 */ 1368, 1388, 1388, 1388, 1388, 1390, 1369, 1367, 1382, 1313, + /* 300 */ 1286, 1683, 1683, 1448, 1437, 1389, 1437, 1680, 1435, 1448, + /* 310 */ 1448, 1435, 1448, 1389, 1680, 1329, 1659, 1324, 1422, 1422, + /* 320 */ 1422, 1412, 1412, 1412, 1412, 1416, 1416, 1514, 1389, 1382, + /* 330 */ 1279, 1355, 1683, 1355, 1355, 1398, 1398, 1682, 1682, 1398, + /* 340 */ 1534, 1667, 1457, 1357, 1363, 1363, 1363, 1363, 1398, 1297, + /* 350 */ 1435, 1667, 1667, 1435, 1457, 1357, 1435, 1357, 1435, 1398, + /* 360 */ 1297, 1550, 1678, 1398, 1297, 1524, 1398, 1297, 1398, 1297, + /* 370 */ 1524, 1355, 1355, 1355, 1344, 1279, 1279, 1524, 1355, 1329, + /* 380 */ 1355, 1344, 1355, 1355, 1625, 1279, 1528, 1528, 1524, 1398, + /* 390 */ 1617, 1617, 1425, 1425, 1430, 1416, 1519, 1398, 1279, 1430, + /* 400 */ 1428, 1426, 1435, 1347, 1640, 1640, 1636, 1636, 1636, 1688, + /* 410 */ 1688, 1587, 1652, 1312, 1312, 1312, 1312, 1652, 1331, 1331, + /* 420 */ 1313, 1313, 1312, 1652, 1279, 1279, 1279, 1279, 1279, 1279, + /* 430 */ 1279, 1647, 1279, 1279, 1535, 1279, 1279, 1279, 1279, 1279, + /* 440 */ 1279, 1279, 1402, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 450 */ 1279, 1279, 1593, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 460 */ 1279, 1279, 1279, 1279, 1462, 1279, 1282, 1584, 1279, 1279, + /* 470 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 480 */ 1279, 1279, 1439, 1440, 1279, 1279, 1279, 1279, 1279, 1279, + /* 490 */ 1279, 1454, 1279, 1279, 1279, 1449, 1279, 1279, 1279, 1279, + /* 500 */ 1279, 1279, 1279, 1279, 1403, 1279, 1279, 1279, 1279, 1279, + /* 510 */ 1279, 1549, 1548, 1279, 1279, 1400, 1279, 1279, 1279, 1279, + /* 520 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1327, + /* 530 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 540 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 550 */ 1279, 1279, 1279, 1427, 1279, 1279, 1279, 1279, 1279, 1279, + /* 560 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1622, 1417, + /* 570 */ 1279, 1279, 1279, 1279, 1671, 1279, 1279, 1279, 1279, 1377, + /* 580 */ 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, 1279, + /* 590 */ 1663, 1371, 1463, 1279, 1466, 1301, 1279, 1291, 1279, 1279, }; /********** End of lemon-generated parsing tables *****************************/ @@ -175232,6 +182317,7 @@ static const YYCODETYPE yyFallback[] = { 0, /* ERROR => nothing */ 0, /* QNUMBER => nothing */ 0, /* SPACE => nothing */ + 0, /* COMMENT => nothing */ 0, /* ILLEGAL => nothing */ }; #endif /* YYFALLBACK */ @@ -175501,120 +182587,120 @@ static const char *const yyTokenName[] = { /* 182 */ "ERROR", /* 183 */ "QNUMBER", /* 184 */ "SPACE", - /* 185 */ "ILLEGAL", - /* 186 */ "input", - /* 187 */ "cmdlist", - /* 188 */ "ecmd", - /* 189 */ "cmdx", - /* 190 */ "explain", - /* 191 */ "cmd", - /* 192 */ "transtype", - /* 193 */ "trans_opt", - /* 194 */ "nm", - /* 195 */ "savepoint_opt", - /* 196 */ "create_table", - /* 197 */ "create_table_args", - /* 198 */ "createkw", - /* 199 */ "temp", - /* 200 */ "ifnotexists", - /* 201 */ "dbnm", - /* 202 */ "columnlist", - /* 203 */ "conslist_opt", - /* 204 */ "table_option_set", - /* 205 */ "select", - /* 206 */ "table_option", - /* 207 */ "columnname", - /* 208 */ "carglist", - /* 209 */ "typetoken", - /* 210 */ "typename", - /* 211 */ "signed", - /* 212 */ "plus_num", - /* 213 */ "minus_num", - /* 214 */ "scanpt", - /* 215 */ "scantok", - /* 216 */ "ccons", - /* 217 */ "term", - /* 218 */ "expr", - /* 219 */ "onconf", - /* 220 */ "sortorder", - /* 221 */ "autoinc", - /* 222 */ "eidlist_opt", - /* 223 */ "refargs", - /* 224 */ "defer_subclause", - /* 225 */ "generated", - /* 226 */ "refarg", - /* 227 */ "refact", - /* 228 */ "init_deferred_pred_opt", - /* 229 */ "conslist", - /* 230 */ "tconscomma", - /* 231 */ "tcons", - /* 232 */ "sortlist", - /* 233 */ "eidlist", - /* 234 */ "defer_subclause_opt", - /* 235 */ "orconf", - /* 236 */ "resolvetype", - /* 237 */ "raisetype", - /* 238 */ "ifexists", - /* 239 */ "fullname", - /* 240 */ "selectnowith", - /* 241 */ "oneselect", - /* 242 */ "wqlist", - /* 243 */ "multiselect_op", - /* 244 */ "distinct", - /* 245 */ "selcollist", - /* 246 */ "from", - /* 247 */ "where_opt", - /* 248 */ "groupby_opt", - /* 249 */ "having_opt", - /* 250 */ "orderby_opt", - /* 251 */ "limit_opt", - /* 252 */ "window_clause", - /* 253 */ "values", - /* 254 */ "nexprlist", - /* 255 */ "mvalues", - /* 256 */ "sclp", - /* 257 */ "as", - /* 258 */ "seltablist", - /* 259 */ "stl_prefix", - /* 260 */ "joinop", - /* 261 */ "on_using", - /* 262 */ "indexed_by", - /* 263 */ "exprlist", - /* 264 */ "xfullname", - /* 265 */ "idlist", - /* 266 */ "indexed_opt", - /* 267 */ "nulls", - /* 268 */ "with", - /* 269 */ "where_opt_ret", - /* 270 */ "setlist", - /* 271 */ "insert_cmd", - /* 272 */ "idlist_opt", - /* 273 */ "upsert", - /* 274 */ "returning", - /* 275 */ "filter_over", - /* 276 */ "likeop", - /* 277 */ "between_op", - /* 278 */ "in_op", - /* 279 */ "paren_exprlist", - /* 280 */ "case_operand", - /* 281 */ "case_exprlist", - /* 282 */ "case_else", - /* 283 */ "uniqueflag", - /* 284 */ "collate", - /* 285 */ "vinto", - /* 286 */ "nmnum", - /* 287 */ "trigger_decl", - /* 288 */ "trigger_cmd_list", - /* 289 */ "trigger_time", - /* 290 */ "trigger_event", - /* 291 */ "foreach_clause", - /* 292 */ "when_clause", - /* 293 */ "trigger_cmd", - /* 294 */ "trnm", + /* 185 */ "COMMENT", + /* 186 */ "ILLEGAL", + /* 187 */ "input", + /* 188 */ "cmdlist", + /* 189 */ "ecmd", + /* 190 */ "cmdx", + /* 191 */ "explain", + /* 192 */ "cmd", + /* 193 */ "transtype", + /* 194 */ "trans_opt", + /* 195 */ "nm", + /* 196 */ "savepoint_opt", + /* 197 */ "create_table", + /* 198 */ "create_table_args", + /* 199 */ "createkw", + /* 200 */ "temp", + /* 201 */ "ifnotexists", + /* 202 */ "dbnm", + /* 203 */ "columnlist", + /* 204 */ "conslist_opt", + /* 205 */ "table_option_set", + /* 206 */ "select", + /* 207 */ "table_option", + /* 208 */ "columnname", + /* 209 */ "carglist", + /* 210 */ "typetoken", + /* 211 */ "typename", + /* 212 */ "signed", + /* 213 */ "plus_num", + /* 214 */ "minus_num", + /* 215 */ "scanpt", + /* 216 */ "scantok", + /* 217 */ "ccons", + /* 218 */ "term", + /* 219 */ "expr", + /* 220 */ "onconf", + /* 221 */ "sortorder", + /* 222 */ "autoinc", + /* 223 */ "eidlist_opt", + /* 224 */ "refargs", + /* 225 */ "defer_subclause", + /* 226 */ "generated", + /* 227 */ "refarg", + /* 228 */ "refact", + /* 229 */ "init_deferred_pred_opt", + /* 230 */ "conslist", + /* 231 */ "tconscomma", + /* 232 */ "tcons", + /* 233 */ "sortlist", + /* 234 */ "eidlist", + /* 235 */ "defer_subclause_opt", + /* 236 */ "orconf", + /* 237 */ "resolvetype", + /* 238 */ "raisetype", + /* 239 */ "ifexists", + /* 240 */ "fullname", + /* 241 */ "selectnowith", + /* 242 */ "oneselect", + /* 243 */ "wqlist", + /* 244 */ "multiselect_op", + /* 245 */ "distinct", + /* 246 */ "selcollist", + /* 247 */ "from", + /* 248 */ "where_opt", + /* 249 */ "groupby_opt", + /* 250 */ "having_opt", + /* 251 */ "orderby_opt", + /* 252 */ "limit_opt", + /* 253 */ "window_clause", + /* 254 */ "values", + /* 255 */ "nexprlist", + /* 256 */ "mvalues", + /* 257 */ "sclp", + /* 258 */ "as", + /* 259 */ "seltablist", + /* 260 */ "stl_prefix", + /* 261 */ "joinop", + /* 262 */ "on_using", + /* 263 */ "indexed_by", + /* 264 */ "exprlist", + /* 265 */ "xfullname", + /* 266 */ "idlist", + /* 267 */ "indexed_opt", + /* 268 */ "nulls", + /* 269 */ "with", + /* 270 */ "where_opt_ret", + /* 271 */ "setlist", + /* 272 */ "insert_cmd", + /* 273 */ "idlist_opt", + /* 274 */ "upsert", + /* 275 */ "returning", + /* 276 */ "filter_over", + /* 277 */ "likeop", + /* 278 */ "between_op", + /* 279 */ "in_op", + /* 280 */ "paren_exprlist", + /* 281 */ "case_operand", + /* 282 */ "case_exprlist", + /* 283 */ "case_else", + /* 284 */ "uniqueflag", + /* 285 */ "collate", + /* 286 */ "vinto", + /* 287 */ "nmnum", + /* 288 */ "trigger_decl", + /* 289 */ "trigger_cmd_list", + /* 290 */ "trigger_time", + /* 291 */ "trigger_event", + /* 292 */ "foreach_clause", + /* 293 */ "when_clause", + /* 294 */ "trigger_cmd", /* 295 */ "tridxby", /* 296 */ "database_kw_opt", /* 297 */ "key_opt", - /* 298 */ "add_column_fullname", + /* 298 */ "alter_add", /* 299 */ "kwcolumn_opt", /* 300 */ "create_vtab", /* 301 */ "vtabarglist", @@ -175767,8 +182853,8 @@ static const char *const yyRuleName[] = { /* 119 */ "fullname ::= nm DOT nm", /* 120 */ "xfullname ::= nm", /* 121 */ "xfullname ::= nm DOT nm", - /* 122 */ "xfullname ::= nm DOT nm AS nm", - /* 123 */ "xfullname ::= nm AS nm", + /* 122 */ "xfullname ::= nm AS nm", + /* 123 */ "xfullname ::= nm DOT nm AS nm", /* 124 */ "joinop ::= COMMA|JOIN", /* 125 */ "joinop ::= JOIN_KW JOIN", /* 126 */ "joinop ::= JOIN_KW nm JOIN", @@ -175917,143 +183003,146 @@ static const char *const yyRuleName[] = { /* 269 */ "when_clause ::= WHEN expr", /* 270 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI", /* 271 */ "trigger_cmd_list ::= trigger_cmd SEMI", - /* 272 */ "trnm ::= nm DOT nm", - /* 273 */ "tridxby ::= INDEXED BY nm", - /* 274 */ "tridxby ::= NOT INDEXED", - /* 275 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt", - /* 276 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt", - /* 277 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt", - /* 278 */ "trigger_cmd ::= scanpt select scanpt", - /* 279 */ "expr ::= RAISE LP IGNORE RP", - /* 280 */ "expr ::= RAISE LP raisetype COMMA expr RP", - /* 281 */ "raisetype ::= ROLLBACK", - /* 282 */ "raisetype ::= ABORT", - /* 283 */ "raisetype ::= FAIL", - /* 284 */ "cmd ::= DROP TRIGGER ifexists fullname", - /* 285 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", - /* 286 */ "cmd ::= DETACH database_kw_opt expr", - /* 287 */ "key_opt ::=", - /* 288 */ "key_opt ::= KEY expr", - /* 289 */ "cmd ::= REINDEX", - /* 290 */ "cmd ::= REINDEX nm dbnm", - /* 291 */ "cmd ::= ANALYZE", - /* 292 */ "cmd ::= ANALYZE nm dbnm", - /* 293 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", - /* 294 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist", + /* 272 */ "tridxby ::= INDEXED BY nm", + /* 273 */ "tridxby ::= NOT INDEXED", + /* 274 */ "trigger_cmd ::= UPDATE orconf xfullname tridxby SET setlist from where_opt scanpt", + /* 275 */ "trigger_cmd ::= scanpt insert_cmd INTO xfullname idlist_opt select upsert scanpt", + /* 276 */ "trigger_cmd ::= DELETE FROM xfullname tridxby where_opt scanpt", + /* 277 */ "trigger_cmd ::= scanpt select scanpt", + /* 278 */ "expr ::= RAISE LP IGNORE RP", + /* 279 */ "expr ::= RAISE LP raisetype COMMA expr RP", + /* 280 */ "raisetype ::= ROLLBACK", + /* 281 */ "raisetype ::= ABORT", + /* 282 */ "raisetype ::= FAIL", + /* 283 */ "cmd ::= DROP TRIGGER ifexists fullname", + /* 284 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", + /* 285 */ "cmd ::= DETACH database_kw_opt expr", + /* 286 */ "key_opt ::=", + /* 287 */ "key_opt ::= KEY expr", + /* 288 */ "cmd ::= REINDEX", + /* 289 */ "cmd ::= REINDEX nm dbnm", + /* 290 */ "cmd ::= ANALYZE", + /* 291 */ "cmd ::= ANALYZE nm dbnm", + /* 292 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", + /* 293 */ "cmd ::= alter_add carglist", + /* 294 */ "alter_add ::= ALTER TABLE fullname ADD kwcolumn_opt nm typetoken", /* 295 */ "cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm", - /* 296 */ "add_column_fullname ::= fullname", - /* 297 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm", - /* 298 */ "cmd ::= create_vtab", - /* 299 */ "cmd ::= create_vtab LP vtabarglist RP", - /* 300 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm", - /* 301 */ "vtabarg ::=", - /* 302 */ "vtabargtoken ::= ANY", - /* 303 */ "vtabargtoken ::= lp anylist RP", - /* 304 */ "lp ::= LP", - /* 305 */ "with ::= WITH wqlist", - /* 306 */ "with ::= WITH RECURSIVE wqlist", - /* 307 */ "wqas ::= AS", - /* 308 */ "wqas ::= AS MATERIALIZED", - /* 309 */ "wqas ::= AS NOT MATERIALIZED", - /* 310 */ "wqitem ::= withnm eidlist_opt wqas LP select RP", - /* 311 */ "withnm ::= nm", - /* 312 */ "wqlist ::= wqitem", - /* 313 */ "wqlist ::= wqlist COMMA wqitem", - /* 314 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn", - /* 315 */ "windowdefn ::= nm AS LP window RP", - /* 316 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt", - /* 317 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt", - /* 318 */ "window ::= ORDER BY sortlist frame_opt", - /* 319 */ "window ::= nm ORDER BY sortlist frame_opt", - /* 320 */ "window ::= nm frame_opt", - /* 321 */ "frame_opt ::=", - /* 322 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt", - /* 323 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt", - /* 324 */ "range_or_rows ::= RANGE|ROWS|GROUPS", - /* 325 */ "frame_bound_s ::= frame_bound", - /* 326 */ "frame_bound_s ::= UNBOUNDED PRECEDING", - /* 327 */ "frame_bound_e ::= frame_bound", - /* 328 */ "frame_bound_e ::= UNBOUNDED FOLLOWING", - /* 329 */ "frame_bound ::= expr PRECEDING|FOLLOWING", - /* 330 */ "frame_bound ::= CURRENT ROW", - /* 331 */ "frame_exclude_opt ::=", - /* 332 */ "frame_exclude_opt ::= EXCLUDE frame_exclude", - /* 333 */ "frame_exclude ::= NO OTHERS", - /* 334 */ "frame_exclude ::= CURRENT ROW", - /* 335 */ "frame_exclude ::= GROUP|TIES", - /* 336 */ "window_clause ::= WINDOW windowdefn_list", - /* 337 */ "filter_over ::= filter_clause over_clause", - /* 338 */ "filter_over ::= over_clause", - /* 339 */ "filter_over ::= filter_clause", - /* 340 */ "over_clause ::= OVER LP window RP", - /* 341 */ "over_clause ::= OVER nm", - /* 342 */ "filter_clause ::= FILTER LP WHERE expr RP", - /* 343 */ "term ::= QNUMBER", - /* 344 */ "input ::= cmdlist", - /* 345 */ "cmdlist ::= cmdlist ecmd", - /* 346 */ "cmdlist ::= ecmd", - /* 347 */ "ecmd ::= SEMI", - /* 348 */ "ecmd ::= cmdx SEMI", - /* 349 */ "ecmd ::= explain cmdx SEMI", - /* 350 */ "trans_opt ::=", - /* 351 */ "trans_opt ::= TRANSACTION", - /* 352 */ "trans_opt ::= TRANSACTION nm", - /* 353 */ "savepoint_opt ::= SAVEPOINT", - /* 354 */ "savepoint_opt ::=", - /* 355 */ "cmd ::= create_table create_table_args", - /* 356 */ "table_option_set ::= table_option", - /* 357 */ "columnlist ::= columnlist COMMA columnname carglist", - /* 358 */ "columnlist ::= columnname carglist", - /* 359 */ "nm ::= ID|INDEXED|JOIN_KW", - /* 360 */ "nm ::= STRING", - /* 361 */ "typetoken ::= typename", - /* 362 */ "typename ::= ID|STRING", - /* 363 */ "signed ::= plus_num", - /* 364 */ "signed ::= minus_num", - /* 365 */ "carglist ::= carglist ccons", - /* 366 */ "carglist ::=", - /* 367 */ "ccons ::= NULL onconf", - /* 368 */ "ccons ::= GENERATED ALWAYS AS generated", - /* 369 */ "ccons ::= AS generated", - /* 370 */ "conslist_opt ::= COMMA conslist", - /* 371 */ "conslist ::= conslist tconscomma tcons", - /* 372 */ "conslist ::= tcons", - /* 373 */ "tconscomma ::=", - /* 374 */ "defer_subclause_opt ::= defer_subclause", - /* 375 */ "resolvetype ::= raisetype", - /* 376 */ "selectnowith ::= oneselect", - /* 377 */ "oneselect ::= values", - /* 378 */ "sclp ::= selcollist COMMA", - /* 379 */ "as ::= ID|STRING", - /* 380 */ "indexed_opt ::= indexed_by", - /* 381 */ "returning ::=", - /* 382 */ "expr ::= term", - /* 383 */ "likeop ::= LIKE_KW|MATCH", - /* 384 */ "case_operand ::= expr", - /* 385 */ "exprlist ::= nexprlist", - /* 386 */ "nmnum ::= plus_num", - /* 387 */ "nmnum ::= nm", - /* 388 */ "nmnum ::= ON", - /* 389 */ "nmnum ::= DELETE", - /* 390 */ "nmnum ::= DEFAULT", - /* 391 */ "plus_num ::= INTEGER|FLOAT", - /* 392 */ "foreach_clause ::=", - /* 393 */ "foreach_clause ::= FOR EACH ROW", - /* 394 */ "trnm ::= nm", - /* 395 */ "tridxby ::=", - /* 396 */ "database_kw_opt ::= DATABASE", - /* 397 */ "database_kw_opt ::=", - /* 398 */ "kwcolumn_opt ::=", - /* 399 */ "kwcolumn_opt ::= COLUMNKW", - /* 400 */ "vtabarglist ::= vtabarg", - /* 401 */ "vtabarglist ::= vtabarglist COMMA vtabarg", - /* 402 */ "vtabarg ::= vtabarg vtabargtoken", - /* 403 */ "anylist ::=", - /* 404 */ "anylist ::= anylist LP anylist RP", - /* 405 */ "anylist ::= anylist ANY", - /* 406 */ "with ::=", - /* 407 */ "windowdefn_list ::= windowdefn", - /* 408 */ "window ::= frame_opt", + /* 296 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm", + /* 297 */ "cmd ::= ALTER TABLE fullname DROP CONSTRAINT nm", + /* 298 */ "cmd ::= ALTER TABLE fullname ALTER kwcolumn_opt nm DROP NOT NULL", + /* 299 */ "cmd ::= ALTER TABLE fullname ALTER kwcolumn_opt nm SET NOT NULL onconf", + /* 300 */ "cmd ::= ALTER TABLE fullname ADD CONSTRAINT nm CHECK LP expr RP onconf", + /* 301 */ "cmd ::= ALTER TABLE fullname ADD CHECK LP expr RP onconf", + /* 302 */ "cmd ::= create_vtab", + /* 303 */ "cmd ::= create_vtab LP vtabarglist RP", + /* 304 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm", + /* 305 */ "vtabarg ::=", + /* 306 */ "vtabargtoken ::= ANY", + /* 307 */ "vtabargtoken ::= lp anylist RP", + /* 308 */ "lp ::= LP", + /* 309 */ "with ::= WITH wqlist", + /* 310 */ "with ::= WITH RECURSIVE wqlist", + /* 311 */ "wqas ::= AS", + /* 312 */ "wqas ::= AS MATERIALIZED", + /* 313 */ "wqas ::= AS NOT MATERIALIZED", + /* 314 */ "wqitem ::= withnm eidlist_opt wqas LP select RP", + /* 315 */ "withnm ::= nm", + /* 316 */ "wqlist ::= wqitem", + /* 317 */ "wqlist ::= wqlist COMMA wqitem", + /* 318 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn", + /* 319 */ "windowdefn ::= nm AS LP window RP", + /* 320 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt", + /* 321 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt", + /* 322 */ "window ::= ORDER BY sortlist frame_opt", + /* 323 */ "window ::= nm ORDER BY sortlist frame_opt", + /* 324 */ "window ::= nm frame_opt", + /* 325 */ "frame_opt ::=", + /* 326 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt", + /* 327 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt", + /* 328 */ "range_or_rows ::= RANGE|ROWS|GROUPS", + /* 329 */ "frame_bound_s ::= frame_bound", + /* 330 */ "frame_bound_s ::= UNBOUNDED PRECEDING", + /* 331 */ "frame_bound_e ::= frame_bound", + /* 332 */ "frame_bound_e ::= UNBOUNDED FOLLOWING", + /* 333 */ "frame_bound ::= expr PRECEDING|FOLLOWING", + /* 334 */ "frame_bound ::= CURRENT ROW", + /* 335 */ "frame_exclude_opt ::=", + /* 336 */ "frame_exclude_opt ::= EXCLUDE frame_exclude", + /* 337 */ "frame_exclude ::= NO OTHERS", + /* 338 */ "frame_exclude ::= CURRENT ROW", + /* 339 */ "frame_exclude ::= GROUP|TIES", + /* 340 */ "window_clause ::= WINDOW windowdefn_list", + /* 341 */ "filter_over ::= filter_clause over_clause", + /* 342 */ "filter_over ::= over_clause", + /* 343 */ "filter_over ::= filter_clause", + /* 344 */ "over_clause ::= OVER LP window RP", + /* 345 */ "over_clause ::= OVER nm", + /* 346 */ "filter_clause ::= FILTER LP WHERE expr RP", + /* 347 */ "term ::= QNUMBER", + /* 348 */ "input ::= cmdlist", + /* 349 */ "cmdlist ::= cmdlist ecmd", + /* 350 */ "cmdlist ::= ecmd", + /* 351 */ "ecmd ::= SEMI", + /* 352 */ "ecmd ::= cmdx SEMI", + /* 353 */ "ecmd ::= explain cmdx SEMI", + /* 354 */ "trans_opt ::=", + /* 355 */ "trans_opt ::= TRANSACTION", + /* 356 */ "trans_opt ::= TRANSACTION nm", + /* 357 */ "savepoint_opt ::= SAVEPOINT", + /* 358 */ "savepoint_opt ::=", + /* 359 */ "cmd ::= create_table create_table_args", + /* 360 */ "table_option_set ::= table_option", + /* 361 */ "columnlist ::= columnlist COMMA columnname carglist", + /* 362 */ "columnlist ::= columnname carglist", + /* 363 */ "nm ::= ID|INDEXED|JOIN_KW", + /* 364 */ "nm ::= STRING", + /* 365 */ "typetoken ::= typename", + /* 366 */ "typename ::= ID|STRING", + /* 367 */ "signed ::= plus_num", + /* 368 */ "signed ::= minus_num", + /* 369 */ "carglist ::= carglist ccons", + /* 370 */ "carglist ::=", + /* 371 */ "ccons ::= NULL onconf", + /* 372 */ "ccons ::= GENERATED ALWAYS AS generated", + /* 373 */ "ccons ::= AS generated", + /* 374 */ "conslist_opt ::= COMMA conslist", + /* 375 */ "conslist ::= conslist tconscomma tcons", + /* 376 */ "conslist ::= tcons", + /* 377 */ "tconscomma ::=", + /* 378 */ "defer_subclause_opt ::= defer_subclause", + /* 379 */ "resolvetype ::= raisetype", + /* 380 */ "selectnowith ::= oneselect", + /* 381 */ "oneselect ::= values", + /* 382 */ "sclp ::= selcollist COMMA", + /* 383 */ "as ::= ID|STRING", + /* 384 */ "indexed_opt ::= indexed_by", + /* 385 */ "returning ::=", + /* 386 */ "expr ::= term", + /* 387 */ "likeop ::= LIKE_KW|MATCH", + /* 388 */ "case_operand ::= expr", + /* 389 */ "exprlist ::= nexprlist", + /* 390 */ "nmnum ::= plus_num", + /* 391 */ "nmnum ::= nm", + /* 392 */ "nmnum ::= ON", + /* 393 */ "nmnum ::= DELETE", + /* 394 */ "nmnum ::= DEFAULT", + /* 395 */ "plus_num ::= INTEGER|FLOAT", + /* 396 */ "foreach_clause ::=", + /* 397 */ "foreach_clause ::= FOR EACH ROW", + /* 398 */ "tridxby ::=", + /* 399 */ "database_kw_opt ::= DATABASE", + /* 400 */ "database_kw_opt ::=", + /* 401 */ "kwcolumn_opt ::=", + /* 402 */ "kwcolumn_opt ::= COLUMNKW", + /* 403 */ "vtabarglist ::= vtabarg", + /* 404 */ "vtabarglist ::= vtabarglist COMMA vtabarg", + /* 405 */ "vtabarg ::= vtabarg vtabargtoken", + /* 406 */ "anylist ::=", + /* 407 */ "anylist ::= anylist LP anylist RP", + /* 408 */ "anylist ::= anylist ANY", + /* 409 */ "with ::=", + /* 410 */ "windowdefn_list ::= windowdefn", + /* 411 */ "window ::= frame_opt", }; #endif /* NDEBUG */ @@ -176068,15 +183157,24 @@ static int yyGrowStack(yyParser *p){ int newSize; int idx; yyStackEntry *pNew; +#ifdef YYSIZELIMIT + int nLimit = YYSIZELIMIT(sqlite3ParserCTX(p)); +#endif newSize = oldSize*2 + 100; +#ifdef YYSIZELIMIT + if( newSize>nLimit ){ + newSize = nLimit; + if( newSize<=oldSize ) return 1; + } +#endif idx = (int)(p->yytos - p->yystack); if( p->yystack==p->yystk0 ){ - pNew = YYREALLOC(0, newSize*sizeof(pNew[0])); + pNew = YYREALLOC(0, newSize*sizeof(pNew[0]), sqlite3ParserCTX(p)); if( pNew==0 ) return 1; memcpy(pNew, p->yystack, oldSize*sizeof(pNew[0])); }else{ - pNew = YYREALLOC(p->yystack, newSize*sizeof(pNew[0])); + pNew = YYREALLOC(p->yystack, newSize*sizeof(pNew[0]), sqlite3ParserCTX(p)); if( pNew==0 ) return 1; } p->yystack = pNew; @@ -176177,74 +183275,74 @@ static void yy_destructor( ** inside the C code. */ /********* Begin destructor definitions ***************************************/ - case 205: /* select */ - case 240: /* selectnowith */ - case 241: /* oneselect */ - case 253: /* values */ - case 255: /* mvalues */ + case 206: /* select */ + case 241: /* selectnowith */ + case 242: /* oneselect */ + case 254: /* values */ + case 256: /* mvalues */ { sqlite3SelectDelete(pParse->db, (yypminor->yy555)); } break; - case 217: /* term */ - case 218: /* expr */ - case 247: /* where_opt */ - case 249: /* having_opt */ - case 269: /* where_opt_ret */ - case 280: /* case_operand */ - case 282: /* case_else */ - case 285: /* vinto */ - case 292: /* when_clause */ + case 218: /* term */ + case 219: /* expr */ + case 248: /* where_opt */ + case 250: /* having_opt */ + case 270: /* where_opt_ret */ + case 281: /* case_operand */ + case 283: /* case_else */ + case 286: /* vinto */ + case 293: /* when_clause */ case 297: /* key_opt */ case 314: /* filter_clause */ { sqlite3ExprDelete(pParse->db, (yypminor->yy454)); } break; - case 222: /* eidlist_opt */ - case 232: /* sortlist */ - case 233: /* eidlist */ - case 245: /* selcollist */ - case 248: /* groupby_opt */ - case 250: /* orderby_opt */ - case 254: /* nexprlist */ - case 256: /* sclp */ - case 263: /* exprlist */ - case 270: /* setlist */ - case 279: /* paren_exprlist */ - case 281: /* case_exprlist */ + case 223: /* eidlist_opt */ + case 233: /* sortlist */ + case 234: /* eidlist */ + case 246: /* selcollist */ + case 249: /* groupby_opt */ + case 251: /* orderby_opt */ + case 255: /* nexprlist */ + case 257: /* sclp */ + case 264: /* exprlist */ + case 271: /* setlist */ + case 280: /* paren_exprlist */ + case 282: /* case_exprlist */ case 313: /* part_opt */ { sqlite3ExprListDelete(pParse->db, (yypminor->yy14)); } break; - case 239: /* fullname */ - case 246: /* from */ - case 258: /* seltablist */ - case 259: /* stl_prefix */ - case 264: /* xfullname */ + case 240: /* fullname */ + case 247: /* from */ + case 259: /* seltablist */ + case 260: /* stl_prefix */ + case 265: /* xfullname */ { sqlite3SrcListDelete(pParse->db, (yypminor->yy203)); } break; - case 242: /* wqlist */ + case 243: /* wqlist */ { sqlite3WithDelete(pParse->db, (yypminor->yy59)); } break; - case 252: /* window_clause */ + case 253: /* window_clause */ case 309: /* windowdefn_list */ { sqlite3WindowListDelete(pParse->db, (yypminor->yy211)); } break; - case 265: /* idlist */ - case 272: /* idlist_opt */ + case 266: /* idlist */ + case 273: /* idlist_opt */ { sqlite3IdListDelete(pParse->db, (yypminor->yy132)); } break; - case 275: /* filter_over */ + case 276: /* filter_over */ case 310: /* windowdefn */ case 311: /* window */ case 312: /* frame_opt */ @@ -176253,13 +183351,13 @@ sqlite3IdListDelete(pParse->db, (yypminor->yy132)); sqlite3WindowDelete(pParse->db, (yypminor->yy211)); } break; - case 288: /* trigger_cmd_list */ - case 293: /* trigger_cmd */ + case 289: /* trigger_cmd_list */ + case 294: /* trigger_cmd */ { sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy427)); } break; - case 290: /* trigger_event */ + case 291: /* trigger_event */ { sqlite3IdListDelete(pParse->db, (yypminor->yy286).b); } @@ -176321,7 +183419,9 @@ SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){ } #if YYGROWABLESTACK - if( pParser->yystack!=pParser->yystk0 ) YYFREE(pParser->yystack); + if( pParser->yystack!=pParser->yystk0 ){ + YYFREE(pParser->yystack, sqlite3ParserCTX(pParser)); + } #endif } @@ -176504,7 +183604,7 @@ static void yyStackOverflow(yyParser *yypParser){ ** stack every overflows */ /******** Begin %stack_overflow code ******************************************/ - sqlite3OomFault(pParse->db); + if( pParse->nErr==0 ) sqlite3ErrorMsg(pParse, "Recursion limit"); /******** End %stack_overflow code ********************************************/ sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument var */ sqlite3ParserCTX_STORE @@ -176570,415 +183670,418 @@ static void yy_shift( /* For rule J, yyRuleInfoLhs[J] contains the symbol on the left-hand side ** of that rule */ static const YYCODETYPE yyRuleInfoLhs[] = { - 190, /* (0) explain ::= EXPLAIN */ - 190, /* (1) explain ::= EXPLAIN QUERY PLAN */ - 189, /* (2) cmdx ::= cmd */ - 191, /* (3) cmd ::= BEGIN transtype trans_opt */ - 192, /* (4) transtype ::= */ - 192, /* (5) transtype ::= DEFERRED */ - 192, /* (6) transtype ::= IMMEDIATE */ - 192, /* (7) transtype ::= EXCLUSIVE */ - 191, /* (8) cmd ::= COMMIT|END trans_opt */ - 191, /* (9) cmd ::= ROLLBACK trans_opt */ - 191, /* (10) cmd ::= SAVEPOINT nm */ - 191, /* (11) cmd ::= RELEASE savepoint_opt nm */ - 191, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ - 196, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */ - 198, /* (14) createkw ::= CREATE */ - 200, /* (15) ifnotexists ::= */ - 200, /* (16) ifnotexists ::= IF NOT EXISTS */ - 199, /* (17) temp ::= TEMP */ - 199, /* (18) temp ::= */ - 197, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_option_set */ - 197, /* (20) create_table_args ::= AS select */ - 204, /* (21) table_option_set ::= */ - 204, /* (22) table_option_set ::= table_option_set COMMA table_option */ - 206, /* (23) table_option ::= WITHOUT nm */ - 206, /* (24) table_option ::= nm */ - 207, /* (25) columnname ::= nm typetoken */ - 209, /* (26) typetoken ::= */ - 209, /* (27) typetoken ::= typename LP signed RP */ - 209, /* (28) typetoken ::= typename LP signed COMMA signed RP */ - 210, /* (29) typename ::= typename ID|STRING */ - 214, /* (30) scanpt ::= */ - 215, /* (31) scantok ::= */ - 216, /* (32) ccons ::= CONSTRAINT nm */ - 216, /* (33) ccons ::= DEFAULT scantok term */ - 216, /* (34) ccons ::= DEFAULT LP expr RP */ - 216, /* (35) ccons ::= DEFAULT PLUS scantok term */ - 216, /* (36) ccons ::= DEFAULT MINUS scantok term */ - 216, /* (37) ccons ::= DEFAULT scantok ID|INDEXED */ - 216, /* (38) ccons ::= NOT NULL onconf */ - 216, /* (39) ccons ::= PRIMARY KEY sortorder onconf autoinc */ - 216, /* (40) ccons ::= UNIQUE onconf */ - 216, /* (41) ccons ::= CHECK LP expr RP */ - 216, /* (42) ccons ::= REFERENCES nm eidlist_opt refargs */ - 216, /* (43) ccons ::= defer_subclause */ - 216, /* (44) ccons ::= COLLATE ID|STRING */ - 225, /* (45) generated ::= LP expr RP */ - 225, /* (46) generated ::= LP expr RP ID */ - 221, /* (47) autoinc ::= */ - 221, /* (48) autoinc ::= AUTOINCR */ - 223, /* (49) refargs ::= */ - 223, /* (50) refargs ::= refargs refarg */ - 226, /* (51) refarg ::= MATCH nm */ - 226, /* (52) refarg ::= ON INSERT refact */ - 226, /* (53) refarg ::= ON DELETE refact */ - 226, /* (54) refarg ::= ON UPDATE refact */ - 227, /* (55) refact ::= SET NULL */ - 227, /* (56) refact ::= SET DEFAULT */ - 227, /* (57) refact ::= CASCADE */ - 227, /* (58) refact ::= RESTRICT */ - 227, /* (59) refact ::= NO ACTION */ - 224, /* (60) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ - 224, /* (61) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ - 228, /* (62) init_deferred_pred_opt ::= */ - 228, /* (63) init_deferred_pred_opt ::= INITIALLY DEFERRED */ - 228, /* (64) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ - 203, /* (65) conslist_opt ::= */ - 230, /* (66) tconscomma ::= COMMA */ - 231, /* (67) tcons ::= CONSTRAINT nm */ - 231, /* (68) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ - 231, /* (69) tcons ::= UNIQUE LP sortlist RP onconf */ - 231, /* (70) tcons ::= CHECK LP expr RP onconf */ - 231, /* (71) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */ - 234, /* (72) defer_subclause_opt ::= */ - 219, /* (73) onconf ::= */ - 219, /* (74) onconf ::= ON CONFLICT resolvetype */ - 235, /* (75) orconf ::= */ - 235, /* (76) orconf ::= OR resolvetype */ - 236, /* (77) resolvetype ::= IGNORE */ - 236, /* (78) resolvetype ::= REPLACE */ - 191, /* (79) cmd ::= DROP TABLE ifexists fullname */ - 238, /* (80) ifexists ::= IF EXISTS */ - 238, /* (81) ifexists ::= */ - 191, /* (82) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */ - 191, /* (83) cmd ::= DROP VIEW ifexists fullname */ - 191, /* (84) cmd ::= select */ - 205, /* (85) select ::= WITH wqlist selectnowith */ - 205, /* (86) select ::= WITH RECURSIVE wqlist selectnowith */ - 205, /* (87) select ::= selectnowith */ - 240, /* (88) selectnowith ::= selectnowith multiselect_op oneselect */ - 243, /* (89) multiselect_op ::= UNION */ - 243, /* (90) multiselect_op ::= UNION ALL */ - 243, /* (91) multiselect_op ::= EXCEPT|INTERSECT */ - 241, /* (92) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ - 241, /* (93) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */ - 253, /* (94) values ::= VALUES LP nexprlist RP */ - 241, /* (95) oneselect ::= mvalues */ - 255, /* (96) mvalues ::= values COMMA LP nexprlist RP */ - 255, /* (97) mvalues ::= mvalues COMMA LP nexprlist RP */ - 244, /* (98) distinct ::= DISTINCT */ - 244, /* (99) distinct ::= ALL */ - 244, /* (100) distinct ::= */ - 256, /* (101) sclp ::= */ - 245, /* (102) selcollist ::= sclp scanpt expr scanpt as */ - 245, /* (103) selcollist ::= sclp scanpt STAR */ - 245, /* (104) selcollist ::= sclp scanpt nm DOT STAR */ - 257, /* (105) as ::= AS nm */ - 257, /* (106) as ::= */ - 246, /* (107) from ::= */ - 246, /* (108) from ::= FROM seltablist */ - 259, /* (109) stl_prefix ::= seltablist joinop */ - 259, /* (110) stl_prefix ::= */ - 258, /* (111) seltablist ::= stl_prefix nm dbnm as on_using */ - 258, /* (112) seltablist ::= stl_prefix nm dbnm as indexed_by on_using */ - 258, /* (113) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_using */ - 258, /* (114) seltablist ::= stl_prefix LP select RP as on_using */ - 258, /* (115) seltablist ::= stl_prefix LP seltablist RP as on_using */ - 201, /* (116) dbnm ::= */ - 201, /* (117) dbnm ::= DOT nm */ - 239, /* (118) fullname ::= nm */ - 239, /* (119) fullname ::= nm DOT nm */ - 264, /* (120) xfullname ::= nm */ - 264, /* (121) xfullname ::= nm DOT nm */ - 264, /* (122) xfullname ::= nm DOT nm AS nm */ - 264, /* (123) xfullname ::= nm AS nm */ - 260, /* (124) joinop ::= COMMA|JOIN */ - 260, /* (125) joinop ::= JOIN_KW JOIN */ - 260, /* (126) joinop ::= JOIN_KW nm JOIN */ - 260, /* (127) joinop ::= JOIN_KW nm nm JOIN */ - 261, /* (128) on_using ::= ON expr */ - 261, /* (129) on_using ::= USING LP idlist RP */ - 261, /* (130) on_using ::= */ - 266, /* (131) indexed_opt ::= */ - 262, /* (132) indexed_by ::= INDEXED BY nm */ - 262, /* (133) indexed_by ::= NOT INDEXED */ - 250, /* (134) orderby_opt ::= */ - 250, /* (135) orderby_opt ::= ORDER BY sortlist */ - 232, /* (136) sortlist ::= sortlist COMMA expr sortorder nulls */ - 232, /* (137) sortlist ::= expr sortorder nulls */ - 220, /* (138) sortorder ::= ASC */ - 220, /* (139) sortorder ::= DESC */ - 220, /* (140) sortorder ::= */ - 267, /* (141) nulls ::= NULLS FIRST */ - 267, /* (142) nulls ::= NULLS LAST */ - 267, /* (143) nulls ::= */ - 248, /* (144) groupby_opt ::= */ - 248, /* (145) groupby_opt ::= GROUP BY nexprlist */ - 249, /* (146) having_opt ::= */ - 249, /* (147) having_opt ::= HAVING expr */ - 251, /* (148) limit_opt ::= */ - 251, /* (149) limit_opt ::= LIMIT expr */ - 251, /* (150) limit_opt ::= LIMIT expr OFFSET expr */ - 251, /* (151) limit_opt ::= LIMIT expr COMMA expr */ - 191, /* (152) cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret */ - 247, /* (153) where_opt ::= */ - 247, /* (154) where_opt ::= WHERE expr */ - 269, /* (155) where_opt_ret ::= */ - 269, /* (156) where_opt_ret ::= WHERE expr */ - 269, /* (157) where_opt_ret ::= RETURNING selcollist */ - 269, /* (158) where_opt_ret ::= WHERE expr RETURNING selcollist */ - 191, /* (159) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret */ - 270, /* (160) setlist ::= setlist COMMA nm EQ expr */ - 270, /* (161) setlist ::= setlist COMMA LP idlist RP EQ expr */ - 270, /* (162) setlist ::= nm EQ expr */ - 270, /* (163) setlist ::= LP idlist RP EQ expr */ - 191, /* (164) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */ - 191, /* (165) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning */ - 273, /* (166) upsert ::= */ - 273, /* (167) upsert ::= RETURNING selcollist */ - 273, /* (168) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert */ - 273, /* (169) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert */ - 273, /* (170) upsert ::= ON CONFLICT DO NOTHING returning */ - 273, /* (171) upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning */ - 274, /* (172) returning ::= RETURNING selcollist */ - 271, /* (173) insert_cmd ::= INSERT orconf */ - 271, /* (174) insert_cmd ::= REPLACE */ - 272, /* (175) idlist_opt ::= */ - 272, /* (176) idlist_opt ::= LP idlist RP */ - 265, /* (177) idlist ::= idlist COMMA nm */ - 265, /* (178) idlist ::= nm */ - 218, /* (179) expr ::= LP expr RP */ - 218, /* (180) expr ::= ID|INDEXED|JOIN_KW */ - 218, /* (181) expr ::= nm DOT nm */ - 218, /* (182) expr ::= nm DOT nm DOT nm */ - 217, /* (183) term ::= NULL|FLOAT|BLOB */ - 217, /* (184) term ::= STRING */ - 217, /* (185) term ::= INTEGER */ - 218, /* (186) expr ::= VARIABLE */ - 218, /* (187) expr ::= expr COLLATE ID|STRING */ - 218, /* (188) expr ::= CAST LP expr AS typetoken RP */ - 218, /* (189) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP */ - 218, /* (190) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP */ - 218, /* (191) expr ::= ID|INDEXED|JOIN_KW LP STAR RP */ - 218, /* (192) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */ - 218, /* (193) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP filter_over */ - 218, /* (194) expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */ - 217, /* (195) term ::= CTIME_KW */ - 218, /* (196) expr ::= LP nexprlist COMMA expr RP */ - 218, /* (197) expr ::= expr AND expr */ - 218, /* (198) expr ::= expr OR expr */ - 218, /* (199) expr ::= expr LT|GT|GE|LE expr */ - 218, /* (200) expr ::= expr EQ|NE expr */ - 218, /* (201) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ - 218, /* (202) expr ::= expr PLUS|MINUS expr */ - 218, /* (203) expr ::= expr STAR|SLASH|REM expr */ - 218, /* (204) expr ::= expr CONCAT expr */ - 276, /* (205) likeop ::= NOT LIKE_KW|MATCH */ - 218, /* (206) expr ::= expr likeop expr */ - 218, /* (207) expr ::= expr likeop expr ESCAPE expr */ - 218, /* (208) expr ::= expr ISNULL|NOTNULL */ - 218, /* (209) expr ::= expr NOT NULL */ - 218, /* (210) expr ::= expr IS expr */ - 218, /* (211) expr ::= expr IS NOT expr */ - 218, /* (212) expr ::= expr IS NOT DISTINCT FROM expr */ - 218, /* (213) expr ::= expr IS DISTINCT FROM expr */ - 218, /* (214) expr ::= NOT expr */ - 218, /* (215) expr ::= BITNOT expr */ - 218, /* (216) expr ::= PLUS|MINUS expr */ - 218, /* (217) expr ::= expr PTR expr */ - 277, /* (218) between_op ::= BETWEEN */ - 277, /* (219) between_op ::= NOT BETWEEN */ - 218, /* (220) expr ::= expr between_op expr AND expr */ - 278, /* (221) in_op ::= IN */ - 278, /* (222) in_op ::= NOT IN */ - 218, /* (223) expr ::= expr in_op LP exprlist RP */ - 218, /* (224) expr ::= LP select RP */ - 218, /* (225) expr ::= expr in_op LP select RP */ - 218, /* (226) expr ::= expr in_op nm dbnm paren_exprlist */ - 218, /* (227) expr ::= EXISTS LP select RP */ - 218, /* (228) expr ::= CASE case_operand case_exprlist case_else END */ - 281, /* (229) case_exprlist ::= case_exprlist WHEN expr THEN expr */ - 281, /* (230) case_exprlist ::= WHEN expr THEN expr */ - 282, /* (231) case_else ::= ELSE expr */ - 282, /* (232) case_else ::= */ - 280, /* (233) case_operand ::= */ - 263, /* (234) exprlist ::= */ - 254, /* (235) nexprlist ::= nexprlist COMMA expr */ - 254, /* (236) nexprlist ::= expr */ - 279, /* (237) paren_exprlist ::= */ - 279, /* (238) paren_exprlist ::= LP exprlist RP */ - 191, /* (239) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */ - 283, /* (240) uniqueflag ::= UNIQUE */ - 283, /* (241) uniqueflag ::= */ - 222, /* (242) eidlist_opt ::= */ - 222, /* (243) eidlist_opt ::= LP eidlist RP */ - 233, /* (244) eidlist ::= eidlist COMMA nm collate sortorder */ - 233, /* (245) eidlist ::= nm collate sortorder */ - 284, /* (246) collate ::= */ - 284, /* (247) collate ::= COLLATE ID|STRING */ - 191, /* (248) cmd ::= DROP INDEX ifexists fullname */ - 191, /* (249) cmd ::= VACUUM vinto */ - 191, /* (250) cmd ::= VACUUM nm vinto */ - 285, /* (251) vinto ::= INTO expr */ - 285, /* (252) vinto ::= */ - 191, /* (253) cmd ::= PRAGMA nm dbnm */ - 191, /* (254) cmd ::= PRAGMA nm dbnm EQ nmnum */ - 191, /* (255) cmd ::= PRAGMA nm dbnm LP nmnum RP */ - 191, /* (256) cmd ::= PRAGMA nm dbnm EQ minus_num */ - 191, /* (257) cmd ::= PRAGMA nm dbnm LP minus_num RP */ - 212, /* (258) plus_num ::= PLUS INTEGER|FLOAT */ - 213, /* (259) minus_num ::= MINUS INTEGER|FLOAT */ - 191, /* (260) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ - 287, /* (261) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ - 289, /* (262) trigger_time ::= BEFORE|AFTER */ - 289, /* (263) trigger_time ::= INSTEAD OF */ - 289, /* (264) trigger_time ::= */ - 290, /* (265) trigger_event ::= DELETE|INSERT */ - 290, /* (266) trigger_event ::= UPDATE */ - 290, /* (267) trigger_event ::= UPDATE OF idlist */ - 292, /* (268) when_clause ::= */ - 292, /* (269) when_clause ::= WHEN expr */ - 288, /* (270) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ - 288, /* (271) trigger_cmd_list ::= trigger_cmd SEMI */ - 294, /* (272) trnm ::= nm DOT nm */ - 295, /* (273) tridxby ::= INDEXED BY nm */ - 295, /* (274) tridxby ::= NOT INDEXED */ - 293, /* (275) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */ - 293, /* (276) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */ - 293, /* (277) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */ - 293, /* (278) trigger_cmd ::= scanpt select scanpt */ - 218, /* (279) expr ::= RAISE LP IGNORE RP */ - 218, /* (280) expr ::= RAISE LP raisetype COMMA expr RP */ - 237, /* (281) raisetype ::= ROLLBACK */ - 237, /* (282) raisetype ::= ABORT */ - 237, /* (283) raisetype ::= FAIL */ - 191, /* (284) cmd ::= DROP TRIGGER ifexists fullname */ - 191, /* (285) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ - 191, /* (286) cmd ::= DETACH database_kw_opt expr */ - 297, /* (287) key_opt ::= */ - 297, /* (288) key_opt ::= KEY expr */ - 191, /* (289) cmd ::= REINDEX */ - 191, /* (290) cmd ::= REINDEX nm dbnm */ - 191, /* (291) cmd ::= ANALYZE */ - 191, /* (292) cmd ::= ANALYZE nm dbnm */ - 191, /* (293) cmd ::= ALTER TABLE fullname RENAME TO nm */ - 191, /* (294) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */ - 191, /* (295) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */ - 298, /* (296) add_column_fullname ::= fullname */ - 191, /* (297) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */ - 191, /* (298) cmd ::= create_vtab */ - 191, /* (299) cmd ::= create_vtab LP vtabarglist RP */ - 300, /* (300) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ - 302, /* (301) vtabarg ::= */ - 303, /* (302) vtabargtoken ::= ANY */ - 303, /* (303) vtabargtoken ::= lp anylist RP */ - 304, /* (304) lp ::= LP */ - 268, /* (305) with ::= WITH wqlist */ - 268, /* (306) with ::= WITH RECURSIVE wqlist */ - 307, /* (307) wqas ::= AS */ - 307, /* (308) wqas ::= AS MATERIALIZED */ - 307, /* (309) wqas ::= AS NOT MATERIALIZED */ - 306, /* (310) wqitem ::= withnm eidlist_opt wqas LP select RP */ - 308, /* (311) withnm ::= nm */ - 242, /* (312) wqlist ::= wqitem */ - 242, /* (313) wqlist ::= wqlist COMMA wqitem */ - 309, /* (314) windowdefn_list ::= windowdefn_list COMMA windowdefn */ - 310, /* (315) windowdefn ::= nm AS LP window RP */ - 311, /* (316) window ::= PARTITION BY nexprlist orderby_opt frame_opt */ - 311, /* (317) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */ - 311, /* (318) window ::= ORDER BY sortlist frame_opt */ - 311, /* (319) window ::= nm ORDER BY sortlist frame_opt */ - 311, /* (320) window ::= nm frame_opt */ - 312, /* (321) frame_opt ::= */ - 312, /* (322) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */ - 312, /* (323) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */ - 316, /* (324) range_or_rows ::= RANGE|ROWS|GROUPS */ - 318, /* (325) frame_bound_s ::= frame_bound */ - 318, /* (326) frame_bound_s ::= UNBOUNDED PRECEDING */ - 319, /* (327) frame_bound_e ::= frame_bound */ - 319, /* (328) frame_bound_e ::= UNBOUNDED FOLLOWING */ - 317, /* (329) frame_bound ::= expr PRECEDING|FOLLOWING */ - 317, /* (330) frame_bound ::= CURRENT ROW */ - 320, /* (331) frame_exclude_opt ::= */ - 320, /* (332) frame_exclude_opt ::= EXCLUDE frame_exclude */ - 321, /* (333) frame_exclude ::= NO OTHERS */ - 321, /* (334) frame_exclude ::= CURRENT ROW */ - 321, /* (335) frame_exclude ::= GROUP|TIES */ - 252, /* (336) window_clause ::= WINDOW windowdefn_list */ - 275, /* (337) filter_over ::= filter_clause over_clause */ - 275, /* (338) filter_over ::= over_clause */ - 275, /* (339) filter_over ::= filter_clause */ - 315, /* (340) over_clause ::= OVER LP window RP */ - 315, /* (341) over_clause ::= OVER nm */ - 314, /* (342) filter_clause ::= FILTER LP WHERE expr RP */ - 217, /* (343) term ::= QNUMBER */ - 186, /* (344) input ::= cmdlist */ - 187, /* (345) cmdlist ::= cmdlist ecmd */ - 187, /* (346) cmdlist ::= ecmd */ - 188, /* (347) ecmd ::= SEMI */ - 188, /* (348) ecmd ::= cmdx SEMI */ - 188, /* (349) ecmd ::= explain cmdx SEMI */ - 193, /* (350) trans_opt ::= */ - 193, /* (351) trans_opt ::= TRANSACTION */ - 193, /* (352) trans_opt ::= TRANSACTION nm */ - 195, /* (353) savepoint_opt ::= SAVEPOINT */ - 195, /* (354) savepoint_opt ::= */ - 191, /* (355) cmd ::= create_table create_table_args */ - 204, /* (356) table_option_set ::= table_option */ - 202, /* (357) columnlist ::= columnlist COMMA columnname carglist */ - 202, /* (358) columnlist ::= columnname carglist */ - 194, /* (359) nm ::= ID|INDEXED|JOIN_KW */ - 194, /* (360) nm ::= STRING */ - 209, /* (361) typetoken ::= typename */ - 210, /* (362) typename ::= ID|STRING */ - 211, /* (363) signed ::= plus_num */ - 211, /* (364) signed ::= minus_num */ - 208, /* (365) carglist ::= carglist ccons */ - 208, /* (366) carglist ::= */ - 216, /* (367) ccons ::= NULL onconf */ - 216, /* (368) ccons ::= GENERATED ALWAYS AS generated */ - 216, /* (369) ccons ::= AS generated */ - 203, /* (370) conslist_opt ::= COMMA conslist */ - 229, /* (371) conslist ::= conslist tconscomma tcons */ - 229, /* (372) conslist ::= tcons */ - 230, /* (373) tconscomma ::= */ - 234, /* (374) defer_subclause_opt ::= defer_subclause */ - 236, /* (375) resolvetype ::= raisetype */ - 240, /* (376) selectnowith ::= oneselect */ - 241, /* (377) oneselect ::= values */ - 256, /* (378) sclp ::= selcollist COMMA */ - 257, /* (379) as ::= ID|STRING */ - 266, /* (380) indexed_opt ::= indexed_by */ - 274, /* (381) returning ::= */ - 218, /* (382) expr ::= term */ - 276, /* (383) likeop ::= LIKE_KW|MATCH */ - 280, /* (384) case_operand ::= expr */ - 263, /* (385) exprlist ::= nexprlist */ - 286, /* (386) nmnum ::= plus_num */ - 286, /* (387) nmnum ::= nm */ - 286, /* (388) nmnum ::= ON */ - 286, /* (389) nmnum ::= DELETE */ - 286, /* (390) nmnum ::= DEFAULT */ - 212, /* (391) plus_num ::= INTEGER|FLOAT */ - 291, /* (392) foreach_clause ::= */ - 291, /* (393) foreach_clause ::= FOR EACH ROW */ - 294, /* (394) trnm ::= nm */ - 295, /* (395) tridxby ::= */ - 296, /* (396) database_kw_opt ::= DATABASE */ - 296, /* (397) database_kw_opt ::= */ - 299, /* (398) kwcolumn_opt ::= */ - 299, /* (399) kwcolumn_opt ::= COLUMNKW */ - 301, /* (400) vtabarglist ::= vtabarg */ - 301, /* (401) vtabarglist ::= vtabarglist COMMA vtabarg */ - 302, /* (402) vtabarg ::= vtabarg vtabargtoken */ - 305, /* (403) anylist ::= */ - 305, /* (404) anylist ::= anylist LP anylist RP */ - 305, /* (405) anylist ::= anylist ANY */ - 268, /* (406) with ::= */ - 309, /* (407) windowdefn_list ::= windowdefn */ - 311, /* (408) window ::= frame_opt */ + 191, /* (0) explain ::= EXPLAIN */ + 191, /* (1) explain ::= EXPLAIN QUERY PLAN */ + 190, /* (2) cmdx ::= cmd */ + 192, /* (3) cmd ::= BEGIN transtype trans_opt */ + 193, /* (4) transtype ::= */ + 193, /* (5) transtype ::= DEFERRED */ + 193, /* (6) transtype ::= IMMEDIATE */ + 193, /* (7) transtype ::= EXCLUSIVE */ + 192, /* (8) cmd ::= COMMIT|END trans_opt */ + 192, /* (9) cmd ::= ROLLBACK trans_opt */ + 192, /* (10) cmd ::= SAVEPOINT nm */ + 192, /* (11) cmd ::= RELEASE savepoint_opt nm */ + 192, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */ + 197, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */ + 199, /* (14) createkw ::= CREATE */ + 201, /* (15) ifnotexists ::= */ + 201, /* (16) ifnotexists ::= IF NOT EXISTS */ + 200, /* (17) temp ::= TEMP */ + 200, /* (18) temp ::= */ + 198, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_option_set */ + 198, /* (20) create_table_args ::= AS select */ + 205, /* (21) table_option_set ::= */ + 205, /* (22) table_option_set ::= table_option_set COMMA table_option */ + 207, /* (23) table_option ::= WITHOUT nm */ + 207, /* (24) table_option ::= nm */ + 208, /* (25) columnname ::= nm typetoken */ + 210, /* (26) typetoken ::= */ + 210, /* (27) typetoken ::= typename LP signed RP */ + 210, /* (28) typetoken ::= typename LP signed COMMA signed RP */ + 211, /* (29) typename ::= typename ID|STRING */ + 215, /* (30) scanpt ::= */ + 216, /* (31) scantok ::= */ + 217, /* (32) ccons ::= CONSTRAINT nm */ + 217, /* (33) ccons ::= DEFAULT scantok term */ + 217, /* (34) ccons ::= DEFAULT LP expr RP */ + 217, /* (35) ccons ::= DEFAULT PLUS scantok term */ + 217, /* (36) ccons ::= DEFAULT MINUS scantok term */ + 217, /* (37) ccons ::= DEFAULT scantok ID|INDEXED */ + 217, /* (38) ccons ::= NOT NULL onconf */ + 217, /* (39) ccons ::= PRIMARY KEY sortorder onconf autoinc */ + 217, /* (40) ccons ::= UNIQUE onconf */ + 217, /* (41) ccons ::= CHECK LP expr RP */ + 217, /* (42) ccons ::= REFERENCES nm eidlist_opt refargs */ + 217, /* (43) ccons ::= defer_subclause */ + 217, /* (44) ccons ::= COLLATE ID|STRING */ + 226, /* (45) generated ::= LP expr RP */ + 226, /* (46) generated ::= LP expr RP ID */ + 222, /* (47) autoinc ::= */ + 222, /* (48) autoinc ::= AUTOINCR */ + 224, /* (49) refargs ::= */ + 224, /* (50) refargs ::= refargs refarg */ + 227, /* (51) refarg ::= MATCH nm */ + 227, /* (52) refarg ::= ON INSERT refact */ + 227, /* (53) refarg ::= ON DELETE refact */ + 227, /* (54) refarg ::= ON UPDATE refact */ + 228, /* (55) refact ::= SET NULL */ + 228, /* (56) refact ::= SET DEFAULT */ + 228, /* (57) refact ::= CASCADE */ + 228, /* (58) refact ::= RESTRICT */ + 228, /* (59) refact ::= NO ACTION */ + 225, /* (60) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ + 225, /* (61) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ + 229, /* (62) init_deferred_pred_opt ::= */ + 229, /* (63) init_deferred_pred_opt ::= INITIALLY DEFERRED */ + 229, /* (64) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ + 204, /* (65) conslist_opt ::= */ + 231, /* (66) tconscomma ::= COMMA */ + 232, /* (67) tcons ::= CONSTRAINT nm */ + 232, /* (68) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ + 232, /* (69) tcons ::= UNIQUE LP sortlist RP onconf */ + 232, /* (70) tcons ::= CHECK LP expr RP onconf */ + 232, /* (71) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */ + 235, /* (72) defer_subclause_opt ::= */ + 220, /* (73) onconf ::= */ + 220, /* (74) onconf ::= ON CONFLICT resolvetype */ + 236, /* (75) orconf ::= */ + 236, /* (76) orconf ::= OR resolvetype */ + 237, /* (77) resolvetype ::= IGNORE */ + 237, /* (78) resolvetype ::= REPLACE */ + 192, /* (79) cmd ::= DROP TABLE ifexists fullname */ + 239, /* (80) ifexists ::= IF EXISTS */ + 239, /* (81) ifexists ::= */ + 192, /* (82) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */ + 192, /* (83) cmd ::= DROP VIEW ifexists fullname */ + 192, /* (84) cmd ::= select */ + 206, /* (85) select ::= WITH wqlist selectnowith */ + 206, /* (86) select ::= WITH RECURSIVE wqlist selectnowith */ + 206, /* (87) select ::= selectnowith */ + 241, /* (88) selectnowith ::= selectnowith multiselect_op oneselect */ + 244, /* (89) multiselect_op ::= UNION */ + 244, /* (90) multiselect_op ::= UNION ALL */ + 244, /* (91) multiselect_op ::= EXCEPT|INTERSECT */ + 242, /* (92) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ + 242, /* (93) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */ + 254, /* (94) values ::= VALUES LP nexprlist RP */ + 242, /* (95) oneselect ::= mvalues */ + 256, /* (96) mvalues ::= values COMMA LP nexprlist RP */ + 256, /* (97) mvalues ::= mvalues COMMA LP nexprlist RP */ + 245, /* (98) distinct ::= DISTINCT */ + 245, /* (99) distinct ::= ALL */ + 245, /* (100) distinct ::= */ + 257, /* (101) sclp ::= */ + 246, /* (102) selcollist ::= sclp scanpt expr scanpt as */ + 246, /* (103) selcollist ::= sclp scanpt STAR */ + 246, /* (104) selcollist ::= sclp scanpt nm DOT STAR */ + 258, /* (105) as ::= AS nm */ + 258, /* (106) as ::= */ + 247, /* (107) from ::= */ + 247, /* (108) from ::= FROM seltablist */ + 260, /* (109) stl_prefix ::= seltablist joinop */ + 260, /* (110) stl_prefix ::= */ + 259, /* (111) seltablist ::= stl_prefix nm dbnm as on_using */ + 259, /* (112) seltablist ::= stl_prefix nm dbnm as indexed_by on_using */ + 259, /* (113) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_using */ + 259, /* (114) seltablist ::= stl_prefix LP select RP as on_using */ + 259, /* (115) seltablist ::= stl_prefix LP seltablist RP as on_using */ + 202, /* (116) dbnm ::= */ + 202, /* (117) dbnm ::= DOT nm */ + 240, /* (118) fullname ::= nm */ + 240, /* (119) fullname ::= nm DOT nm */ + 265, /* (120) xfullname ::= nm */ + 265, /* (121) xfullname ::= nm DOT nm */ + 265, /* (122) xfullname ::= nm AS nm */ + 265, /* (123) xfullname ::= nm DOT nm AS nm */ + 261, /* (124) joinop ::= COMMA|JOIN */ + 261, /* (125) joinop ::= JOIN_KW JOIN */ + 261, /* (126) joinop ::= JOIN_KW nm JOIN */ + 261, /* (127) joinop ::= JOIN_KW nm nm JOIN */ + 262, /* (128) on_using ::= ON expr */ + 262, /* (129) on_using ::= USING LP idlist RP */ + 262, /* (130) on_using ::= */ + 267, /* (131) indexed_opt ::= */ + 263, /* (132) indexed_by ::= INDEXED BY nm */ + 263, /* (133) indexed_by ::= NOT INDEXED */ + 251, /* (134) orderby_opt ::= */ + 251, /* (135) orderby_opt ::= ORDER BY sortlist */ + 233, /* (136) sortlist ::= sortlist COMMA expr sortorder nulls */ + 233, /* (137) sortlist ::= expr sortorder nulls */ + 221, /* (138) sortorder ::= ASC */ + 221, /* (139) sortorder ::= DESC */ + 221, /* (140) sortorder ::= */ + 268, /* (141) nulls ::= NULLS FIRST */ + 268, /* (142) nulls ::= NULLS LAST */ + 268, /* (143) nulls ::= */ + 249, /* (144) groupby_opt ::= */ + 249, /* (145) groupby_opt ::= GROUP BY nexprlist */ + 250, /* (146) having_opt ::= */ + 250, /* (147) having_opt ::= HAVING expr */ + 252, /* (148) limit_opt ::= */ + 252, /* (149) limit_opt ::= LIMIT expr */ + 252, /* (150) limit_opt ::= LIMIT expr OFFSET expr */ + 252, /* (151) limit_opt ::= LIMIT expr COMMA expr */ + 192, /* (152) cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret */ + 248, /* (153) where_opt ::= */ + 248, /* (154) where_opt ::= WHERE expr */ + 270, /* (155) where_opt_ret ::= */ + 270, /* (156) where_opt_ret ::= WHERE expr */ + 270, /* (157) where_opt_ret ::= RETURNING selcollist */ + 270, /* (158) where_opt_ret ::= WHERE expr RETURNING selcollist */ + 192, /* (159) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret */ + 271, /* (160) setlist ::= setlist COMMA nm EQ expr */ + 271, /* (161) setlist ::= setlist COMMA LP idlist RP EQ expr */ + 271, /* (162) setlist ::= nm EQ expr */ + 271, /* (163) setlist ::= LP idlist RP EQ expr */ + 192, /* (164) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */ + 192, /* (165) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning */ + 274, /* (166) upsert ::= */ + 274, /* (167) upsert ::= RETURNING selcollist */ + 274, /* (168) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt upsert */ + 274, /* (169) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert */ + 274, /* (170) upsert ::= ON CONFLICT DO NOTHING returning */ + 274, /* (171) upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning */ + 275, /* (172) returning ::= RETURNING selcollist */ + 272, /* (173) insert_cmd ::= INSERT orconf */ + 272, /* (174) insert_cmd ::= REPLACE */ + 273, /* (175) idlist_opt ::= */ + 273, /* (176) idlist_opt ::= LP idlist RP */ + 266, /* (177) idlist ::= idlist COMMA nm */ + 266, /* (178) idlist ::= nm */ + 219, /* (179) expr ::= LP expr RP */ + 219, /* (180) expr ::= ID|INDEXED|JOIN_KW */ + 219, /* (181) expr ::= nm DOT nm */ + 219, /* (182) expr ::= nm DOT nm DOT nm */ + 218, /* (183) term ::= NULL|FLOAT|BLOB */ + 218, /* (184) term ::= STRING */ + 218, /* (185) term ::= INTEGER */ + 219, /* (186) expr ::= VARIABLE */ + 219, /* (187) expr ::= expr COLLATE ID|STRING */ + 219, /* (188) expr ::= CAST LP expr AS typetoken RP */ + 219, /* (189) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP */ + 219, /* (190) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP */ + 219, /* (191) expr ::= ID|INDEXED|JOIN_KW LP STAR RP */ + 219, /* (192) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist RP filter_over */ + 219, /* (193) expr ::= ID|INDEXED|JOIN_KW LP distinct exprlist ORDER BY sortlist RP filter_over */ + 219, /* (194) expr ::= ID|INDEXED|JOIN_KW LP STAR RP filter_over */ + 218, /* (195) term ::= CTIME_KW */ + 219, /* (196) expr ::= LP nexprlist COMMA expr RP */ + 219, /* (197) expr ::= expr AND expr */ + 219, /* (198) expr ::= expr OR expr */ + 219, /* (199) expr ::= expr LT|GT|GE|LE expr */ + 219, /* (200) expr ::= expr EQ|NE expr */ + 219, /* (201) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ + 219, /* (202) expr ::= expr PLUS|MINUS expr */ + 219, /* (203) expr ::= expr STAR|SLASH|REM expr */ + 219, /* (204) expr ::= expr CONCAT expr */ + 277, /* (205) likeop ::= NOT LIKE_KW|MATCH */ + 219, /* (206) expr ::= expr likeop expr */ + 219, /* (207) expr ::= expr likeop expr ESCAPE expr */ + 219, /* (208) expr ::= expr ISNULL|NOTNULL */ + 219, /* (209) expr ::= expr NOT NULL */ + 219, /* (210) expr ::= expr IS expr */ + 219, /* (211) expr ::= expr IS NOT expr */ + 219, /* (212) expr ::= expr IS NOT DISTINCT FROM expr */ + 219, /* (213) expr ::= expr IS DISTINCT FROM expr */ + 219, /* (214) expr ::= NOT expr */ + 219, /* (215) expr ::= BITNOT expr */ + 219, /* (216) expr ::= PLUS|MINUS expr */ + 219, /* (217) expr ::= expr PTR expr */ + 278, /* (218) between_op ::= BETWEEN */ + 278, /* (219) between_op ::= NOT BETWEEN */ + 219, /* (220) expr ::= expr between_op expr AND expr */ + 279, /* (221) in_op ::= IN */ + 279, /* (222) in_op ::= NOT IN */ + 219, /* (223) expr ::= expr in_op LP exprlist RP */ + 219, /* (224) expr ::= LP select RP */ + 219, /* (225) expr ::= expr in_op LP select RP */ + 219, /* (226) expr ::= expr in_op nm dbnm paren_exprlist */ + 219, /* (227) expr ::= EXISTS LP select RP */ + 219, /* (228) expr ::= CASE case_operand case_exprlist case_else END */ + 282, /* (229) case_exprlist ::= case_exprlist WHEN expr THEN expr */ + 282, /* (230) case_exprlist ::= WHEN expr THEN expr */ + 283, /* (231) case_else ::= ELSE expr */ + 283, /* (232) case_else ::= */ + 281, /* (233) case_operand ::= */ + 264, /* (234) exprlist ::= */ + 255, /* (235) nexprlist ::= nexprlist COMMA expr */ + 255, /* (236) nexprlist ::= expr */ + 280, /* (237) paren_exprlist ::= */ + 280, /* (238) paren_exprlist ::= LP exprlist RP */ + 192, /* (239) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */ + 284, /* (240) uniqueflag ::= UNIQUE */ + 284, /* (241) uniqueflag ::= */ + 223, /* (242) eidlist_opt ::= */ + 223, /* (243) eidlist_opt ::= LP eidlist RP */ + 234, /* (244) eidlist ::= eidlist COMMA nm collate sortorder */ + 234, /* (245) eidlist ::= nm collate sortorder */ + 285, /* (246) collate ::= */ + 285, /* (247) collate ::= COLLATE ID|STRING */ + 192, /* (248) cmd ::= DROP INDEX ifexists fullname */ + 192, /* (249) cmd ::= VACUUM vinto */ + 192, /* (250) cmd ::= VACUUM nm vinto */ + 286, /* (251) vinto ::= INTO expr */ + 286, /* (252) vinto ::= */ + 192, /* (253) cmd ::= PRAGMA nm dbnm */ + 192, /* (254) cmd ::= PRAGMA nm dbnm EQ nmnum */ + 192, /* (255) cmd ::= PRAGMA nm dbnm LP nmnum RP */ + 192, /* (256) cmd ::= PRAGMA nm dbnm EQ minus_num */ + 192, /* (257) cmd ::= PRAGMA nm dbnm LP minus_num RP */ + 213, /* (258) plus_num ::= PLUS INTEGER|FLOAT */ + 214, /* (259) minus_num ::= MINUS INTEGER|FLOAT */ + 192, /* (260) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */ + 288, /* (261) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ + 290, /* (262) trigger_time ::= BEFORE|AFTER */ + 290, /* (263) trigger_time ::= INSTEAD OF */ + 290, /* (264) trigger_time ::= */ + 291, /* (265) trigger_event ::= DELETE|INSERT */ + 291, /* (266) trigger_event ::= UPDATE */ + 291, /* (267) trigger_event ::= UPDATE OF idlist */ + 293, /* (268) when_clause ::= */ + 293, /* (269) when_clause ::= WHEN expr */ + 289, /* (270) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ + 289, /* (271) trigger_cmd_list ::= trigger_cmd SEMI */ + 295, /* (272) tridxby ::= INDEXED BY nm */ + 295, /* (273) tridxby ::= NOT INDEXED */ + 294, /* (274) trigger_cmd ::= UPDATE orconf xfullname tridxby SET setlist from where_opt scanpt */ + 294, /* (275) trigger_cmd ::= scanpt insert_cmd INTO xfullname idlist_opt select upsert scanpt */ + 294, /* (276) trigger_cmd ::= DELETE FROM xfullname tridxby where_opt scanpt */ + 294, /* (277) trigger_cmd ::= scanpt select scanpt */ + 219, /* (278) expr ::= RAISE LP IGNORE RP */ + 219, /* (279) expr ::= RAISE LP raisetype COMMA expr RP */ + 238, /* (280) raisetype ::= ROLLBACK */ + 238, /* (281) raisetype ::= ABORT */ + 238, /* (282) raisetype ::= FAIL */ + 192, /* (283) cmd ::= DROP TRIGGER ifexists fullname */ + 192, /* (284) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ + 192, /* (285) cmd ::= DETACH database_kw_opt expr */ + 297, /* (286) key_opt ::= */ + 297, /* (287) key_opt ::= KEY expr */ + 192, /* (288) cmd ::= REINDEX */ + 192, /* (289) cmd ::= REINDEX nm dbnm */ + 192, /* (290) cmd ::= ANALYZE */ + 192, /* (291) cmd ::= ANALYZE nm dbnm */ + 192, /* (292) cmd ::= ALTER TABLE fullname RENAME TO nm */ + 192, /* (293) cmd ::= alter_add carglist */ + 298, /* (294) alter_add ::= ALTER TABLE fullname ADD kwcolumn_opt nm typetoken */ + 192, /* (295) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */ + 192, /* (296) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */ + 192, /* (297) cmd ::= ALTER TABLE fullname DROP CONSTRAINT nm */ + 192, /* (298) cmd ::= ALTER TABLE fullname ALTER kwcolumn_opt nm DROP NOT NULL */ + 192, /* (299) cmd ::= ALTER TABLE fullname ALTER kwcolumn_opt nm SET NOT NULL onconf */ + 192, /* (300) cmd ::= ALTER TABLE fullname ADD CONSTRAINT nm CHECK LP expr RP onconf */ + 192, /* (301) cmd ::= ALTER TABLE fullname ADD CHECK LP expr RP onconf */ + 192, /* (302) cmd ::= create_vtab */ + 192, /* (303) cmd ::= create_vtab LP vtabarglist RP */ + 300, /* (304) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ + 302, /* (305) vtabarg ::= */ + 303, /* (306) vtabargtoken ::= ANY */ + 303, /* (307) vtabargtoken ::= lp anylist RP */ + 304, /* (308) lp ::= LP */ + 269, /* (309) with ::= WITH wqlist */ + 269, /* (310) with ::= WITH RECURSIVE wqlist */ + 307, /* (311) wqas ::= AS */ + 307, /* (312) wqas ::= AS MATERIALIZED */ + 307, /* (313) wqas ::= AS NOT MATERIALIZED */ + 306, /* (314) wqitem ::= withnm eidlist_opt wqas LP select RP */ + 308, /* (315) withnm ::= nm */ + 243, /* (316) wqlist ::= wqitem */ + 243, /* (317) wqlist ::= wqlist COMMA wqitem */ + 309, /* (318) windowdefn_list ::= windowdefn_list COMMA windowdefn */ + 310, /* (319) windowdefn ::= nm AS LP window RP */ + 311, /* (320) window ::= PARTITION BY nexprlist orderby_opt frame_opt */ + 311, /* (321) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */ + 311, /* (322) window ::= ORDER BY sortlist frame_opt */ + 311, /* (323) window ::= nm ORDER BY sortlist frame_opt */ + 311, /* (324) window ::= nm frame_opt */ + 312, /* (325) frame_opt ::= */ + 312, /* (326) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */ + 312, /* (327) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */ + 316, /* (328) range_or_rows ::= RANGE|ROWS|GROUPS */ + 318, /* (329) frame_bound_s ::= frame_bound */ + 318, /* (330) frame_bound_s ::= UNBOUNDED PRECEDING */ + 319, /* (331) frame_bound_e ::= frame_bound */ + 319, /* (332) frame_bound_e ::= UNBOUNDED FOLLOWING */ + 317, /* (333) frame_bound ::= expr PRECEDING|FOLLOWING */ + 317, /* (334) frame_bound ::= CURRENT ROW */ + 320, /* (335) frame_exclude_opt ::= */ + 320, /* (336) frame_exclude_opt ::= EXCLUDE frame_exclude */ + 321, /* (337) frame_exclude ::= NO OTHERS */ + 321, /* (338) frame_exclude ::= CURRENT ROW */ + 321, /* (339) frame_exclude ::= GROUP|TIES */ + 253, /* (340) window_clause ::= WINDOW windowdefn_list */ + 276, /* (341) filter_over ::= filter_clause over_clause */ + 276, /* (342) filter_over ::= over_clause */ + 276, /* (343) filter_over ::= filter_clause */ + 315, /* (344) over_clause ::= OVER LP window RP */ + 315, /* (345) over_clause ::= OVER nm */ + 314, /* (346) filter_clause ::= FILTER LP WHERE expr RP */ + 218, /* (347) term ::= QNUMBER */ + 187, /* (348) input ::= cmdlist */ + 188, /* (349) cmdlist ::= cmdlist ecmd */ + 188, /* (350) cmdlist ::= ecmd */ + 189, /* (351) ecmd ::= SEMI */ + 189, /* (352) ecmd ::= cmdx SEMI */ + 189, /* (353) ecmd ::= explain cmdx SEMI */ + 194, /* (354) trans_opt ::= */ + 194, /* (355) trans_opt ::= TRANSACTION */ + 194, /* (356) trans_opt ::= TRANSACTION nm */ + 196, /* (357) savepoint_opt ::= SAVEPOINT */ + 196, /* (358) savepoint_opt ::= */ + 192, /* (359) cmd ::= create_table create_table_args */ + 205, /* (360) table_option_set ::= table_option */ + 203, /* (361) columnlist ::= columnlist COMMA columnname carglist */ + 203, /* (362) columnlist ::= columnname carglist */ + 195, /* (363) nm ::= ID|INDEXED|JOIN_KW */ + 195, /* (364) nm ::= STRING */ + 210, /* (365) typetoken ::= typename */ + 211, /* (366) typename ::= ID|STRING */ + 212, /* (367) signed ::= plus_num */ + 212, /* (368) signed ::= minus_num */ + 209, /* (369) carglist ::= carglist ccons */ + 209, /* (370) carglist ::= */ + 217, /* (371) ccons ::= NULL onconf */ + 217, /* (372) ccons ::= GENERATED ALWAYS AS generated */ + 217, /* (373) ccons ::= AS generated */ + 204, /* (374) conslist_opt ::= COMMA conslist */ + 230, /* (375) conslist ::= conslist tconscomma tcons */ + 230, /* (376) conslist ::= tcons */ + 231, /* (377) tconscomma ::= */ + 235, /* (378) defer_subclause_opt ::= defer_subclause */ + 237, /* (379) resolvetype ::= raisetype */ + 241, /* (380) selectnowith ::= oneselect */ + 242, /* (381) oneselect ::= values */ + 257, /* (382) sclp ::= selcollist COMMA */ + 258, /* (383) as ::= ID|STRING */ + 267, /* (384) indexed_opt ::= indexed_by */ + 275, /* (385) returning ::= */ + 219, /* (386) expr ::= term */ + 277, /* (387) likeop ::= LIKE_KW|MATCH */ + 281, /* (388) case_operand ::= expr */ + 264, /* (389) exprlist ::= nexprlist */ + 287, /* (390) nmnum ::= plus_num */ + 287, /* (391) nmnum ::= nm */ + 287, /* (392) nmnum ::= ON */ + 287, /* (393) nmnum ::= DELETE */ + 287, /* (394) nmnum ::= DEFAULT */ + 213, /* (395) plus_num ::= INTEGER|FLOAT */ + 292, /* (396) foreach_clause ::= */ + 292, /* (397) foreach_clause ::= FOR EACH ROW */ + 295, /* (398) tridxby ::= */ + 296, /* (399) database_kw_opt ::= DATABASE */ + 296, /* (400) database_kw_opt ::= */ + 299, /* (401) kwcolumn_opt ::= */ + 299, /* (402) kwcolumn_opt ::= COLUMNKW */ + 301, /* (403) vtabarglist ::= vtabarg */ + 301, /* (404) vtabarglist ::= vtabarglist COMMA vtabarg */ + 302, /* (405) vtabarg ::= vtabarg vtabargtoken */ + 305, /* (406) anylist ::= */ + 305, /* (407) anylist ::= anylist LP anylist RP */ + 305, /* (408) anylist ::= anylist ANY */ + 269, /* (409) with ::= */ + 309, /* (410) windowdefn_list ::= windowdefn */ + 311, /* (411) window ::= frame_opt */ }; /* For rule J, yyRuleInfoNRhs[J] contains the negative of the number @@ -177106,8 +184209,8 @@ static const signed char yyRuleInfoNRhs[] = { -3, /* (119) fullname ::= nm DOT nm */ -1, /* (120) xfullname ::= nm */ -3, /* (121) xfullname ::= nm DOT nm */ - -5, /* (122) xfullname ::= nm DOT nm AS nm */ - -3, /* (123) xfullname ::= nm AS nm */ + -3, /* (122) xfullname ::= nm AS nm */ + -5, /* (123) xfullname ::= nm DOT nm AS nm */ -1, /* (124) joinop ::= COMMA|JOIN */ -2, /* (125) joinop ::= JOIN_KW JOIN */ -3, /* (126) joinop ::= JOIN_KW nm JOIN */ @@ -177256,143 +184359,146 @@ static const signed char yyRuleInfoNRhs[] = { -2, /* (269) when_clause ::= WHEN expr */ -3, /* (270) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ -2, /* (271) trigger_cmd_list ::= trigger_cmd SEMI */ - -3, /* (272) trnm ::= nm DOT nm */ - -3, /* (273) tridxby ::= INDEXED BY nm */ - -2, /* (274) tridxby ::= NOT INDEXED */ - -9, /* (275) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */ - -8, /* (276) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */ - -6, /* (277) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */ - -3, /* (278) trigger_cmd ::= scanpt select scanpt */ - -4, /* (279) expr ::= RAISE LP IGNORE RP */ - -6, /* (280) expr ::= RAISE LP raisetype COMMA expr RP */ - -1, /* (281) raisetype ::= ROLLBACK */ - -1, /* (282) raisetype ::= ABORT */ - -1, /* (283) raisetype ::= FAIL */ - -4, /* (284) cmd ::= DROP TRIGGER ifexists fullname */ - -6, /* (285) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ - -3, /* (286) cmd ::= DETACH database_kw_opt expr */ - 0, /* (287) key_opt ::= */ - -2, /* (288) key_opt ::= KEY expr */ - -1, /* (289) cmd ::= REINDEX */ - -3, /* (290) cmd ::= REINDEX nm dbnm */ - -1, /* (291) cmd ::= ANALYZE */ - -3, /* (292) cmd ::= ANALYZE nm dbnm */ - -6, /* (293) cmd ::= ALTER TABLE fullname RENAME TO nm */ - -7, /* (294) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */ + -3, /* (272) tridxby ::= INDEXED BY nm */ + -2, /* (273) tridxby ::= NOT INDEXED */ + -9, /* (274) trigger_cmd ::= UPDATE orconf xfullname tridxby SET setlist from where_opt scanpt */ + -8, /* (275) trigger_cmd ::= scanpt insert_cmd INTO xfullname idlist_opt select upsert scanpt */ + -6, /* (276) trigger_cmd ::= DELETE FROM xfullname tridxby where_opt scanpt */ + -3, /* (277) trigger_cmd ::= scanpt select scanpt */ + -4, /* (278) expr ::= RAISE LP IGNORE RP */ + -6, /* (279) expr ::= RAISE LP raisetype COMMA expr RP */ + -1, /* (280) raisetype ::= ROLLBACK */ + -1, /* (281) raisetype ::= ABORT */ + -1, /* (282) raisetype ::= FAIL */ + -4, /* (283) cmd ::= DROP TRIGGER ifexists fullname */ + -6, /* (284) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ + -3, /* (285) cmd ::= DETACH database_kw_opt expr */ + 0, /* (286) key_opt ::= */ + -2, /* (287) key_opt ::= KEY expr */ + -1, /* (288) cmd ::= REINDEX */ + -3, /* (289) cmd ::= REINDEX nm dbnm */ + -1, /* (290) cmd ::= ANALYZE */ + -3, /* (291) cmd ::= ANALYZE nm dbnm */ + -6, /* (292) cmd ::= ALTER TABLE fullname RENAME TO nm */ + -2, /* (293) cmd ::= alter_add carglist */ + -7, /* (294) alter_add ::= ALTER TABLE fullname ADD kwcolumn_opt nm typetoken */ -6, /* (295) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */ - -1, /* (296) add_column_fullname ::= fullname */ - -8, /* (297) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */ - -1, /* (298) cmd ::= create_vtab */ - -4, /* (299) cmd ::= create_vtab LP vtabarglist RP */ - -8, /* (300) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ - 0, /* (301) vtabarg ::= */ - -1, /* (302) vtabargtoken ::= ANY */ - -3, /* (303) vtabargtoken ::= lp anylist RP */ - -1, /* (304) lp ::= LP */ - -2, /* (305) with ::= WITH wqlist */ - -3, /* (306) with ::= WITH RECURSIVE wqlist */ - -1, /* (307) wqas ::= AS */ - -2, /* (308) wqas ::= AS MATERIALIZED */ - -3, /* (309) wqas ::= AS NOT MATERIALIZED */ - -6, /* (310) wqitem ::= withnm eidlist_opt wqas LP select RP */ - -1, /* (311) withnm ::= nm */ - -1, /* (312) wqlist ::= wqitem */ - -3, /* (313) wqlist ::= wqlist COMMA wqitem */ - -3, /* (314) windowdefn_list ::= windowdefn_list COMMA windowdefn */ - -5, /* (315) windowdefn ::= nm AS LP window RP */ - -5, /* (316) window ::= PARTITION BY nexprlist orderby_opt frame_opt */ - -6, /* (317) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */ - -4, /* (318) window ::= ORDER BY sortlist frame_opt */ - -5, /* (319) window ::= nm ORDER BY sortlist frame_opt */ - -2, /* (320) window ::= nm frame_opt */ - 0, /* (321) frame_opt ::= */ - -3, /* (322) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */ - -6, /* (323) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */ - -1, /* (324) range_or_rows ::= RANGE|ROWS|GROUPS */ - -1, /* (325) frame_bound_s ::= frame_bound */ - -2, /* (326) frame_bound_s ::= UNBOUNDED PRECEDING */ - -1, /* (327) frame_bound_e ::= frame_bound */ - -2, /* (328) frame_bound_e ::= UNBOUNDED FOLLOWING */ - -2, /* (329) frame_bound ::= expr PRECEDING|FOLLOWING */ - -2, /* (330) frame_bound ::= CURRENT ROW */ - 0, /* (331) frame_exclude_opt ::= */ - -2, /* (332) frame_exclude_opt ::= EXCLUDE frame_exclude */ - -2, /* (333) frame_exclude ::= NO OTHERS */ - -2, /* (334) frame_exclude ::= CURRENT ROW */ - -1, /* (335) frame_exclude ::= GROUP|TIES */ - -2, /* (336) window_clause ::= WINDOW windowdefn_list */ - -2, /* (337) filter_over ::= filter_clause over_clause */ - -1, /* (338) filter_over ::= over_clause */ - -1, /* (339) filter_over ::= filter_clause */ - -4, /* (340) over_clause ::= OVER LP window RP */ - -2, /* (341) over_clause ::= OVER nm */ - -5, /* (342) filter_clause ::= FILTER LP WHERE expr RP */ - -1, /* (343) term ::= QNUMBER */ - -1, /* (344) input ::= cmdlist */ - -2, /* (345) cmdlist ::= cmdlist ecmd */ - -1, /* (346) cmdlist ::= ecmd */ - -1, /* (347) ecmd ::= SEMI */ - -2, /* (348) ecmd ::= cmdx SEMI */ - -3, /* (349) ecmd ::= explain cmdx SEMI */ - 0, /* (350) trans_opt ::= */ - -1, /* (351) trans_opt ::= TRANSACTION */ - -2, /* (352) trans_opt ::= TRANSACTION nm */ - -1, /* (353) savepoint_opt ::= SAVEPOINT */ - 0, /* (354) savepoint_opt ::= */ - -2, /* (355) cmd ::= create_table create_table_args */ - -1, /* (356) table_option_set ::= table_option */ - -4, /* (357) columnlist ::= columnlist COMMA columnname carglist */ - -2, /* (358) columnlist ::= columnname carglist */ - -1, /* (359) nm ::= ID|INDEXED|JOIN_KW */ - -1, /* (360) nm ::= STRING */ - -1, /* (361) typetoken ::= typename */ - -1, /* (362) typename ::= ID|STRING */ - -1, /* (363) signed ::= plus_num */ - -1, /* (364) signed ::= minus_num */ - -2, /* (365) carglist ::= carglist ccons */ - 0, /* (366) carglist ::= */ - -2, /* (367) ccons ::= NULL onconf */ - -4, /* (368) ccons ::= GENERATED ALWAYS AS generated */ - -2, /* (369) ccons ::= AS generated */ - -2, /* (370) conslist_opt ::= COMMA conslist */ - -3, /* (371) conslist ::= conslist tconscomma tcons */ - -1, /* (372) conslist ::= tcons */ - 0, /* (373) tconscomma ::= */ - -1, /* (374) defer_subclause_opt ::= defer_subclause */ - -1, /* (375) resolvetype ::= raisetype */ - -1, /* (376) selectnowith ::= oneselect */ - -1, /* (377) oneselect ::= values */ - -2, /* (378) sclp ::= selcollist COMMA */ - -1, /* (379) as ::= ID|STRING */ - -1, /* (380) indexed_opt ::= indexed_by */ - 0, /* (381) returning ::= */ - -1, /* (382) expr ::= term */ - -1, /* (383) likeop ::= LIKE_KW|MATCH */ - -1, /* (384) case_operand ::= expr */ - -1, /* (385) exprlist ::= nexprlist */ - -1, /* (386) nmnum ::= plus_num */ - -1, /* (387) nmnum ::= nm */ - -1, /* (388) nmnum ::= ON */ - -1, /* (389) nmnum ::= DELETE */ - -1, /* (390) nmnum ::= DEFAULT */ - -1, /* (391) plus_num ::= INTEGER|FLOAT */ - 0, /* (392) foreach_clause ::= */ - -3, /* (393) foreach_clause ::= FOR EACH ROW */ - -1, /* (394) trnm ::= nm */ - 0, /* (395) tridxby ::= */ - -1, /* (396) database_kw_opt ::= DATABASE */ - 0, /* (397) database_kw_opt ::= */ - 0, /* (398) kwcolumn_opt ::= */ - -1, /* (399) kwcolumn_opt ::= COLUMNKW */ - -1, /* (400) vtabarglist ::= vtabarg */ - -3, /* (401) vtabarglist ::= vtabarglist COMMA vtabarg */ - -2, /* (402) vtabarg ::= vtabarg vtabargtoken */ - 0, /* (403) anylist ::= */ - -4, /* (404) anylist ::= anylist LP anylist RP */ - -2, /* (405) anylist ::= anylist ANY */ - 0, /* (406) with ::= */ - -1, /* (407) windowdefn_list ::= windowdefn */ - -1, /* (408) window ::= frame_opt */ + -8, /* (296) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */ + -6, /* (297) cmd ::= ALTER TABLE fullname DROP CONSTRAINT nm */ + -9, /* (298) cmd ::= ALTER TABLE fullname ALTER kwcolumn_opt nm DROP NOT NULL */ + -10, /* (299) cmd ::= ALTER TABLE fullname ALTER kwcolumn_opt nm SET NOT NULL onconf */ + -11, /* (300) cmd ::= ALTER TABLE fullname ADD CONSTRAINT nm CHECK LP expr RP onconf */ + -9, /* (301) cmd ::= ALTER TABLE fullname ADD CHECK LP expr RP onconf */ + -1, /* (302) cmd ::= create_vtab */ + -4, /* (303) cmd ::= create_vtab LP vtabarglist RP */ + -8, /* (304) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ + 0, /* (305) vtabarg ::= */ + -1, /* (306) vtabargtoken ::= ANY */ + -3, /* (307) vtabargtoken ::= lp anylist RP */ + -1, /* (308) lp ::= LP */ + -2, /* (309) with ::= WITH wqlist */ + -3, /* (310) with ::= WITH RECURSIVE wqlist */ + -1, /* (311) wqas ::= AS */ + -2, /* (312) wqas ::= AS MATERIALIZED */ + -3, /* (313) wqas ::= AS NOT MATERIALIZED */ + -6, /* (314) wqitem ::= withnm eidlist_opt wqas LP select RP */ + -1, /* (315) withnm ::= nm */ + -1, /* (316) wqlist ::= wqitem */ + -3, /* (317) wqlist ::= wqlist COMMA wqitem */ + -3, /* (318) windowdefn_list ::= windowdefn_list COMMA windowdefn */ + -5, /* (319) windowdefn ::= nm AS LP window RP */ + -5, /* (320) window ::= PARTITION BY nexprlist orderby_opt frame_opt */ + -6, /* (321) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */ + -4, /* (322) window ::= ORDER BY sortlist frame_opt */ + -5, /* (323) window ::= nm ORDER BY sortlist frame_opt */ + -2, /* (324) window ::= nm frame_opt */ + 0, /* (325) frame_opt ::= */ + -3, /* (326) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */ + -6, /* (327) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */ + -1, /* (328) range_or_rows ::= RANGE|ROWS|GROUPS */ + -1, /* (329) frame_bound_s ::= frame_bound */ + -2, /* (330) frame_bound_s ::= UNBOUNDED PRECEDING */ + -1, /* (331) frame_bound_e ::= frame_bound */ + -2, /* (332) frame_bound_e ::= UNBOUNDED FOLLOWING */ + -2, /* (333) frame_bound ::= expr PRECEDING|FOLLOWING */ + -2, /* (334) frame_bound ::= CURRENT ROW */ + 0, /* (335) frame_exclude_opt ::= */ + -2, /* (336) frame_exclude_opt ::= EXCLUDE frame_exclude */ + -2, /* (337) frame_exclude ::= NO OTHERS */ + -2, /* (338) frame_exclude ::= CURRENT ROW */ + -1, /* (339) frame_exclude ::= GROUP|TIES */ + -2, /* (340) window_clause ::= WINDOW windowdefn_list */ + -2, /* (341) filter_over ::= filter_clause over_clause */ + -1, /* (342) filter_over ::= over_clause */ + -1, /* (343) filter_over ::= filter_clause */ + -4, /* (344) over_clause ::= OVER LP window RP */ + -2, /* (345) over_clause ::= OVER nm */ + -5, /* (346) filter_clause ::= FILTER LP WHERE expr RP */ + -1, /* (347) term ::= QNUMBER */ + -1, /* (348) input ::= cmdlist */ + -2, /* (349) cmdlist ::= cmdlist ecmd */ + -1, /* (350) cmdlist ::= ecmd */ + -1, /* (351) ecmd ::= SEMI */ + -2, /* (352) ecmd ::= cmdx SEMI */ + -3, /* (353) ecmd ::= explain cmdx SEMI */ + 0, /* (354) trans_opt ::= */ + -1, /* (355) trans_opt ::= TRANSACTION */ + -2, /* (356) trans_opt ::= TRANSACTION nm */ + -1, /* (357) savepoint_opt ::= SAVEPOINT */ + 0, /* (358) savepoint_opt ::= */ + -2, /* (359) cmd ::= create_table create_table_args */ + -1, /* (360) table_option_set ::= table_option */ + -4, /* (361) columnlist ::= columnlist COMMA columnname carglist */ + -2, /* (362) columnlist ::= columnname carglist */ + -1, /* (363) nm ::= ID|INDEXED|JOIN_KW */ + -1, /* (364) nm ::= STRING */ + -1, /* (365) typetoken ::= typename */ + -1, /* (366) typename ::= ID|STRING */ + -1, /* (367) signed ::= plus_num */ + -1, /* (368) signed ::= minus_num */ + -2, /* (369) carglist ::= carglist ccons */ + 0, /* (370) carglist ::= */ + -2, /* (371) ccons ::= NULL onconf */ + -4, /* (372) ccons ::= GENERATED ALWAYS AS generated */ + -2, /* (373) ccons ::= AS generated */ + -2, /* (374) conslist_opt ::= COMMA conslist */ + -3, /* (375) conslist ::= conslist tconscomma tcons */ + -1, /* (376) conslist ::= tcons */ + 0, /* (377) tconscomma ::= */ + -1, /* (378) defer_subclause_opt ::= defer_subclause */ + -1, /* (379) resolvetype ::= raisetype */ + -1, /* (380) selectnowith ::= oneselect */ + -1, /* (381) oneselect ::= values */ + -2, /* (382) sclp ::= selcollist COMMA */ + -1, /* (383) as ::= ID|STRING */ + -1, /* (384) indexed_opt ::= indexed_by */ + 0, /* (385) returning ::= */ + -1, /* (386) expr ::= term */ + -1, /* (387) likeop ::= LIKE_KW|MATCH */ + -1, /* (388) case_operand ::= expr */ + -1, /* (389) exprlist ::= nexprlist */ + -1, /* (390) nmnum ::= plus_num */ + -1, /* (391) nmnum ::= nm */ + -1, /* (392) nmnum ::= ON */ + -1, /* (393) nmnum ::= DELETE */ + -1, /* (394) nmnum ::= DEFAULT */ + -1, /* (395) plus_num ::= INTEGER|FLOAT */ + 0, /* (396) foreach_clause ::= */ + -3, /* (397) foreach_clause ::= FOR EACH ROW */ + 0, /* (398) tridxby ::= */ + -1, /* (399) database_kw_opt ::= DATABASE */ + 0, /* (400) database_kw_opt ::= */ + 0, /* (401) kwcolumn_opt ::= */ + -1, /* (402) kwcolumn_opt ::= COLUMNKW */ + -1, /* (403) vtabarglist ::= vtabarg */ + -3, /* (404) vtabarglist ::= vtabarglist COMMA vtabarg */ + -2, /* (405) vtabarg ::= vtabarg vtabargtoken */ + 0, /* (406) anylist ::= */ + -4, /* (407) anylist ::= anylist LP anylist RP */ + -2, /* (408) anylist ::= anylist ANY */ + 0, /* (409) with ::= */ + -1, /* (410) windowdefn_list ::= windowdefn */ + -1, /* (411) window ::= frame_opt */ }; static void yy_accept(yyParser*); /* Forward Declaration */ @@ -177452,7 +184558,7 @@ static YYACTIONTYPE yy_reduce( case 5: /* transtype ::= DEFERRED */ case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6); case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7); - case 324: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==324); + case 328: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==328); {yymsp[0].minor.yy144 = yymsp[0].major; /*A-overwrites-X*/} break; case 8: /* cmd ::= COMMIT|END trans_opt */ @@ -177480,7 +184586,9 @@ static YYACTIONTYPE yy_reduce( } break; case 14: /* createkw ::= CREATE */ -{disableLookaside(pParse);} +{ + disableLookaside(pParse); +} break; case 15: /* ifnotexists ::= */ case 18: /* temp ::= */ yytestcase(yyruleno==18); @@ -177572,7 +184680,7 @@ static YYACTIONTYPE yy_reduce( break; case 32: /* ccons ::= CONSTRAINT nm */ case 67: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==67); -{pParse->constraintName = yymsp[0].minor.yy0;} +{ASSERT_IS_CREATE; pParse->u1.cr.constraintName = yymsp[0].minor.yy0;} break; case 33: /* ccons ::= DEFAULT scantok term */ {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy454,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);} @@ -177682,7 +184790,7 @@ static YYACTIONTYPE yy_reduce( {yymsp[-1].minor.yy144 = 0;} break; case 66: /* tconscomma ::= COMMA */ -{pParse->constraintName.n = 0;} +{ASSERT_IS_CREATE; pParse->u1.cr.constraintName.n = 0;} break; case 68: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy144,yymsp[-2].minor.yy144,0);} @@ -177732,7 +184840,11 @@ static YYACTIONTYPE yy_reduce( case 84: /* cmd ::= select */ { SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0, 0}; - sqlite3Select(pParse, yymsp[0].minor.yy555, &dest); + if( (pParse->db->mDbFlags & DBFLAG_EncodingFixed)!=0 + || sqlite3ReadSchema(pParse)==SQLITE_OK + ){ + sqlite3Select(pParse, yymsp[0].minor.yy555, &dest); + } sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy555); } break; @@ -177765,8 +184877,8 @@ static YYACTIONTYPE yy_reduce( if( pRhs ){ pRhs->op = (u8)yymsp[-1].minor.yy144; pRhs->pPrior = pLhs; - if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue; - pRhs->selFlags &= ~SF_MultiValue; + if( ALWAYS(pLhs) ) pLhs->selFlags &= ~(u32)SF_MultiValue; + pRhs->selFlags &= ~(u32)SF_MultiValue; if( yymsp[-1].minor.yy144!=TK_ALL ) pParse->hasCompound = 1; }else{ sqlite3SelectDelete(pParse->db, pLhs); @@ -177904,6 +185016,7 @@ static YYACTIONTYPE yy_reduce( SrcItem *pOld = yymsp[-3].minor.yy203->a; assert( pOld->fg.fixedSchema==0 ); pNew->zName = pOld->zName; + pOld->zName = 0; assert( pOld->fg.fixedSchema==0 ); if( pOld->fg.isSubquery ){ pNew->fg.isSubquery = 1; @@ -177923,8 +185036,13 @@ static YYACTIONTYPE yy_reduce( pOld->u1.pFuncArg = 0; pOld->fg.isTabFunc = 0; pNew->fg.isTabFunc = 1; + }else if( pOld->fg.isIndexedBy ){ + pNew->u1.zIndexedBy = pOld->u1.zIndexedBy; + pOld->u1.zIndexedBy = 0; + pOld->fg.isIndexedBy = 0; + pNew->fg.isIndexedBy = 1; } - pOld->zName = 0; + pNew->fg.notIndexed = pOld->fg.notIndexed; } sqlite3SrcListDelete(pParse->db, yymsp[-3].minor.yy203); }else{ @@ -177940,6 +185058,7 @@ static YYACTIONTYPE yy_reduce( {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;} break; case 118: /* fullname ::= nm */ + case 120: /* xfullname ::= nm */ yytestcase(yyruleno==120); { yylhsminor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); if( IN_RENAME_OBJECT && yylhsminor.yy203 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy203->a[0].zName, &yymsp[0].minor.yy0); @@ -177947,29 +185066,38 @@ static YYACTIONTYPE yy_reduce( yymsp[0].minor.yy203 = yylhsminor.yy203; break; case 119: /* fullname ::= nm DOT nm */ + case 121: /* xfullname ::= nm DOT nm */ yytestcase(yyruleno==121); { yylhsminor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); if( IN_RENAME_OBJECT && yylhsminor.yy203 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy203->a[0].zName, &yymsp[0].minor.yy0); } yymsp[-2].minor.yy203 = yylhsminor.yy203; break; - case 120: /* xfullname ::= nm */ -{yymsp[0].minor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/} - break; - case 121: /* xfullname ::= nm DOT nm */ -{yymsp[-2].minor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/} - break; - case 122: /* xfullname ::= nm DOT nm AS nm */ + case 122: /* xfullname ::= nm AS nm */ { - yymsp[-4].minor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/ - if( yymsp[-4].minor.yy203 ) yymsp[-4].minor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0); + yylhsminor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); + if( yylhsminor.yy203 ){ + if( IN_RENAME_OBJECT ){ + sqlite3RenameTokenMap(pParse, yylhsminor.yy203->a[0].zName, &yymsp[-2].minor.yy0); + }else{ + yylhsminor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0); + } + } } + yymsp[-2].minor.yy203 = yylhsminor.yy203; break; - case 123: /* xfullname ::= nm AS nm */ + case 123: /* xfullname ::= nm DOT nm AS nm */ { - yymsp[-2].minor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/ - if( yymsp[-2].minor.yy203 ) yymsp[-2].minor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0); + yylhsminor.yy203 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); + if( yylhsminor.yy203 ){ + if( IN_RENAME_OBJECT ){ + sqlite3RenameTokenMap(pParse, yylhsminor.yy203->a[0].zName, &yymsp[-2].minor.yy0); + }else{ + yylhsminor.yy203->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0); + } + } } + yymsp[-4].minor.yy203 = yylhsminor.yy203; break; case 124: /* joinop ::= COMMA|JOIN */ { yymsp[0].minor.yy144 = JT_INNER; } @@ -178185,7 +185313,12 @@ static YYACTIONTYPE yy_reduce( break; case 185: /* term ::= INTEGER */ { - yylhsminor.yy454 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1); + int iValue; + if( sqlite3GetInt32(yymsp[0].minor.yy0.z, &iValue)==0 ){ + yylhsminor.yy454 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 0); + }else{ + yylhsminor.yy454 = sqlite3ExprInt32(pParse->db, iValue); + } if( yylhsminor.yy454 ) yylhsminor.yy454->w.iOfst = (int)(yymsp[0].minor.yy0.z - pParse->zTail); } yymsp[0].minor.yy454 = yylhsminor.yy454; @@ -178203,7 +185336,7 @@ static YYACTIONTYPE yy_reduce( Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/ assert( t.n>=2 ); if( pParse->nested==0 ){ - sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t); + parserSyntaxError(pParse, &t); yymsp[0].minor.yy454 = 0; }else{ yymsp[0].minor.yy454 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0); @@ -178275,9 +185408,11 @@ static YYACTIONTYPE yy_reduce( ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy14, yymsp[-1].minor.yy454); yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0); if( yymsp[-4].minor.yy454 ){ + int i; yymsp[-4].minor.yy454->x.pList = pList; - if( ALWAYS(pList->nExpr) ){ - yymsp[-4].minor.yy454->flags |= pList->a[0].pExpr->flags & EP_Propagate; + for(i=0; i<pList->nExpr; i++){ + assert( pList->a[i].pExpr!=0 ); + yymsp[-4].minor.yy454->flags |= pList->a[i].pExpr->flags & EP_Propagate; } }else{ sqlite3ExprListDelete(pParse->db, pList); @@ -178325,33 +185460,29 @@ static YYACTIONTYPE yy_reduce( } break; case 208: /* expr ::= expr ISNULL|NOTNULL */ -{yymsp[-1].minor.yy454 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy454,0);} +{yymsp[-1].minor.yy454 = sqlite3PExprIsNull(pParse,yymsp[0].major,yymsp[-1].minor.yy454);} break; case 209: /* expr ::= expr NOT NULL */ -{yymsp[-2].minor.yy454 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy454,0);} +{yymsp[-2].minor.yy454 = sqlite3PExprIsNull(pParse,TK_NOTNULL,yymsp[-2].minor.yy454);} break; case 210: /* expr ::= expr IS expr */ { - yymsp[-2].minor.yy454 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy454,yymsp[0].minor.yy454); - binaryToUnaryIfNull(pParse, yymsp[0].minor.yy454, yymsp[-2].minor.yy454, TK_ISNULL); + yymsp[-2].minor.yy454 = sqlite3PExprIs(pParse, TK_IS, yymsp[-2].minor.yy454, yymsp[0].minor.yy454); } break; case 211: /* expr ::= expr IS NOT expr */ { - yymsp[-3].minor.yy454 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy454,yymsp[0].minor.yy454); - binaryToUnaryIfNull(pParse, yymsp[0].minor.yy454, yymsp[-3].minor.yy454, TK_NOTNULL); + yymsp[-3].minor.yy454 = sqlite3PExprIs(pParse, TK_ISNOT, yymsp[-3].minor.yy454, yymsp[0].minor.yy454); } break; case 212: /* expr ::= expr IS NOT DISTINCT FROM expr */ { - yymsp[-5].minor.yy454 = sqlite3PExpr(pParse,TK_IS,yymsp[-5].minor.yy454,yymsp[0].minor.yy454); - binaryToUnaryIfNull(pParse, yymsp[0].minor.yy454, yymsp[-5].minor.yy454, TK_ISNULL); + yymsp[-5].minor.yy454 = sqlite3PExprIs(pParse, TK_IS, yymsp[-5].minor.yy454, yymsp[0].minor.yy454); } break; case 213: /* expr ::= expr IS DISTINCT FROM expr */ { - yymsp[-4].minor.yy454 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-4].minor.yy454,yymsp[0].minor.yy454); - binaryToUnaryIfNull(pParse, yymsp[0].minor.yy454, yymsp[-4].minor.yy454, TK_NOTNULL); + yymsp[-4].minor.yy454 = sqlite3PExprIs(pParse, TK_ISNOT, yymsp[-4].minor.yy454, yymsp[0].minor.yy454); } break; case 214: /* expr ::= NOT expr */ @@ -178392,6 +185523,7 @@ static YYACTIONTYPE yy_reduce( yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy454, 0); if( yymsp[-4].minor.yy454 ){ yymsp[-4].minor.yy454->x.pList = pList; + sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy454); }else{ sqlite3ExprListDelete(pParse->db, pList); } @@ -178406,15 +185538,28 @@ static YYACTIONTYPE yy_reduce( ** expr1 IN () ** expr1 NOT IN () ** - ** simplify to constants 0 (false) and 1 (true), respectively, - ** regardless of the value of expr1. + ** simplify to constants 0 (false) and 1 (true), respectively. + ** + ** Except, do not apply this optimization if expr1 contains a function + ** because that function might be an aggregate (we don't know yet whether + ** it is or not) and if it is an aggregate, that could change the meaning + ** of the whole query. */ - sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy454); - yymsp[-4].minor.yy454 = sqlite3Expr(pParse->db, TK_STRING, yymsp[-3].minor.yy144 ? "true" : "false"); - if( yymsp[-4].minor.yy454 ) sqlite3ExprIdToTrueFalse(yymsp[-4].minor.yy454); + Expr *pB = sqlite3Expr(pParse->db, TK_STRING, yymsp[-3].minor.yy144 ? "true" : "false"); + if( pB ) sqlite3ExprIdToTrueFalse(pB); + if( !ExprHasProperty(yymsp[-4].minor.yy454, EP_HasFunc) ){ + sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy454); + yymsp[-4].minor.yy454 = pB; + }else{ + yymsp[-4].minor.yy454 = sqlite3PExpr(pParse, yymsp[-3].minor.yy144 ? TK_OR : TK_AND, pB, yymsp[-4].minor.yy454); + } }else{ Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr; - if( yymsp[-1].minor.yy14->nExpr==1 && sqlite3ExprIsConstant(pParse,pRHS) && yymsp[-4].minor.yy454->op!=TK_VECTOR ){ + if( yymsp[-1].minor.yy14->nExpr==1 + && sqlite3ExprIsConstant(pParse,pRHS) + && pRHS->op!=TK_COLLATE + && yymsp[-4].minor.yy454->op!=TK_VECTOR + ){ yymsp[-1].minor.yy14->a[0].pExpr = 0; sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14); pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0); @@ -178519,7 +185664,7 @@ static YYACTIONTYPE yy_reduce( } break; case 240: /* uniqueflag ::= UNIQUE */ - case 282: /* raisetype ::= ABORT */ yytestcase(yyruleno==282); + case 281: /* raisetype ::= ABORT */ yytestcase(yyruleno==281); {yymsp[0].minor.yy144 = OE_Abort;} break; case 241: /* uniqueflag ::= */ @@ -178571,6 +185716,10 @@ static YYACTIONTYPE yy_reduce( { sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy144, yymsp[-4].minor.yy286.a, yymsp[-4].minor.yy286.b, yymsp[-2].minor.yy203, yymsp[0].minor.yy454, yymsp[-10].minor.yy144, yymsp[-8].minor.yy144); yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/ +#ifdef SQLITE_DEBUG + assert( pParse->isCreate ); /* Set by createkw reduce action */ + pParse->isCreate = 0; /* But, should not be set for CREATE TRIGGER */ +#endif } break; case 262: /* trigger_time ::= BEFORE|AFTER */ @@ -178590,67 +185739,57 @@ static YYACTIONTYPE yy_reduce( {yymsp[-2].minor.yy286.a = TK_UPDATE; yymsp[-2].minor.yy286.b = yymsp[0].minor.yy132;} break; case 268: /* when_clause ::= */ - case 287: /* key_opt ::= */ yytestcase(yyruleno==287); + case 286: /* key_opt ::= */ yytestcase(yyruleno==286); { yymsp[1].minor.yy454 = 0; } break; case 269: /* when_clause ::= WHEN expr */ - case 288: /* key_opt ::= KEY expr */ yytestcase(yyruleno==288); + case 287: /* key_opt ::= KEY expr */ yytestcase(yyruleno==287); { yymsp[-1].minor.yy454 = yymsp[0].minor.yy454; } break; case 270: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ { - assert( yymsp[-2].minor.yy427!=0 ); yymsp[-2].minor.yy427->pLast->pNext = yymsp[-1].minor.yy427; yymsp[-2].minor.yy427->pLast = yymsp[-1].minor.yy427; } break; case 271: /* trigger_cmd_list ::= trigger_cmd SEMI */ { - assert( yymsp[-1].minor.yy427!=0 ); yymsp[-1].minor.yy427->pLast = yymsp[-1].minor.yy427; } break; - case 272: /* trnm ::= nm DOT nm */ -{ - yymsp[-2].minor.yy0 = yymsp[0].minor.yy0; - sqlite3ErrorMsg(pParse, - "qualified table names are not allowed on INSERT, UPDATE, and DELETE " - "statements within triggers"); -} - break; - case 273: /* tridxby ::= INDEXED BY nm */ + case 272: /* tridxby ::= INDEXED BY nm */ { sqlite3ErrorMsg(pParse, "the INDEXED BY clause is not allowed on UPDATE or DELETE statements " "within triggers"); } break; - case 274: /* tridxby ::= NOT INDEXED */ + case 273: /* tridxby ::= NOT INDEXED */ { sqlite3ErrorMsg(pParse, "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements " "within triggers"); } break; - case 275: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */ -{yylhsminor.yy427 = sqlite3TriggerUpdateStep(pParse, &yymsp[-6].minor.yy0, yymsp[-2].minor.yy203, yymsp[-3].minor.yy14, yymsp[-1].minor.yy454, yymsp[-7].minor.yy144, yymsp[-8].minor.yy0.z, yymsp[0].minor.yy168);} + case 274: /* trigger_cmd ::= UPDATE orconf xfullname tridxby SET setlist from where_opt scanpt */ +{yylhsminor.yy427 = sqlite3TriggerUpdateStep(pParse, yymsp[-6].minor.yy203, yymsp[-2].minor.yy203, yymsp[-3].minor.yy14, yymsp[-1].minor.yy454, yymsp[-7].minor.yy144, yymsp[-8].minor.yy0.z, yymsp[0].minor.yy168);} yymsp[-8].minor.yy427 = yylhsminor.yy427; break; - case 276: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */ + case 275: /* trigger_cmd ::= scanpt insert_cmd INTO xfullname idlist_opt select upsert scanpt */ { - yylhsminor.yy427 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy132,yymsp[-2].minor.yy555,yymsp[-6].minor.yy144,yymsp[-1].minor.yy122,yymsp[-7].minor.yy168,yymsp[0].minor.yy168);/*yylhsminor.yy427-overwrites-yymsp[-6].minor.yy144*/ + yylhsminor.yy427 = sqlite3TriggerInsertStep(pParse,yymsp[-4].minor.yy203,yymsp[-3].minor.yy132,yymsp[-2].minor.yy555,yymsp[-6].minor.yy144,yymsp[-1].minor.yy122,yymsp[-7].minor.yy168,yymsp[0].minor.yy168);/*yylhsminor.yy427-overwrites-yymsp[-6].minor.yy144*/ } yymsp[-7].minor.yy427 = yylhsminor.yy427; break; - case 277: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */ -{yylhsminor.yy427 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy454, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy168);} + case 276: /* trigger_cmd ::= DELETE FROM xfullname tridxby where_opt scanpt */ +{yylhsminor.yy427 = sqlite3TriggerDeleteStep(pParse, yymsp[-3].minor.yy203, yymsp[-1].minor.yy454, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy168);} yymsp[-5].minor.yy427 = yylhsminor.yy427; break; - case 278: /* trigger_cmd ::= scanpt select scanpt */ + case 277: /* trigger_cmd ::= scanpt select scanpt */ {yylhsminor.yy427 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy555, yymsp[-2].minor.yy168, yymsp[0].minor.yy168); /*yylhsminor.yy427-overwrites-yymsp[-1].minor.yy555*/} yymsp[-2].minor.yy427 = yylhsminor.yy427; break; - case 279: /* expr ::= RAISE LP IGNORE RP */ + case 278: /* expr ::= RAISE LP IGNORE RP */ { yymsp[-3].minor.yy454 = sqlite3PExpr(pParse, TK_RAISE, 0, 0); if( yymsp[-3].minor.yy454 ){ @@ -178658,7 +185797,7 @@ static YYACTIONTYPE yy_reduce( } } break; - case 280: /* expr ::= RAISE LP raisetype COMMA expr RP */ + case 279: /* expr ::= RAISE LP raisetype COMMA expr RP */ { yymsp[-5].minor.yy454 = sqlite3PExpr(pParse, TK_RAISE, yymsp[-1].minor.yy454, 0); if( yymsp[-5].minor.yy454 ) { @@ -178666,48 +185805,56 @@ static YYACTIONTYPE yy_reduce( } } break; - case 281: /* raisetype ::= ROLLBACK */ + case 280: /* raisetype ::= ROLLBACK */ {yymsp[0].minor.yy144 = OE_Rollback;} break; - case 283: /* raisetype ::= FAIL */ + case 282: /* raisetype ::= FAIL */ {yymsp[0].minor.yy144 = OE_Fail;} break; - case 284: /* cmd ::= DROP TRIGGER ifexists fullname */ + case 283: /* cmd ::= DROP TRIGGER ifexists fullname */ { sqlite3DropTrigger(pParse,yymsp[0].minor.yy203,yymsp[-1].minor.yy144); } break; - case 285: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ + case 284: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ { sqlite3Attach(pParse, yymsp[-3].minor.yy454, yymsp[-1].minor.yy454, yymsp[0].minor.yy454); } break; - case 286: /* cmd ::= DETACH database_kw_opt expr */ + case 285: /* cmd ::= DETACH database_kw_opt expr */ { sqlite3Detach(pParse, yymsp[0].minor.yy454); } break; - case 289: /* cmd ::= REINDEX */ + case 288: /* cmd ::= REINDEX */ {sqlite3Reindex(pParse, 0, 0);} break; - case 290: /* cmd ::= REINDEX nm dbnm */ + case 289: /* cmd ::= REINDEX nm dbnm */ {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} break; - case 291: /* cmd ::= ANALYZE */ + case 290: /* cmd ::= ANALYZE */ {sqlite3Analyze(pParse, 0, 0);} break; - case 292: /* cmd ::= ANALYZE nm dbnm */ + case 291: /* cmd ::= ANALYZE nm dbnm */ {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} break; - case 293: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ + case 292: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ { sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy203,&yymsp[0].minor.yy0); } break; - case 294: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */ + case 293: /* cmd ::= alter_add carglist */ { yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n; sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0); +} + break; + case 294: /* alter_add ::= ALTER TABLE fullname ADD kwcolumn_opt nm typetoken */ +{ + disableLookaside(pParse); + sqlite3AlterBeginAddColumn(pParse, yymsp[-4].minor.yy203); + sqlite3AddColumn(pParse, yymsp[-1].minor.yy0, yymsp[0].minor.yy0); + yymsp[-6].minor.yy0 = yymsp[-1].minor.yy0; } break; case 295: /* cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */ @@ -178715,68 +185862,87 @@ static YYACTIONTYPE yy_reduce( sqlite3AlterDropColumn(pParse, yymsp[-3].minor.yy203, &yymsp[0].minor.yy0); } break; - case 296: /* add_column_fullname ::= fullname */ + case 296: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */ { - disableLookaside(pParse); - sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy203); + sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy203, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0); } break; - case 297: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */ + case 297: /* cmd ::= ALTER TABLE fullname DROP CONSTRAINT nm */ { - sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy203, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0); + sqlite3AlterDropConstraint(pParse, yymsp[-3].minor.yy203, &yymsp[0].minor.yy0, 0); +} + break; + case 298: /* cmd ::= ALTER TABLE fullname ALTER kwcolumn_opt nm DROP NOT NULL */ +{ + sqlite3AlterDropConstraint(pParse, yymsp[-6].minor.yy203, 0, &yymsp[-3].minor.yy0); } break; - case 298: /* cmd ::= create_vtab */ + case 299: /* cmd ::= ALTER TABLE fullname ALTER kwcolumn_opt nm SET NOT NULL onconf */ +{ + sqlite3AlterSetNotNull(pParse, yymsp[-7].minor.yy203, &yymsp[-4].minor.yy0, &yymsp[-2].minor.yy0); +} + break; + case 300: /* cmd ::= ALTER TABLE fullname ADD CONSTRAINT nm CHECK LP expr RP onconf */ +{ + sqlite3AlterAddConstraint(pParse, yymsp[-8].minor.yy203, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy0.z+1, (yymsp[-1].minor.yy0.z-yymsp[-3].minor.yy0.z-1), yymsp[-2].minor.yy454); +} + break; + case 301: /* cmd ::= ALTER TABLE fullname ADD CHECK LP expr RP onconf */ +{ + sqlite3AlterAddConstraint(pParse, yymsp[-6].minor.yy203, &yymsp[-4].minor.yy0, 0, yymsp[-3].minor.yy0.z+1, (yymsp[-1].minor.yy0.z-yymsp[-3].minor.yy0.z-1), yymsp[-2].minor.yy454); +} + break; + case 302: /* cmd ::= create_vtab */ {sqlite3VtabFinishParse(pParse,0);} break; - case 299: /* cmd ::= create_vtab LP vtabarglist RP */ + case 303: /* cmd ::= create_vtab LP vtabarglist RP */ {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);} break; - case 300: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ + case 304: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */ { sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy144); } break; - case 301: /* vtabarg ::= */ + case 305: /* vtabarg ::= */ {sqlite3VtabArgInit(pParse);} break; - case 302: /* vtabargtoken ::= ANY */ - case 303: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==303); - case 304: /* lp ::= LP */ yytestcase(yyruleno==304); + case 306: /* vtabargtoken ::= ANY */ + case 307: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==307); + case 308: /* lp ::= LP */ yytestcase(yyruleno==308); {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);} break; - case 305: /* with ::= WITH wqlist */ - case 306: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==306); + case 309: /* with ::= WITH wqlist */ + case 310: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==310); { sqlite3WithPush(pParse, yymsp[0].minor.yy59, 1); } break; - case 307: /* wqas ::= AS */ + case 311: /* wqas ::= AS */ {yymsp[0].minor.yy462 = M10d_Any;} break; - case 308: /* wqas ::= AS MATERIALIZED */ + case 312: /* wqas ::= AS MATERIALIZED */ {yymsp[-1].minor.yy462 = M10d_Yes;} break; - case 309: /* wqas ::= AS NOT MATERIALIZED */ + case 313: /* wqas ::= AS NOT MATERIALIZED */ {yymsp[-2].minor.yy462 = M10d_No;} break; - case 310: /* wqitem ::= withnm eidlist_opt wqas LP select RP */ + case 314: /* wqitem ::= withnm eidlist_opt wqas LP select RP */ { yymsp[-5].minor.yy67 = sqlite3CteNew(pParse, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy555, yymsp[-3].minor.yy462); /*A-overwrites-X*/ } break; - case 311: /* withnm ::= nm */ + case 315: /* withnm ::= nm */ {pParse->bHasWith = 1;} break; - case 312: /* wqlist ::= wqitem */ + case 316: /* wqlist ::= wqitem */ { yymsp[0].minor.yy59 = sqlite3WithAdd(pParse, 0, yymsp[0].minor.yy67); /*A-overwrites-X*/ } break; - case 313: /* wqlist ::= wqlist COMMA wqitem */ + case 317: /* wqlist ::= wqlist COMMA wqitem */ { yymsp[-2].minor.yy59 = sqlite3WithAdd(pParse, yymsp[-2].minor.yy59, yymsp[0].minor.yy67); } break; - case 314: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */ + case 318: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */ { assert( yymsp[0].minor.yy211!=0 ); sqlite3WindowChain(pParse, yymsp[0].minor.yy211, yymsp[-2].minor.yy211); @@ -178785,7 +185951,7 @@ static YYACTIONTYPE yy_reduce( } yymsp[-2].minor.yy211 = yylhsminor.yy211; break; - case 315: /* windowdefn ::= nm AS LP window RP */ + case 319: /* windowdefn ::= nm AS LP window RP */ { if( ALWAYS(yymsp[-1].minor.yy211) ){ yymsp[-1].minor.yy211->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n); @@ -178794,83 +185960,83 @@ static YYACTIONTYPE yy_reduce( } yymsp[-4].minor.yy211 = yylhsminor.yy211; break; - case 316: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */ + case 320: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */ { yymsp[-4].minor.yy211 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy211, yymsp[-2].minor.yy14, yymsp[-1].minor.yy14, 0); } break; - case 317: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */ + case 321: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */ { yylhsminor.yy211 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy211, yymsp[-2].minor.yy14, yymsp[-1].minor.yy14, &yymsp[-5].minor.yy0); } yymsp[-5].minor.yy211 = yylhsminor.yy211; break; - case 318: /* window ::= ORDER BY sortlist frame_opt */ + case 322: /* window ::= ORDER BY sortlist frame_opt */ { yymsp[-3].minor.yy211 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy211, 0, yymsp[-1].minor.yy14, 0); } break; - case 319: /* window ::= nm ORDER BY sortlist frame_opt */ + case 323: /* window ::= nm ORDER BY sortlist frame_opt */ { yylhsminor.yy211 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy211, 0, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0); } yymsp[-4].minor.yy211 = yylhsminor.yy211; break; - case 320: /* window ::= nm frame_opt */ + case 324: /* window ::= nm frame_opt */ { yylhsminor.yy211 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy211, 0, 0, &yymsp[-1].minor.yy0); } yymsp[-1].minor.yy211 = yylhsminor.yy211; break; - case 321: /* frame_opt ::= */ + case 325: /* frame_opt ::= */ { yymsp[1].minor.yy211 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0); } break; - case 322: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */ + case 326: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */ { yylhsminor.yy211 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy144, yymsp[-1].minor.yy509.eType, yymsp[-1].minor.yy509.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy462); } yymsp[-2].minor.yy211 = yylhsminor.yy211; break; - case 323: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */ + case 327: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */ { yylhsminor.yy211 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy144, yymsp[-3].minor.yy509.eType, yymsp[-3].minor.yy509.pExpr, yymsp[-1].minor.yy509.eType, yymsp[-1].minor.yy509.pExpr, yymsp[0].minor.yy462); } yymsp[-5].minor.yy211 = yylhsminor.yy211; break; - case 325: /* frame_bound_s ::= frame_bound */ - case 327: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==327); + case 329: /* frame_bound_s ::= frame_bound */ + case 331: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==331); {yylhsminor.yy509 = yymsp[0].minor.yy509;} yymsp[0].minor.yy509 = yylhsminor.yy509; break; - case 326: /* frame_bound_s ::= UNBOUNDED PRECEDING */ - case 328: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==328); - case 330: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==330); + case 330: /* frame_bound_s ::= UNBOUNDED PRECEDING */ + case 332: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==332); + case 334: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==334); {yylhsminor.yy509.eType = yymsp[-1].major; yylhsminor.yy509.pExpr = 0;} yymsp[-1].minor.yy509 = yylhsminor.yy509; break; - case 329: /* frame_bound ::= expr PRECEDING|FOLLOWING */ + case 333: /* frame_bound ::= expr PRECEDING|FOLLOWING */ {yylhsminor.yy509.eType = yymsp[0].major; yylhsminor.yy509.pExpr = yymsp[-1].minor.yy454;} yymsp[-1].minor.yy509 = yylhsminor.yy509; break; - case 331: /* frame_exclude_opt ::= */ + case 335: /* frame_exclude_opt ::= */ {yymsp[1].minor.yy462 = 0;} break; - case 332: /* frame_exclude_opt ::= EXCLUDE frame_exclude */ + case 336: /* frame_exclude_opt ::= EXCLUDE frame_exclude */ {yymsp[-1].minor.yy462 = yymsp[0].minor.yy462;} break; - case 333: /* frame_exclude ::= NO OTHERS */ - case 334: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==334); + case 337: /* frame_exclude ::= NO OTHERS */ + case 338: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==338); {yymsp[-1].minor.yy462 = yymsp[-1].major; /*A-overwrites-X*/} break; - case 335: /* frame_exclude ::= GROUP|TIES */ + case 339: /* frame_exclude ::= GROUP|TIES */ {yymsp[0].minor.yy462 = yymsp[0].major; /*A-overwrites-X*/} break; - case 336: /* window_clause ::= WINDOW windowdefn_list */ + case 340: /* window_clause ::= WINDOW windowdefn_list */ { yymsp[-1].minor.yy211 = yymsp[0].minor.yy211; } break; - case 337: /* filter_over ::= filter_clause over_clause */ + case 341: /* filter_over ::= filter_clause over_clause */ { if( yymsp[0].minor.yy211 ){ yymsp[0].minor.yy211->pFilter = yymsp[-1].minor.yy454; @@ -178881,13 +186047,13 @@ static YYACTIONTYPE yy_reduce( } yymsp[-1].minor.yy211 = yylhsminor.yy211; break; - case 338: /* filter_over ::= over_clause */ + case 342: /* filter_over ::= over_clause */ { yylhsminor.yy211 = yymsp[0].minor.yy211; } yymsp[0].minor.yy211 = yylhsminor.yy211; break; - case 339: /* filter_over ::= filter_clause */ + case 343: /* filter_over ::= filter_clause */ { yylhsminor.yy211 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window)); if( yylhsminor.yy211 ){ @@ -178899,13 +186065,13 @@ static YYACTIONTYPE yy_reduce( } yymsp[0].minor.yy211 = yylhsminor.yy211; break; - case 340: /* over_clause ::= OVER LP window RP */ + case 344: /* over_clause ::= OVER LP window RP */ { yymsp[-3].minor.yy211 = yymsp[-1].minor.yy211; assert( yymsp[-3].minor.yy211!=0 ); } break; - case 341: /* over_clause ::= OVER nm */ + case 345: /* over_clause ::= OVER nm */ { yymsp[-1].minor.yy211 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window)); if( yymsp[-1].minor.yy211 ){ @@ -178913,10 +186079,10 @@ static YYACTIONTYPE yy_reduce( } } break; - case 342: /* filter_clause ::= FILTER LP WHERE expr RP */ + case 346: /* filter_clause ::= FILTER LP WHERE expr RP */ { yymsp[-4].minor.yy454 = yymsp[-1].minor.yy454; } break; - case 343: /* term ::= QNUMBER */ + case 347: /* term ::= QNUMBER */ { yylhsminor.yy454=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); sqlite3DequoteNumber(pParse, yylhsminor.yy454); @@ -178924,71 +186090,70 @@ static YYACTIONTYPE yy_reduce( yymsp[0].minor.yy454 = yylhsminor.yy454; break; default: - /* (344) input ::= cmdlist */ yytestcase(yyruleno==344); - /* (345) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==345); - /* (346) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=346); - /* (347) ecmd ::= SEMI */ yytestcase(yyruleno==347); - /* (348) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==348); - /* (349) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=349); - /* (350) trans_opt ::= */ yytestcase(yyruleno==350); - /* (351) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==351); - /* (352) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==352); - /* (353) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==353); - /* (354) savepoint_opt ::= */ yytestcase(yyruleno==354); - /* (355) cmd ::= create_table create_table_args */ yytestcase(yyruleno==355); - /* (356) table_option_set ::= table_option (OPTIMIZED OUT) */ assert(yyruleno!=356); - /* (357) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==357); - /* (358) columnlist ::= columnname carglist */ yytestcase(yyruleno==358); - /* (359) nm ::= ID|INDEXED|JOIN_KW */ yytestcase(yyruleno==359); - /* (360) nm ::= STRING */ yytestcase(yyruleno==360); - /* (361) typetoken ::= typename */ yytestcase(yyruleno==361); - /* (362) typename ::= ID|STRING */ yytestcase(yyruleno==362); - /* (363) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=363); - /* (364) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=364); - /* (365) carglist ::= carglist ccons */ yytestcase(yyruleno==365); - /* (366) carglist ::= */ yytestcase(yyruleno==366); - /* (367) ccons ::= NULL onconf */ yytestcase(yyruleno==367); - /* (368) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==368); - /* (369) ccons ::= AS generated */ yytestcase(yyruleno==369); - /* (370) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==370); - /* (371) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==371); - /* (372) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=372); - /* (373) tconscomma ::= */ yytestcase(yyruleno==373); - /* (374) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=374); - /* (375) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=375); - /* (376) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=376); - /* (377) oneselect ::= values */ yytestcase(yyruleno==377); - /* (378) sclp ::= selcollist COMMA */ yytestcase(yyruleno==378); - /* (379) as ::= ID|STRING */ yytestcase(yyruleno==379); - /* (380) indexed_opt ::= indexed_by (OPTIMIZED OUT) */ assert(yyruleno!=380); - /* (381) returning ::= */ yytestcase(yyruleno==381); - /* (382) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=382); - /* (383) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==383); - /* (384) case_operand ::= expr */ yytestcase(yyruleno==384); - /* (385) exprlist ::= nexprlist */ yytestcase(yyruleno==385); - /* (386) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=386); - /* (387) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=387); - /* (388) nmnum ::= ON */ yytestcase(yyruleno==388); - /* (389) nmnum ::= DELETE */ yytestcase(yyruleno==389); - /* (390) nmnum ::= DEFAULT */ yytestcase(yyruleno==390); - /* (391) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==391); - /* (392) foreach_clause ::= */ yytestcase(yyruleno==392); - /* (393) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==393); - /* (394) trnm ::= nm */ yytestcase(yyruleno==394); - /* (395) tridxby ::= */ yytestcase(yyruleno==395); - /* (396) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==396); - /* (397) database_kw_opt ::= */ yytestcase(yyruleno==397); - /* (398) kwcolumn_opt ::= */ yytestcase(yyruleno==398); - /* (399) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==399); - /* (400) vtabarglist ::= vtabarg */ yytestcase(yyruleno==400); - /* (401) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==401); - /* (402) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==402); - /* (403) anylist ::= */ yytestcase(yyruleno==403); - /* (404) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==404); - /* (405) anylist ::= anylist ANY */ yytestcase(yyruleno==405); - /* (406) with ::= */ yytestcase(yyruleno==406); - /* (407) windowdefn_list ::= windowdefn (OPTIMIZED OUT) */ assert(yyruleno!=407); - /* (408) window ::= frame_opt (OPTIMIZED OUT) */ assert(yyruleno!=408); + /* (348) input ::= cmdlist */ yytestcase(yyruleno==348); + /* (349) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==349); + /* (350) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=350); + /* (351) ecmd ::= SEMI */ yytestcase(yyruleno==351); + /* (352) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==352); + /* (353) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=353); + /* (354) trans_opt ::= */ yytestcase(yyruleno==354); + /* (355) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==355); + /* (356) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==356); + /* (357) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==357); + /* (358) savepoint_opt ::= */ yytestcase(yyruleno==358); + /* (359) cmd ::= create_table create_table_args */ yytestcase(yyruleno==359); + /* (360) table_option_set ::= table_option (OPTIMIZED OUT) */ assert(yyruleno!=360); + /* (361) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==361); + /* (362) columnlist ::= columnname carglist */ yytestcase(yyruleno==362); + /* (363) nm ::= ID|INDEXED|JOIN_KW */ yytestcase(yyruleno==363); + /* (364) nm ::= STRING */ yytestcase(yyruleno==364); + /* (365) typetoken ::= typename */ yytestcase(yyruleno==365); + /* (366) typename ::= ID|STRING */ yytestcase(yyruleno==366); + /* (367) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=367); + /* (368) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=368); + /* (369) carglist ::= carglist ccons */ yytestcase(yyruleno==369); + /* (370) carglist ::= */ yytestcase(yyruleno==370); + /* (371) ccons ::= NULL onconf */ yytestcase(yyruleno==371); + /* (372) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==372); + /* (373) ccons ::= AS generated */ yytestcase(yyruleno==373); + /* (374) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==374); + /* (375) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==375); + /* (376) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=376); + /* (377) tconscomma ::= */ yytestcase(yyruleno==377); + /* (378) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=378); + /* (379) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=379); + /* (380) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=380); + /* (381) oneselect ::= values */ yytestcase(yyruleno==381); + /* (382) sclp ::= selcollist COMMA */ yytestcase(yyruleno==382); + /* (383) as ::= ID|STRING */ yytestcase(yyruleno==383); + /* (384) indexed_opt ::= indexed_by (OPTIMIZED OUT) */ assert(yyruleno!=384); + /* (385) returning ::= */ yytestcase(yyruleno==385); + /* (386) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=386); + /* (387) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==387); + /* (388) case_operand ::= expr */ yytestcase(yyruleno==388); + /* (389) exprlist ::= nexprlist */ yytestcase(yyruleno==389); + /* (390) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=390); + /* (391) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=391); + /* (392) nmnum ::= ON */ yytestcase(yyruleno==392); + /* (393) nmnum ::= DELETE */ yytestcase(yyruleno==393); + /* (394) nmnum ::= DEFAULT */ yytestcase(yyruleno==394); + /* (395) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==395); + /* (396) foreach_clause ::= */ yytestcase(yyruleno==396); + /* (397) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==397); + /* (398) tridxby ::= */ yytestcase(yyruleno==398); + /* (399) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==399); + /* (400) database_kw_opt ::= */ yytestcase(yyruleno==400); + /* (401) kwcolumn_opt ::= */ yytestcase(yyruleno==401); + /* (402) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==402); + /* (403) vtabarglist ::= vtabarg */ yytestcase(yyruleno==403); + /* (404) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==404); + /* (405) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==405); + /* (406) anylist ::= */ yytestcase(yyruleno==406); + /* (407) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==407); + /* (408) anylist ::= anylist ANY */ yytestcase(yyruleno==408); + /* (409) with ::= */ yytestcase(yyruleno==409); + /* (410) windowdefn_list ::= windowdefn (OPTIMIZED OUT) */ assert(yyruleno!=410); + /* (411) window ::= frame_opt (OPTIMIZED OUT) */ assert(yyruleno!=411); break; /********** End reduce actions ************************************************/ }; @@ -179051,7 +186216,7 @@ static void yy_syntax_error( UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */ if( TOKEN.z[0] ){ - sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); + parserSyntaxError(pParse, &TOKEN); }else{ sqlite3ErrorMsg(pParse, "incomplete input"); } @@ -179767,8 +186932,8 @@ static const unsigned char aKWCode[148] = {0, /* Check to see if z[0..n-1] is a keyword. If it is, write the ** parser symbol code for that keyword into *pType. Always ** return the integer n (the length of the token). */ -static int keywordCode(const char *z, int n, int *pType){ - int i, j; +static i64 keywordCode(const char *z, i64 n, int *pType){ + i64 i, j; const char *zKW; assert( n>=2 ); i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n*1) % 127; @@ -180013,7 +187178,7 @@ static int getToken(const unsigned char **pz){ int t; /* Token type to return */ do { z += sqlite3GetToken(z, &t); - }while( t==TK_SPACE ); + }while( t==TK_SPACE || t==TK_COMMENT ); if( t==TK_ID || t==TK_STRING || t==TK_JOIN_KW @@ -180084,8 +187249,9 @@ static int analyzeFilterKeyword(const unsigned char *z, int lastToken){ ** Return the length (in bytes) of the token that begins at z[0]. ** Store the token type in *tokenType before returning. */ -SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ - int i, c; +SQLITE_PRIVATE i64 sqlite3GetToken(const unsigned char *z, int *tokenType){ + i64 i; + int c; switch( aiClass[*z] ){ /* Switch on the character-class of the first byte ** of the token. See the comment on the CC_ defines ** above. */ @@ -180102,7 +187268,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ case CC_MINUS: { if( z[1]=='-' ){ for(i=2; (c=z[i])!=0 && c!='\n'; i++){} - *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ + *tokenType = TK_COMMENT; return i; }else if( z[1]=='>' ){ *tokenType = TK_PTR; @@ -180138,7 +187304,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ } for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){} if( c ) i++; - *tokenType = TK_SPACE; /* IMP: R-22934-25134 */ + *tokenType = TK_COMMENT; return i; } case CC_PERCENT: { @@ -180321,7 +187487,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ } case CC_DOLLAR: case CC_VARALPHA: { - int n = 0; + i64 n = 0; testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' ); testcase( z[0]=='#' ); *tokenType = TK_VARIABLE; @@ -180413,11 +187579,11 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql){ int nErr = 0; /* Number of errors encountered */ void *pEngine; /* The LEMON-generated LALR(1) parser */ - int n = 0; /* Length of the next token token */ + i64 n = 0; /* Length of the next token token */ int tokenType; /* type of the next token */ int lastTokenParsed = -1; /* type of the previous token */ sqlite3 *db = pParse->db; /* The database connection */ - int mxSqlLen; /* Max length of an SQL string */ + i64 mxSqlLen; /* Max length of an SQL string */ Parse *pParentParse = 0; /* Outer parse context, if any */ #ifdef sqlite3Parser_ENGINEALWAYSONSTACK yyParser sEngine; /* Space to hold the Lemon-generated Parser object */ @@ -180467,12 +187633,12 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql){ if( tokenType>=TK_WINDOW ){ assert( tokenType==TK_SPACE || tokenType==TK_OVER || tokenType==TK_FILTER || tokenType==TK_ILLEGAL || tokenType==TK_WINDOW - || tokenType==TK_QNUMBER + || tokenType==TK_QNUMBER || tokenType==TK_COMMENT ); #else if( tokenType>=TK_SPACE ){ assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL - || tokenType==TK_QNUMBER + || tokenType==TK_QNUMBER || tokenType==TK_COMMENT ); #endif /* SQLITE_OMIT_WINDOWFUNC */ if( AtomicLoad(&db->u1.isInterrupted) ){ @@ -180506,16 +187672,23 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql){ assert( n==6 ); tokenType = analyzeFilterKeyword((const u8*)&zSql[6], lastTokenParsed); #endif /* SQLITE_OMIT_WINDOWFUNC */ + }else if( tokenType==TK_COMMENT + && (db->init.busy || (db->flags & SQLITE_Comments)!=0) + ){ + /* Ignore SQL comments if either (1) we are reparsing the schema or + ** (2) SQLITE_DBCONFIG_ENABLE_COMMENTS is turned on (the default). */ + zSql += n; + continue; }else if( tokenType!=TK_QNUMBER ){ Token x; x.z = zSql; - x.n = n; + x.n = (u32)n; sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"", &x); break; } } pParse->sLastToken.z = zSql; - pParse->sLastToken.n = n; + pParse->sLastToken.n = (u32)n; sqlite3Parser(pEngine, tokenType, pParse->sLastToken); lastTokenParsed = tokenType; zSql += n; @@ -180540,9 +187713,11 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql){ } if( pParse->zErrMsg || (pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE) ){ if( pParse->zErrMsg==0 ){ - pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc)); + pParse->zErrMsg = sqlite3DbStrDup(db, sqlite3ErrStr(pParse->rc)); + } + if( (pParse->prepFlags & SQLITE_PREPARE_DONT_LOG)==0 ){ + sqlite3_log(pParse->rc, "%s in \"%s\"", pParse->zErrMsg, pParse->zTail); } - sqlite3_log(pParse->rc, "%s in \"%s\"", pParse->zErrMsg, pParse->zTail); nErr++; } pParse->zTail = zSql; @@ -180589,7 +187764,7 @@ SQLITE_PRIVATE char *sqlite3Normalize( ){ sqlite3 *db; /* The database connection */ int i; /* Next unread byte of zSql[] */ - int n; /* length of current token */ + i64 n; /* length of current token */ int tokenType; /* type of current token */ int prevType = 0; /* Previous non-whitespace token */ int nParen; /* Number of nested levels of parentheses */ @@ -180610,6 +187785,7 @@ SQLITE_PRIVATE char *sqlite3Normalize( n = sqlite3GetToken((unsigned char*)zSql+i, &tokenType); if( NEVER(n<=0) ) break; switch( tokenType ){ + case TK_COMMENT: case TK_SPACE: { break; } @@ -180618,7 +187794,7 @@ SQLITE_PRIVATE char *sqlite3Normalize( sqlite3_str_append(pStr, " NULL", 5); break; } - /* Fall through */ + /* no break */ deliberate_fall_through } case TK_STRING: case TK_INTEGER: @@ -180682,7 +187858,7 @@ SQLITE_PRIVATE char *sqlite3Normalize( } case TK_SELECT: { iStartIN = 0; - /* fall through */ + /* no break */ deliberate_fall_through } default: { if( sqlite3IsIdChar(zSql[i]) ) addSpaceSeparator(pStr); @@ -180754,15 +187930,55 @@ SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[]; #endif /* -** Return TRUE if the given SQL string ends in a semicolon. +** Return zero if the given SQL string is complete - if all comments, +** string and blob literals, and quoted identifiers have been closed and +** if the entire string ends with ";" and possibly with ";END;" if the +** string is a CREATE TRIGGER statement. A non-zero return indicates +** that the string is empty or incomplete. Bits of the return value +** indicate what is missing and is needed to close out the statement. ** ** Special handling is require for CREATE TRIGGER statements. ** Whenever the CREATE TRIGGER keywords are seen, the statement ** must end with ";END;". ** +** Let the return code be a value R. R is split up into various +** subfields, at byte boundaries: +** +** R = 0xwwwwwwww00xxyyzz +** +** In other words, zz is the least significant byte, yy is the next +** most significant byte, xx is the third byte, wwwwwwww is the upper +** four bytes of the return value. +** +** zz == SQLITE_OK Input is complete +** zz == SQLITE_ERROR Input is incomplete +** zz == SQLITE_EMPTY Input contains only whitespace +** zz == SQLITE_MISUSE Input is a NULL pointer +** zz != 0 New values for zz may be added in the future +** +** yy == 0x01 Need a semicolon at the end +** yy == 0x02 Need "END" and a semicolon +** yy == 0x03 Need semicolon, "END", and semicolon +** yy != 0 New values for yy may be added in the future +** +** xx == '\'' Incomplete string or blob literal +** xx == '"' Incomplete quoted identifier +** xx == '`' Incompelte MySQL-style quoted identifier +** xx == ']' Incomplete SQLServer-style quoted identifer +** xx == '-' Incomplete SQL-style comment +** xx == '/' Incomplete C-style comment +** xx != 0 New values of xx may be added in the future +** +** wwwwwwww Interpret as a signed integer, the number +** of unmatched "(". Negative means there are +** more ")" and "(". +** +** ((R>>24)&0xff)!=0 New uses for the 4th byte may be added +** in the future +** ** This implementation uses a state machine with 8 states: ** -** (0) INVALID We have not yet seen a non-whitespace character. +** (0) NOTHING We have not yet seen a non-whitespace character. ** ** (1) START At the beginning or end of an SQL statement. This routine ** returns 1 if it ends in the START state and 0 if it ends @@ -180806,9 +188022,11 @@ SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[]; ** to recognize the end of a trigger can be omitted. All we have to do ** is look for a semicolon that is not part of an string or comment. */ -SQLITE_API int sqlite3_complete(const char *zSql){ +SQLITE_API sqlite3_int64 sqlite3_incomplete(const char *zSql){ u8 state = 0; /* Current state, using numbers defined in header comment */ u8 token; /* Value of the next token */ + u8 pending = 0; /* unmatched structure character */ + int nParen = 0; /* Nested parentheses */ #ifndef SQLITE_OMIT_TRIGGER /* A complex statement machine used to detect the end of a CREATE TRIGGER @@ -180817,7 +188035,7 @@ SQLITE_API int sqlite3_complete(const char *zSql){ static const u8 trans[8][8] = { /* Token: */ /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */ - /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, }, + /* 0 NOTHING: */ { 1, 0, 2, 3, 4, 2, 2, 2, }, /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, }, /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, }, /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, }, @@ -180833,16 +188051,26 @@ SQLITE_API int sqlite3_complete(const char *zSql){ static const u8 trans[3][3] = { /* Token: */ /* State: ** SEMI WS OTHER */ - /* 0 INVALID: */ { 1, 0, 2, }, + /* 0 NOTHING: */ { 1, 0, 2, }, /* 1 START: */ { 1, 1, 2, }, /* 2 NORMAL: */ { 1, 2, 2, }, }; #endif /* SQLITE_OMIT_TRIGGER */ + /* Mapping state number to yy value for the return */ + static const u8 statemap[8] = { + /* 0 NOTHING */ 0, + /* 1 START */ 0, + /* 2 NORMAL */ 1, + /* 3 EXPLAIN */ 1, + /* 4 CREATE */ 1, + /* 5 TRIGGER */ 3, + /* 6 SEMI */ 2, + /* 7 END */ 1, + }; #ifdef SQLITE_ENABLE_API_ARMOR if( zSql==0 ){ - (void)SQLITE_MISUSE_BKPT; - return 0; + return SQLITE_MISUSE_BKPT; } #endif @@ -180867,7 +188095,10 @@ SQLITE_API int sqlite3_complete(const char *zSql){ } zSql += 2; while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; } - if( zSql[0]==0 ) return 0; + if( zSql[0]==0 ){ + pending = '/'; + goto incomplete_finish; + } zSql++; token = tkWS; break; @@ -180878,14 +188109,20 @@ SQLITE_API int sqlite3_complete(const char *zSql){ break; } while( *zSql && *zSql!='\n' ){ zSql++; } - if( *zSql==0 ) return state==1; + if( *zSql==0 ){ + pending = '-'; + goto incomplete_finish; + } token = tkWS; break; } case '[': { /* Microsoft-style identifiers in [...] */ zSql++; while( *zSql && *zSql!=']' ){ zSql++; } - if( *zSql==0 ) return 0; + if( *zSql==0 ){ + pending = ']'; + goto incomplete_finish; + } token = tkOTHER; break; } @@ -180895,7 +188132,20 @@ SQLITE_API int sqlite3_complete(const char *zSql){ int c = *zSql; zSql++; while( *zSql && *zSql!=c ){ zSql++; } - if( *zSql==0 ) return 0; + if( *zSql==0 ){ + pending = c; + goto incomplete_finish; + } + token = tkOTHER; + break; + } + case '(': { + nParen++; + token = tkOTHER; + break; + } + case ')': { + nParen--; token = tkOTHER; break; } @@ -180962,7 +188212,16 @@ SQLITE_API int sqlite3_complete(const char *zSql){ state = trans[state][token]; zSql++; } - return state==1; +incomplete_finish: + if( state==0 && pending==0 ) return SQLITE_EMPTY; + if( state==1 ) nParen = 0; + return (i64)((((u64)nParen)<<32) | + ((u64)pending<<16) | + ((u64)statemap[state]<<8) | + (state>1 || pending!=0)); +} +SQLITE_API int sqlite3_complete(const char *zSql){ + return sqlite3_incomplete(zSql)==0; } #ifndef SQLITE_OMIT_UTF16 @@ -180984,7 +188243,7 @@ SQLITE_API int sqlite3_complete16(const void *zSql){ sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); if( zSql8 ){ - rc = sqlite3_complete(zSql8); + rc = sqlite3_incomplete(zSql8)==0; }else{ rc = SQLITE_NOMEM_BKPT; } @@ -181166,9 +188425,6 @@ static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = { sqlite3DbstatRegister, #endif sqlite3TestExtInit, -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON) - sqlite3JsonTableFunctions, -#endif #ifdef SQLITE_ENABLE_STMTVTAB sqlite3StmtVtabInit, #endif @@ -181254,17 +188510,29 @@ SQLITE_API char *sqlite3_data_directory = 0; /* ** Initialize SQLite. ** -** This routine must be called to initialize the memory allocation, -** VFS, and mutex subsystems prior to doing any serious work with -** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT +** The sqlite3_initialize() routine must be called to initialize the +** memory allocation, VFS, and mutex subsystems prior to doing any +** serious work. As long as you do not compile with SQLITE_OMIT_AUTOINIT ** this routine will be called automatically by key routines such as ** sqlite3_open(). ** ** This routine is a no-op except on its very first call for the process, -** or for the first call after a call to sqlite3_shutdown. +** or for the first call after a call to sqlite3_shutdown. Most calls +** to sqlite3_initialize() are, in fact, no-ops. For that reason, the +** routine is broken into two pieces: +** +** sqlite3Initialize() Does the actual work of initialization ** -** The first thread to call this routine runs the initialization to -** completion. If subsequent threads call this routine before the first +** sqlite3_initialize() Checks to see if initialization is needed +** and invokes sqlite3Initialize() if it is. +** +** The sqlite3_initialize() interface is called frequently, but +** sqlite3Initialize() runs rarely. The function is broken up this way +** to avoid wasting CPU cycles with unnecessary stack setup for local +** variables in cases where it is not needed. +** +** The first thread to call sqlite3_initialize() runs the initialization to +** completion. If subsequent threads call sqlite3_initialize() before the first ** thread has finished the initialization process, then the subsequent ** threads must block until the first thread finishes with the initialization. ** @@ -181272,44 +188540,29 @@ SQLITE_API char *sqlite3_data_directory = 0; ** calls to this routine should not block, of course. Otherwise the ** initialization process would never complete. ** -** Let X be the first thread to enter this routine. Let Y be some other -** thread. Then while the initial invocation of this routine by X is -** incomplete, it is required that: +** Let X be the first thread to enter sqlite3_initialize(). Let Y be some +** other thread. While the initial invocation of sqlite3_initialize() by X +** is incomplete, it is required that: ** -** * Calls to this routine from Y must block until the outer-most +** * Calls to sqlite3_initialize() from Y must block until the outer-most ** call by X completes. ** -** * Recursive calls to this routine from thread X return immediately -** without blocking. +** * Recursive calls to sqlite3_initialize() from thread X return +** immediately without blocking. */ -SQLITE_API int sqlite3_initialize(void){ - MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */ - int rc; /* Result code */ +static SQLITE_NOINLINE int sqlite3Initialize(void){ + MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */ + int rc; /* Result code */ #ifdef SQLITE_EXTRA_INIT - int bRunExtraInit = 0; /* Extra initialization needed */ -#endif - -#ifdef SQLITE_OMIT_WSD - rc = sqlite3_wsd_init(4096, 24); - if( rc!=SQLITE_OK ){ - return rc; - } + int bRunExtraInit = 0; /* Extra initialization needed */ #endif /* If the following assert() fails on some obscure processor/compiler - ** combination, the work-around is to set the correct pointer - ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */ - assert( SQLITE_PTRSIZE==sizeof(char*) ); - - /* If SQLite is already completely initialized, then this call - ** to sqlite3_initialize() should be a no-op. But the initialization - ** must be complete. So isInit must not be set until the very end - ** of this routine. + ** combination to warn that SQLite has been mis-compiled. If you hit + ** this assert(), that means you need to recompile with the + ** -DSQLITE_PTRSIZE=n compile-time option to set the correct pointer size. */ - if( sqlite3GlobalConfig.isInit ){ - sqlite3MemoryBarrier(); - return SQLITE_OK; - } + assert( SQLITE_PTRSIZE==sizeof(char*) ); /* Make sure the mutex subsystem is initialized. If unable to ** initialize the mutex subsystem, return early with the error. @@ -181395,6 +188648,14 @@ SQLITE_API int sqlite3_initialize(void){ if( rc==SQLITE_OK ){ sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage); +#ifdef SQLITE_EXTRA_INIT_MUTEXED + { + int SQLITE_EXTRA_INIT_MUTEXED(const char*); + rc = SQLITE_EXTRA_INIT_MUTEXED(0); + } +#endif + } + if( rc==SQLITE_OK ){ sqlite3MemoryBarrier(); sqlite3GlobalConfig.isInit = 1; #ifdef SQLITE_EXTRA_INIT @@ -181447,6 +188708,26 @@ SQLITE_API int sqlite3_initialize(void){ #endif return rc; } +SQLITE_API int sqlite3_initialize(void){ + /* If this build does not support writable static data (WSD) natively + ** then we have to invoke the (application-supplied) WSD initialization + ** routine before doing anything else. */ +#ifdef SQLITE_OMIT_WSD + int rc = sqlite3_wsd_init(4096, 24); + if( rc!=SQLITE_OK ){ + return rc; + } +#endif + + if( sqlite3GlobalConfig.isInit ){ + /* SQLite has already been initialized. Fast early-out. */ + sqlite3MemoryBarrier(); + return SQLITE_OK; + }else{ + /* Invoke sqlite3Initialize() to do the actual work. */ + return sqlite3Initialize(); + } +} /* ** Undo the effects of sqlite3_initialize(). Must not be called while @@ -181605,7 +188886,7 @@ SQLITE_API int sqlite3_config(int op, ...){ break; } case SQLITE_CONFIG_SMALL_MALLOC: { - sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int); + sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int)!=0; break; } case SQLITE_CONFIG_PAGECACHE: { @@ -181851,17 +189132,22 @@ SQLITE_API int sqlite3_config(int op, ...){ ** If lookaside is already active, return SQLITE_BUSY. ** ** The sz parameter is the number of bytes in each lookaside slot. -** The cnt parameter is the number of slots. If pStart is NULL the -** space for the lookaside memory is obtained from sqlite3_malloc(). -** If pStart is not NULL then it is sz*cnt bytes of memory to use for -** the lookaside memory. +** The cnt parameter is the number of slots. If pBuf is NULL the +** space for the lookaside memory is obtained from sqlite3_malloc() +** or similar. If pBuf is not NULL then it is sz*cnt bytes of memory +** to use for the lookaside memory. */ -static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ +static int setupLookaside( + sqlite3 *db, /* Database connection being configured */ + void *pBuf, /* Memory to use for lookaside. May be NULL */ + int sz, /* Desired size of each lookaside memory slot */ + int cnt /* Number of slots to allocate */ +){ #ifndef SQLITE_OMIT_LOOKASIDE - void *pStart; - sqlite3_int64 szAlloc = sz*(sqlite3_int64)cnt; - int nBig; /* Number of full-size slots */ - int nSm; /* Number smaller LOOKASIDE_SMALL-byte slots */ + void *pStart; /* Start of the lookaside buffer */ + sqlite3_int64 szAlloc; /* Total space set aside for lookaside memory */ + int nBig; /* Number of full-size slots */ + int nSm; /* Number smaller LOOKASIDE_SMALL-byte slots */ if( sqlite3LookasideUsed(db,0)>0 ){ return SQLITE_BUSY; @@ -181874,17 +189160,22 @@ static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ sqlite3_free(db->lookaside.pStart); } /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger - ** than a pointer to be useful. + ** than a pointer and small enough to fit in a u16. */ - sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */ + sz = ROUNDDOWN8(sz); if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0; - if( cnt<0 ) cnt = 0; - if( sz==0 || cnt==0 ){ + if( sz>65528 ) sz = 65528; + /* Count must be at least 1 to be useful, but not so large as to use + ** more than 0x7fff0000 total bytes for lookaside. */ + if( cnt<1 ) cnt = 0; + if( sz>0 && cnt>(0x7fff0000/sz) ) cnt = 0x7fff0000/sz; + szAlloc = (i64)sz*(i64)cnt; + if( szAlloc==0 ){ sz = 0; pStart = 0; }else if( pBuf==0 ){ sqlite3BeginBenignMalloc(); - pStart = sqlite3Malloc( szAlloc ); /* IMP: R-61949-35727 */ + pStart = sqlite3Malloc( szAlloc ); sqlite3EndBenignMalloc(); if( pStart ) szAlloc = sqlite3MallocSize(pStart); }else{ @@ -181893,10 +189184,10 @@ static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE if( sz>=LOOKASIDE_SMALL*3 ){ nBig = szAlloc/(3*LOOKASIDE_SMALL+sz); - nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL; + nSm = (szAlloc - (i64)sz*(i64)nBig)/LOOKASIDE_SMALL; }else if( sz>=LOOKASIDE_SMALL*2 ){ nBig = szAlloc/(LOOKASIDE_SMALL+sz); - nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL; + nSm = (szAlloc - (i64)sz*(i64)nBig)/LOOKASIDE_SMALL; }else #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */ if( sz>0 ){ @@ -182048,10 +189339,18 @@ SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){ rc = setupLookaside(db, pBuf, sz, cnt); break; } + case SQLITE_DBCONFIG_FP_DIGITS: { + int nIn = va_arg(ap, int); + int *pOut = va_arg(ap, int*); + if( nIn>3 && nIn<24 ) db->nFpDigit = (u8)nIn; + if( pOut ) *pOut = db->nFpDigit; + rc = SQLITE_OK; + break; + } default: { static const struct { int op; /* The opcode */ - u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */ + u64 mask; /* Mask of the bit in sqlite3.flags to set/clear */ } aFlagOp[] = { { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys }, { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger }, @@ -182072,6 +189371,9 @@ SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){ { SQLITE_DBCONFIG_TRUSTED_SCHEMA, SQLITE_TrustedSchema }, { SQLITE_DBCONFIG_STMT_SCANSTATUS, SQLITE_StmtScanStatus }, { SQLITE_DBCONFIG_REVERSE_SCANORDER, SQLITE_ReverseOrder }, + { SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE, SQLITE_AttachCreate }, + { SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE, SQLITE_AttachWrite }, + { SQLITE_DBCONFIG_ENABLE_COMMENTS, SQLITE_Comments }, }; unsigned int i; rc = SQLITE_ERROR; /* IMP: R-42790-23372 */ @@ -182107,7 +189409,7 @@ SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){ ** This is the default collating function named "BINARY" which is always ** available. */ -static int binCollFunc( +SQLITE_PRIVATE int sqlite3BinaryCompare( void *NotUsed, int nKey1, const void *pKey1, int nKey2, const void *pKey2 @@ -182139,16 +189441,19 @@ static int rtrimCollFunc( const u8 *pK2 = (const u8*)pKey2; while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--; while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--; - return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2); + return sqlite3BinaryCompare(pUser, nKey1, pKey1, nKey2, pKey2); } /* ** Return true if CollSeq is the default built-in BINARY. */ +#if !SQLITE_USES_INLINE SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq *p){ - assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 ); - return p==0 || p->xCmp==binCollFunc; + assert( p==0 || p->xCmp!=sqlite3BinaryCompare + || strcmp(p->zName,"BINARY")==0 ); + return p==0 || p->xCmp==sqlite3BinaryCompare; } +#endif /* ** Another built-in collating sequence: NOCASE. @@ -182177,13 +189482,17 @@ static int nocaseCollatingFunc( ** Return the ROWID of the most recent insert */ SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){ + i64 iRet; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - return db->lastRowid; + sqlite3_mutex_enter(db->mutex); + iRet = db->lastRowid; + sqlite3_mutex_leave(db->mutex); + return iRet; } /* @@ -182202,16 +189511,21 @@ SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid) } /* -** Return the number of changes in the most recent call to sqlite3_exec(). +** Return the number of changes in the most recently executed DML +** statement. */ SQLITE_API sqlite3_int64 sqlite3_changes64(sqlite3 *db){ + i64 iRet; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - return db->nChange; + sqlite3_mutex_enter(db->mutex); + iRet = db->nChange; + sqlite3_mutex_leave(db->mutex); + return iRet; } SQLITE_API int sqlite3_changes(sqlite3 *db){ return (int)sqlite3_changes64(db); @@ -182221,13 +189535,17 @@ SQLITE_API int sqlite3_changes(sqlite3 *db){ ** Return the number of changes since the database handle was opened. */ SQLITE_API sqlite3_int64 sqlite3_total_changes64(sqlite3 *db){ + i64 iRet; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - return db->nTotalChange; + sqlite3_mutex_enter(db->mutex); + iRet = db->nTotalChange; + sqlite3_mutex_leave(db->mutex); + return iRet; } SQLITE_API int sqlite3_total_changes(sqlite3 *db){ return (int)sqlite3_total_changes64(db); @@ -182468,6 +189786,7 @@ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ /* Clear the TEMP schema separately and last */ if( db->aDb[1].pSchema ){ sqlite3SchemaClear(db->aDb[1].pSchema); + assert( db->aDb[1].pSchema->trigHash.count==0 ); } sqlite3VtabUnlockList(db); @@ -182515,10 +189834,6 @@ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){ sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */ sqlite3ValueFree(db->pErr); sqlite3CloseExtensions(db); -#if SQLITE_USER_AUTHENTICATION - sqlite3_free(db->auth.zAuthUser); - sqlite3_free(db->auth.zAuthPW); -#endif db->eOpenState = SQLITE_STATE_ERROR; @@ -182607,6 +189922,9 @@ SQLITE_PRIVATE const char *sqlite3ErrName(int rc){ case SQLITE_OK: zName = "SQLITE_OK"; break; case SQLITE_ERROR: zName = "SQLITE_ERROR"; break; case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break; + case SQLITE_ERROR_RETRY: zName = "SQLITE_ERROR_RETRY"; break; + case SQLITE_ERROR_MISSING_COLLSEQ: + zName = "SQLITE_ERROR_MISSING_COLLSEQ"; break; case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break; case SQLITE_PERM: zName = "SQLITE_PERM"; break; case SQLITE_ABORT: zName = "SQLITE_ABORT"; break; @@ -182862,6 +190180,9 @@ SQLITE_API int sqlite3_busy_handler( db->busyHandler.pBusyArg = pArg; db->busyHandler.nBusy = 0; db->busyTimeout = 0; +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + db->setlkTimeout = 0; +#endif sqlite3_mutex_leave(db->mutex); return SQLITE_OK; } @@ -182907,13 +190228,52 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; #endif + sqlite3_mutex_enter(db->mutex); if( ms>0 ){ sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback, (void*)db); db->busyTimeout = ms; +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + db->setlkTimeout = ms; +#endif }else{ sqlite3_busy_handler(db, 0, 0); } + sqlite3_mutex_leave(db->mutex); + return SQLITE_OK; +} + +/* +** Set the setlk timeout value. +*/ +SQLITE_API int sqlite3_setlk_timeout(sqlite3 *db, int ms, int flags){ +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + int iDb; + int bBOC = ((flags & SQLITE_SETLK_BLOCK_ON_CONNECT) ? 1 : 0); +#endif +#ifdef SQLITE_ENABLE_API_ARMOR + if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; +#endif + if( ms<-1 ) return SQLITE_RANGE; +#ifdef SQLITE_ENABLE_SETLK_TIMEOUT + sqlite3_mutex_enter(db->mutex); + db->setlkTimeout = ms; + db->setlkFlags = flags; + sqlite3BtreeEnterAll(db); + for(iDb=0; iDb<db->nDb; iDb++){ + Btree *pBt = db->aDb[iDb].pBt; + if( pBt ){ + sqlite3_file *fd = sqlite3PagerFile(sqlite3BtreePager(pBt)); + sqlite3OsFileControlHint(fd, SQLITE_FCNTL_BLOCK_ON_CONNECT, (void*)&bBOC); + } + } + sqlite3BtreeLeaveAll(db); + sqlite3_mutex_leave(db->mutex); +#endif +#if !defined(SQLITE_ENABLE_API_ARMOR) && !defined(SQLITE_ENABLE_SETLK_TIMEOUT) + UNUSED_PARAMETER(db); + UNUSED_PARAMETER(flags); +#endif return SQLITE_OK; } @@ -183045,7 +190405,7 @@ SQLITE_PRIVATE int sqlite3CreateFunc( if( db->nVdbeActive ){ sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to delete/modify user-function due to active statements"); - assert( !db->mallocFailed ); + assert( !db->mallocFailed || db->nVdbeExec>0 ); return SQLITE_BUSY; }else{ sqlite3ExpirePreparedStatements(db, 0); @@ -183560,6 +190920,9 @@ SQLITE_API void *sqlite3_wal_hook( sqlite3_mutex_leave(db->mutex); return pRet; #else + UNUSED_PARAMETER(db); + UNUSED_PARAMETER(xCallback); + UNUSED_PARAMETER(pArg); return 0; #endif } @@ -183575,6 +190938,11 @@ SQLITE_API int sqlite3_wal_checkpoint_v2( int *pnCkpt /* OUT: Total number of frames checkpointed */ ){ #ifdef SQLITE_OMIT_WAL + UNUSED_PARAMETER(db); + UNUSED_PARAMETER(zDb); + UNUSED_PARAMETER(eMode); + UNUSED_PARAMETER(pnLog); + UNUSED_PARAMETER(pnCkpt); return SQLITE_OK; #else int rc; /* Return code */ @@ -183588,11 +190956,12 @@ SQLITE_API int sqlite3_wal_checkpoint_v2( if( pnLog ) *pnLog = -1; if( pnCkpt ) *pnCkpt = -1; + assert( SQLITE_CHECKPOINT_NOOP==-1 ); assert( SQLITE_CHECKPOINT_PASSIVE==0 ); assert( SQLITE_CHECKPOINT_FULL==1 ); assert( SQLITE_CHECKPOINT_RESTART==2 ); assert( SQLITE_CHECKPOINT_TRUNCATE==3 ); - if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){ + if( eMode<SQLITE_CHECKPOINT_NOOP || eMode>SQLITE_CHECKPOINT_TRUNCATE ){ /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint ** mode: */ return SQLITE_MISUSE_BKPT; @@ -183748,14 +191117,39 @@ SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){ return z; } +/* +** Set the error code and error message associated with the database handle. +** +** This routine is intended to be called by outside extensions (ex: the +** Session extension). Internal logic should invoke sqlite3Error() or +** sqlite3ErrorWithMsg() directly. +*/ +SQLITE_API int sqlite3_set_errmsg(sqlite3 *db, int errcode, const char *zMsg){ + int rc = SQLITE_OK; + if( !sqlite3SafetyCheckOk(db) ){ + return SQLITE_MISUSE_BKPT; + } + sqlite3_mutex_enter(db->mutex); + if( zMsg ){ + sqlite3ErrorWithMsg(db, errcode, "%s", zMsg); + }else{ + sqlite3Error(db, errcode); + } + rc = sqlite3ApiExit(db, rc); + sqlite3_mutex_leave(db->mutex); + return rc; +} + /* ** Return the byte offset of the most recent error */ SQLITE_API int sqlite3_error_offset(sqlite3 *db){ int iOffset = -1; - if( db && sqlite3SafetyCheckSickOrOk(db) && db->errCode ){ + if( db && sqlite3SafetyCheckSickOrOk(db) ){ sqlite3_mutex_enter(db->mutex); - iOffset = db->errByteOffset; + if( db->errCode ){ + iOffset = db->errByteOffset; + } sqlite3_mutex_leave(db->mutex); } return iOffset; @@ -183809,25 +191203,43 @@ SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){ ** passed to this function, we assume a malloc() failed during sqlite3_open(). */ SQLITE_API int sqlite3_errcode(sqlite3 *db){ - if( db && !sqlite3SafetyCheckSickOrOk(db) ){ + int iRet; + if( !db ) return SQLITE_NOMEM_BKPT; + if( !sqlite3SafetyCheckSickOrOk(db) ){ return SQLITE_MISUSE_BKPT; } - if( !db || db->mallocFailed ){ - return SQLITE_NOMEM_BKPT; + sqlite3_mutex_enter(db->mutex); + if( db->mallocFailed ){ + iRet = SQLITE_NOMEM_BKPT; + }else{ + iRet = db->errCode & db->errMask; } - return db->errCode & db->errMask; + sqlite3_mutex_leave(db->mutex); + return iRet; } SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){ - if( db && !sqlite3SafetyCheckSickOrOk(db) ){ + int iRet; + if( !db ) return SQLITE_NOMEM_BKPT; + if( !sqlite3SafetyCheckSickOrOk(db) ){ return SQLITE_MISUSE_BKPT; } - if( !db || db->mallocFailed ){ - return SQLITE_NOMEM_BKPT; + sqlite3_mutex_enter(db->mutex); + if( db->mallocFailed ){ + iRet = SQLITE_NOMEM_BKPT; + }else{ + iRet = db->errCode; } - return db->errCode; + sqlite3_mutex_leave(db->mutex); + return iRet; } SQLITE_API int sqlite3_system_errno(sqlite3 *db){ - return db ? db->iSysErrno : 0; + int iRet = 0; + if( db ){ + sqlite3_mutex_enter(db->mutex); + iRet = db->iSysErrno; + sqlite3_mutex_leave(db->mutex); + } + return iRet; } /* @@ -183933,6 +191345,9 @@ static const int aHardLimit[] = { SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */ SQLITE_MAX_TRIGGER_DEPTH, SQLITE_MAX_WORKER_THREADS, + SQLITE_MAX_PARSER_DEPTH, + SQLITE_MAX_SCHEMA, + SQLITE_MAX_TRIGGER_STEPS, }; /* @@ -183947,14 +191362,17 @@ static const int aHardLimit[] = { #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH #endif +#if SQLITE_MAX_SQL_LENGTH>2147482624 /* 1024 less than 2^31 */ +# error SQLITE_MAX_SQL_LENGTH must not be greater than 2147482624 +#endif #if SQLITE_MAX_COMPOUND_SELECT<2 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2 #endif #if SQLITE_MAX_VDBE_OP<40 # error SQLITE_MAX_VDBE_OP must be at least 40 #endif -#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127 -# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127 +#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>32767 +# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 32767 #endif #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125 # error SQLITE_MAX_ATTACHED must be between 0 and 125 @@ -183971,6 +191389,9 @@ static const int aHardLimit[] = { #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50 #endif +#if SQLITE_MAX_TRIGGER_STEPS<0 || SQLITE_MAX_TRIGGER_STEPS>65535 +# error SQLITE_MAX_TRIGGER_STEPS must be between 0 and 65535 +#endif /* @@ -184002,6 +191423,7 @@ SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH ); assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN ); assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH ); + assert( aHardLimit[SQLITE_LIMIT_PARSER_DEPTH]==SQLITE_MAX_PARSER_DEPTH ); assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT); assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP ); assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG ); @@ -184011,21 +191433,25 @@ SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER); assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH ); assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS ); - assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) ); + assert( aHardLimit[SQLITE_LIMIT_SCHEMA]==SQLITE_MAX_SCHEMA ); + assert( aHardLimit[SQLITE_LIMIT_TRIGGER_STEPS]==SQLITE_MAX_TRIGGER_STEPS ); + assert( SQLITE_LIMIT_TRIGGER_STEPS==(SQLITE_N_LIMIT-1) ); if( limitId<0 || limitId>=SQLITE_N_LIMIT ){ return -1; } + sqlite3_mutex_enter(db->mutex); oldLimit = db->aLimit[limitId]; if( newLimit>=0 ){ /* IMP: R-52476-28732 */ if( newLimit>aHardLimit[limitId] ){ newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */ - }else if( newLimit<1 && limitId==SQLITE_LIMIT_LENGTH ){ - newLimit = 1; + }else if( newLimit<SQLITE_MIN_LENGTH && limitId==SQLITE_LIMIT_LENGTH ){ + newLimit = SQLITE_MIN_LENGTH; } db->aLimit[limitId] = newLimit; } + sqlite3_mutex_leave(db->mutex); return oldLimit; /* IMP: R-53341-35419 */ } @@ -184068,7 +191494,7 @@ SQLITE_PRIVATE int sqlite3ParseUri( const char *zVfs = zDefaultVfs; char *zFile; char c; - int nUri = sqlite3Strlen30(zUri); + i64 nUri = strlen(zUri); assert( *pzErrMsg==0 ); @@ -184078,8 +191504,8 @@ SQLITE_PRIVATE int sqlite3ParseUri( ){ char *zOpt; int eState; /* Parser state when parsing URI */ - int iIn; /* Input character index */ - int iOut = 0; /* Output character index */ + i64 iIn; /* Input character index */ + i64 iOut = 0; /* Output character index */ u64 nByte = nUri+8; /* Bytes of space to allocate */ /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen @@ -184113,7 +191539,7 @@ SQLITE_PRIVATE int sqlite3ParseUri( while( zUri[iIn] && zUri[iIn]!='/' ) iIn++; if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){ *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", - iIn-7, &zUri[7]); + (int)(iIn-7), &zUri[7]); rc = SQLITE_ERROR; goto parse_uri_out; } @@ -184188,11 +191614,11 @@ SQLITE_PRIVATE int sqlite3ParseUri( ** here. Options that are interpreted here include "vfs" and those that ** correspond to flags that may be passed to the sqlite3_open_v2() ** method. */ - zOpt = &zFile[sqlite3Strlen30(zFile)+1]; + zOpt = &zFile[strlen(zFile)+1]; while( zOpt[0] ){ - int nOpt = sqlite3Strlen30(zOpt); + i64 nOpt = strlen(zOpt); char *zVal = &zOpt[nOpt+1]; - int nVal = sqlite3Strlen30(zVal); + i64 nVal = strlen(zVal); if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){ zVfs = zVal; @@ -184238,7 +191664,7 @@ SQLITE_PRIVATE int sqlite3ParseUri( int mode = 0; for(i=0; aMode[i].z; i++){ const char *z = aMode[i].z; - if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){ + if( nVal==(i64)strlen(z) && 0==memcmp(zVal, z, nVal) ){ mode = aMode[i].mode; break; } @@ -184375,7 +191801,7 @@ static int openDatabase( db = sqlite3MallocZero( sizeof(sqlite3) ); if( db==0 ) goto opendb_out; if( isThreadsafe -#ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS +#if defined(SQLITE_THREAD_MISUSE_WARNINGS) || sqlite3GlobalConfig.bCoreMutex #endif ){ @@ -184396,6 +191822,7 @@ static int openDatabase( db->aDb = db->aDbStatic; db->lookaside.bDisable = 1; db->lookaside.sz = 0; + db->nFpDigit = 17; assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); @@ -184417,6 +191844,9 @@ static int openDatabase( | SQLITE_EnableTrigger | SQLITE_EnableView | SQLITE_CacheSpill + | SQLITE_AttachCreate + | SQLITE_AttachWrite + | SQLITE_Comments #if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0 | SQLITE_TrustedSchema #endif @@ -184497,9 +191927,12 @@ static int openDatabase( ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating ** functions: */ - createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0); - createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0); - createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0); + createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, + sqlite3BinaryCompare, 0); + createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, + sqlite3BinaryCompare, 0); + createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, + sqlite3BinaryCompare, 0); createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0); if( db->mallocFailed ){ @@ -184838,6 +192271,12 @@ SQLITE_API int sqlite3_collation_needed16( */ SQLITE_API void *sqlite3_get_clientdata(sqlite3 *db, const char *zName){ DbClientData *p; +#ifdef SQLITE_ENABLE_API_ARMOR + if( !zName || !sqlite3SafetyCheckOk(db) ){ + (void)SQLITE_MISUSE_BKPT; + return 0; + } +#endif sqlite3_mutex_enter(db->mutex); for(p=db->pDbData; p; p=p->pNext){ if( strcmp(p->zName, zName)==0 ){ @@ -184879,7 +192318,7 @@ SQLITE_API int sqlite3_set_clientdata( return SQLITE_OK; }else{ size_t n = strlen(zName); - p = sqlite3_malloc64( sizeof(DbClientData)+n+1 ); + p = sqlite3_malloc64( SZ_DBCLIENTDATA(n+1) ); if( p==0 ){ if( xDestructor ) xDestructor(pData); sqlite3_mutex_leave(db->mutex); @@ -184913,13 +192352,17 @@ SQLITE_API int sqlite3_global_recover(void){ ** by the next COMMIT or ROLLBACK. */ SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){ + int iRet; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - return db->autoCommit; + sqlite3_mutex_enter(db->mutex); + iRet = db->autoCommit; + sqlite3_mutex_leave(db->mutex); + return iRet; } /* @@ -185033,13 +192476,10 @@ SQLITE_API int sqlite3_table_column_metadata( if( zColumnName==0 ){ /* Query for existence of table only */ }else{ - for(iCol=0; iCol<pTab->nCol; iCol++){ + iCol = sqlite3ColumnIndex(pTab, zColumnName); + if( iCol>=0 ){ pCol = &pTab->aCol[iCol]; - if( 0==sqlite3StrICmp(pCol->zCnName, zColumnName) ){ - break; - } - } - if( iCol==pTab->nCol ){ + }else{ if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){ iCol = pTab->iPKey; pCol = iCol>=0 ? &pTab->aCol[iCol] : 0; @@ -185248,8 +192688,8 @@ SQLITE_API int sqlite3_test_control(int op, ...){ /* sqlite3_test_control(SQLITE_TESTCTRL_FK_NO_ACTION, sqlite3 *db, int b); ** ** If b is true, then activate the SQLITE_FkNoAction setting. If b is - ** false then clearn that setting. If the SQLITE_FkNoAction setting is - ** abled, all foreign key ON DELETE and ON UPDATE actions behave as if + ** false then clear that setting. If the SQLITE_FkNoAction setting is + ** enabled, all foreign key ON DELETE and ON UPDATE actions behave as if ** they were NO ACTION, regardless of how they are defined. ** ** NB: One must usually run "PRAGMA writable_schema=RESET" after @@ -185366,7 +192806,6 @@ SQLITE_API int sqlite3_test_control(int op, ...){ /* Invoke these debugging routines so that the compiler does not ** issue "defined but not used" warnings. */ if( x==9999 ){ - sqlite3ShowExpr(0); sqlite3ShowExpr(0); sqlite3ShowExprList(0); sqlite3ShowIdList(0); @@ -185573,13 +193012,15 @@ SQLITE_API int sqlite3_test_control(int op, ...){ break; } - /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum); + /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, mode, tnum); ** ** This test control is used to create imposter tables. "db" is a pointer ** to the database connection. dbName is the database name (ex: "main" or - ** "temp") which will receive the imposter. "onOff" turns imposter mode on - ** or off. "tnum" is the root page of the b-tree to which the imposter - ** table should connect. + ** "temp") which will receive the imposter. "mode" turns imposter mode on + ** or off. mode==0 means imposter mode is off. mode==1 means imposter mode + ** is on. mode==2 means imposter mode is on but results in an imposter + ** table that is read-only unless writable_schema is on. "tnum" is the + ** root page of the b-tree to which the imposter table should connect. ** ** Enable imposter mode only when the schema has already been parsed. Then ** run a single CREATE TABLE statement to construct the imposter table in @@ -185697,6 +193138,17 @@ SQLITE_API int sqlite3_test_control(int op, ...){ break; } + /* sqlite3_test_control(SQLITE_TESTCTRL_ATOF, const char *z, double *p); + ** + ** Test access to the sqlite3AtoF() routine. + */ + case SQLITE_TESTCTRL_ATOF: { + const char *z = va_arg(ap,const char*); + double *pR = va_arg(ap,double*); + rc = sqlite3AtoF(z,pR); + break; + } + #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_WSD) /* sqlite3_test_control(SQLITE_TESTCTRL_TUNE, id, *piValue) ** @@ -185913,6 +193365,7 @@ SQLITE_API const char *sqlite3_filename_journal(const char *zFilename){ } SQLITE_API const char *sqlite3_filename_wal(const char *zFilename){ #ifdef SQLITE_OMIT_WAL + UNUSED_PARAMETER(zFilename); return 0; #else zFilename = sqlite3_filename_journal(zFilename); @@ -185934,17 +193387,19 @@ SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){ ** of range. */ SQLITE_API const char *sqlite3_db_name(sqlite3 *db, int N){ + const char *zRet = 0; #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) ){ (void)SQLITE_MISUSE_BKPT; return 0; } #endif - if( N<0 || N>=db->nDb ){ - return 0; - }else{ - return db->aDb[N].zDbSName; + sqlite3_mutex_enter(db->mutex); + if( N>=0 && N<db->nDb ){ + zRet = db->aDb[N].zDbSName; } + sqlite3_mutex_leave(db->mutex); + return zRet; } /* @@ -186597,7 +194052,7 @@ SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){ ** Here, array { X } means zero or more occurrences of X, adjacent in ** memory. A "position" is an index of a token in the token stream ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur -** in the same logical place as the position element, and act as sentinals +** in the same logical place as the position element, and act as sentinels ** ending a position list array. POS_END is 0. POS_COLUMN is 1. ** The positions numbers are not stored literally but rather as two more ** than the difference from the prior position, or the just the position plus @@ -186816,10 +194271,20 @@ SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){ #ifndef _FTSINT_H #define _FTSINT_H +/* +** Activate assert() only if SQLITE_TEST is enabled. +*/ #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) # define NDEBUG 1 #endif +/* #include <assert.h> */ +/* #include <stdlib.h> */ +/* #include <stddef.h> */ +/* #include <stdio.h> */ +/* #include <string.h> */ +/* #include <stdarg.h> */ + /* FTS3/FTS4 require virtual tables */ #ifdef SQLITE_OMIT_VIRTUALTABLE # undef SQLITE_ENABLE_FTS3 @@ -187262,13 +194727,6 @@ typedef sqlite3_int64 i64; /* 8-byte signed integer */ */ #define UNUSED_PARAMETER(x) (void)(x) -/* -** Activate assert() only if SQLITE_TEST is enabled. -*/ -#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) -# define NDEBUG 1 -#endif - /* ** The TESTONLY macro is used to enclose variable declarations or ** other bits of code that are needed to support the arguments @@ -187283,7 +194741,29 @@ typedef sqlite3_int64 i64; /* 8-byte signed integer */ #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) -#define deliberate_fall_through +#if !defined(deliberate_fall_through) +# if defined(__has_attribute) +# if __has_attribute(fallthrough) +# define deliberate_fall_through __attribute__((fallthrough)); +# endif +# endif +#endif +#if !defined(deliberate_fall_through) +# define deliberate_fall_through +#endif + +/* +** Macros needed to provide flexible arrays in a portable way +*/ +#ifndef offsetof +# define offsetof(ST,M) ((size_t)((char*)&((ST*)0)->M - (char*)0)) +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) +# define FLEXARRAY +#else +# define FLEXARRAY 1 +#endif + #endif /* SQLITE_AMALGAMATION */ @@ -187389,7 +194869,7 @@ struct Fts3Table { #endif #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - /* True to disable the incremental doclist optimization. This is controled + /* True to disable the incremental doclist optimization. This is controlled ** by special insert command 'test-no-incr-doclist'. */ int bNoIncrDoclist; @@ -187441,7 +194921,7 @@ struct Fts3Cursor { /* ** The Fts3Cursor.eSearch member is always set to one of the following. -** Actualy, Fts3Cursor.eSearch can be greater than or equal to +** Actually, Fts3Cursor.eSearch can be greater than or equal to ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index ** of the column to be searched. For example, in ** @@ -187514,9 +194994,13 @@ struct Fts3Phrase { */ int nToken; /* Number of tokens in the phrase */ int iColumn; /* Index of column this phrase must match */ - Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */ + Fts3PhraseToken aToken[FLEXARRAY]; /* One for each token in the phrase */ }; +/* Size (in bytes) of an Fts3Phrase object large enough to hold N tokens */ +#define SZ_FTS3PHRASE(N) \ + (offsetof(Fts3Phrase,aToken)+(N)*sizeof(Fts3PhraseToken)) + /* ** A tree of these objects forms the RHS of a MATCH operator. ** @@ -187664,6 +195148,15 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int); (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \ ) +SQLITE_PRIVATE int sqlite3Fts3PrepareStmt( + Fts3Table *p, /* Prepare for this connection */ + const char *zSql, /* SQL to prepare */ + int bPersist, /* True to set SQLITE_PREPARE_PERSISTENT */ + int bAllowVtab, /* True to omit SQLITE_PREPARE_NO_VTAB */ + sqlite3_stmt **pp /* OUT: Prepared statement */ +); + + /* fts3.c */ SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...); SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64); @@ -187723,6 +195216,7 @@ SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext( SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *); SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr); +SQLITE_PRIVATE int sqlite3Fts3MsrCancel(Fts3Cursor*, Fts3Expr*); /* fts3_tokenize_vtab.c */ SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *, void(*xDestroy)(void*)); @@ -187749,12 +195243,6 @@ SQLITE_PRIVATE int sqlite3Fts3IntegrityCheck(Fts3Table *p, int *pbOk); # define SQLITE_CORE 1 #endif -/* #include <assert.h> */ -/* #include <stdlib.h> */ -/* #include <stddef.h> */ -/* #include <stdio.h> */ -/* #include <string.h> */ -/* #include <stdarg.h> */ /* #include "fts3.h" */ #ifndef SQLITE_CORE @@ -187762,6 +195250,12 @@ SQLITE_PRIVATE int sqlite3Fts3IntegrityCheck(Fts3Table *p, int *pbOk); SQLITE_EXTENSION_INIT1 #endif + +/* +** Assume any b-tree layer with more levels than this is corrupt. +*/ +#define FTS3_MAX_BTREE_HEIGHT 48 + typedef struct Fts3HashWrapper Fts3HashWrapper; struct Fts3HashWrapper { Fts3Hash hash; /* Hash table */ @@ -188584,7 +196078,10 @@ static int fts3ContentColumns( ** nul-terminator byte. */ nCol = sqlite3_column_count(pStmt); for(i=0; i<nCol; i++){ + /* This call to sqlite3_column_name() cannot fail, as no conversion + ** between encodings, and therefore no malloc() call, is required. */ const char *zCol = sqlite3_column_name(pStmt, i); + assert( zCol ); nStr += strlen(zCol) + 1; } @@ -188597,6 +196094,7 @@ static int fts3ContentColumns( for(i=0; i<nCol; i++){ const char *zCol = sqlite3_column_name(pStmt, i); int n = (int)strlen(zCol)+1; + assert( zCol ); /* no malloc() required, cannot fail */ memcpy(p, zCol, n); azCol[i] = p; p += n; @@ -189276,9 +196774,7 @@ static int fts3CursorSeekStmt(Fts3Cursor *pCsr){ zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist); if( !zSql ) return SQLITE_NOMEM; p->bLock++; - rc = sqlite3_prepare_v3( - p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0 - ); + rc = sqlite3Fts3PrepareStmt(p, zSql, 1, 1, &pCsr->pStmt); p->bLock--; sqlite3_free(zSql); } @@ -189480,7 +196976,11 @@ static int fts3SelectLeaf( assert( piLeaf || piLeaf2 ); fts3GetVarint32(zNode, &iHeight); - rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2); + if( iHeight>FTS3_MAX_BTREE_HEIGHT ){ + rc = FTS_CORRUPT_VTAB; + }else{ + rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2); + } assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) ); if( rc==SQLITE_OK && iHeight>1 ){ @@ -189525,8 +197025,13 @@ static void fts3PutDeltaVarint( sqlite3_int64 iVal /* Write this value to the list */ ){ assert_fts3_nc( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) ); - *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev); - *piPrev = iVal; + if( iVal-(*piPrev)>=0 ){ + /* Refuse to write a negative delta integer. This only happens with a + ** corrupt db (see the assert above) and can cause buffer overwrites + ** in some cases. */ + *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev); + *piPrev = iVal; + } } /* @@ -189798,10 +197303,15 @@ static int fts3PoslistPhraseMerge( if( *p1==POS_COLUMN ){ p1++; p1 += fts3GetVarint32(p1, &iCol1); + /* iCol1==0 indicates corruption. Column 0 does not have a POS_COLUMN + ** entry, so this is actually end-of-doclist. */ + if( iCol1==0 ) return 0; } if( *p2==POS_COLUMN ){ p2++; p2 += fts3GetVarint32(p2, &iCol2); + /* As above, iCol2==0 indicates corruption. */ + if( iCol2==0 ) return 0; } while( 1 ){ @@ -190088,7 +197598,7 @@ static int fts3DoclistOrMerge( ** sizes of the two inputs, plus enough space for exactly one of the input ** docids to grow. ** - ** A symetric argument may be made if the doclists are in descending + ** A symmetric argument may be made if the doclists are in descending ** order. */ aOut = sqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING); @@ -190848,9 +198358,7 @@ static int fts3FilterMethod( } if( zSql ){ p->bLock++; - rc = sqlite3_prepare_v3( - p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0 - ); + rc = sqlite3Fts3PrepareStmt(p, zSql, 1, 1, &pCsr->pStmt); p->bLock--; sqlite3_free(zSql); }else{ @@ -191163,12 +198671,13 @@ static void fts3SnippetFunc( int nVal, /* Size of apVal[] array */ sqlite3_value **apVal /* Array of arguments */ ){ + Fts3Table *pTab = 0; Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */ const char *zStart = "<b>"; const char *zEnd = "</b>"; const char *zEllipsis = "<b>...</b>"; - int iCol = -1; - int nToken = 15; /* Default number of tokens in snippet */ + i64 iCol = -1; + i64 nToken = 15; /* Default number of tokens in snippet */ /* There must be at least one argument passed to this function (otherwise ** the non-overloaded version would have been called instead of this one). @@ -191181,11 +198690,12 @@ static void fts3SnippetFunc( return; } if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return; + pTab = (Fts3Table *)pCsr->base.pVtab; switch( nVal ){ - case 6: nToken = sqlite3_value_int(apVal[5]); + case 6: nToken = sqlite3_value_int64(apVal[5]); /* no break */ deliberate_fall_through - case 5: iCol = sqlite3_value_int(apVal[4]); + case 5: iCol = sqlite3_value_int64(apVal[4]); /* no break */ deliberate_fall_through case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]); /* no break */ deliberate_fall_through @@ -191195,9 +198705,12 @@ static void fts3SnippetFunc( } if( !zEllipsis || !zEnd || !zStart ){ sqlite3_result_error_nomem(pContext); - }else if( nToken==0 ){ + }else if( nToken==0 || iCol>=pTab->nColumn ){ sqlite3_result_text(pContext, "", -1, SQLITE_STATIC); }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){ + if( iCol<0 ) iCol = -1; + if( nToken<-64 ) nToken = -64; + if( nToken>64 ) nToken = 64; sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken); } } @@ -191473,6 +198986,7 @@ static int fts3IntegrityMethod( UNUSED_PARAMETER(isQuick); rc = sqlite3Fts3IntegrityCheck(p, &bOk); + assert( pVtab->zErrMsg==0 || rc!=SQLITE_OK ); assert( rc!=SQLITE_CORRUPT_VTAB ); if( rc==SQLITE_ERROR || (rc&0xFF)==SQLITE_CORRUPT ){ *pzErr = sqlite3_mprintf("unable to validate the inverted index for" @@ -191876,6 +199390,7 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){ char *p1; char *p2; char *aOut; + i64 nAlloc = (i64)nPoslist*2 + FTS3_BUFFER_PADDING; if( nMaxUndeferred>iPrev ){ p1 = aPoslist; @@ -191887,7 +199402,7 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){ nDistance = iPrev - nMaxUndeferred; } - aOut = (char *)sqlite3Fts3MallocZero(nPoslist+FTS3_BUFFER_PADDING); + aOut = (char *)sqlite3Fts3MallocZero(nAlloc); if( !aOut ){ sqlite3_free(aPoslist); return SQLITE_NOMEM; @@ -192186,7 +199701,7 @@ static int incrPhraseTokenNext( ** ** * does not contain any deferred tokens. ** -** Advance it to the next matching documnent in the database and populate +** Advance it to the next matching document in the database and populate ** the Fts3Doclist.pList and nList fields. ** ** If there is no "next" entry and no error occurs, then *pbEof is set to @@ -192972,7 +200487,7 @@ static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){ nTmp += p->pRight->pPhrase->doclist.nList; } nTmp += p->pPhrase->doclist.nList; - aTmp = sqlite3_malloc64(nTmp*2); + aTmp = sqlite3_malloc64(nTmp*2 + FTS3_VARINT_MAX); if( !aTmp ){ *pRc = SQLITE_NOMEM; res = 0; @@ -193193,7 +200708,7 @@ static int fts3EvalNext(Fts3Cursor *pCsr){ } /* -** Restart interation for expression pExpr so that the next call to +** Restart iteration for expression pExpr so that the next call to ** fts3EvalNext() visits the first row. Do not allow incremental ** loading or merging of phrase doclists for this iteration. ** @@ -193236,6 +200751,24 @@ static void fts3EvalRestart( } } +/* +** Expression node pExpr is an MSR phrase. This function restarts pExpr +** so that it is a regular phrase query, not an MSR. SQLITE_OK is returned +** if successful, or an SQLite error code otherwise. +*/ +SQLITE_PRIVATE int sqlite3Fts3MsrCancel(Fts3Cursor *pCsr, Fts3Expr *pExpr){ + int rc = SQLITE_OK; + if( pExpr->bEof==0 ){ + i64 iDocid = pExpr->iDocid; + fts3EvalRestart(pCsr, pExpr, &rc); + while( rc==SQLITE_OK && pExpr->iDocid!=iDocid ){ + fts3EvalNextRow(pCsr, pExpr, &rc); + if( pExpr->bEof ) rc = FTS_CORRUPT_VTAB; + } + } + return rc; +} + /* ** After allocating the Fts3Expr.aMI[] array for each phrase in the ** expression rooted at pExpr, the cursor iterates through all rows matched @@ -193623,7 +201156,7 @@ SQLITE_PRIVATE int sqlite3Fts3Corrupt(){ } #endif -#if !SQLITE_CORE +#if !defined(SQLITE_CORE) /* ** Initialize API pointer table, if required. */ @@ -193789,6 +201322,14 @@ static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){ #define FTS4AUX_GE_CONSTRAINT 2 #define FTS4AUX_LE_CONSTRAINT 4 +/* +** Return true if constraint iCons of pInfo uses the "binary" collation +** sequence. Or false it it uses anything else. +*/ +static int fts3auxIsBinary(sqlite3_index_info *pInfo, int iCons){ + return 0==sqlite3_stricmp("binary", sqlite3_vtab_collation(pInfo, iCons)); +} + /* ** xBestIndex - Analyze a WHERE and ORDER BY clause. */ @@ -193816,7 +201357,7 @@ static int fts3auxBestIndexMethod( /* Search for equality and range constraints on the "term" column. ** And equality constraints on the hidden "languageid" column. */ for(i=0; i<pInfo->nConstraint; i++){ - if( pInfo->aConstraint[i].usable ){ + if( pInfo->aConstraint[i].usable && fts3auxIsBinary(pInfo, i) ){ int op = pInfo->aConstraint[i].op; int iCol = pInfo->aConstraint[i].iColumn; @@ -193971,7 +201512,7 @@ static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){ pCsr->aStat[1].nDoc++; } eState = 2; - /* fall through */ + /* no break */ deliberate_fall_through case 2: if( v==0 ){ /* 0x00. Next integer will be a docid. */ @@ -193987,7 +201528,7 @@ static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){ /* State 3. The integer just read is a column number. */ default: assert( eState==3 ); iCol = (int)v; - if( iCol<1 ){ + if( iCol<1 || iCol>32767 ){ rc = SQLITE_CORRUPT_VTAB; break; } @@ -194062,7 +201603,7 @@ static int fts3auxFilterMethod( pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY; if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN; - if( iEq>=0 || iGe>=0 ){ + if( (iEq>=0 || iGe>=0) && sqlite3_value_type(apVal[0])==SQLITE_TEXT ){ const unsigned char *zStr = sqlite3_value_text(apVal[0]); assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) ); if( zStr ){ @@ -194072,7 +201613,7 @@ static int fts3auxFilterMethod( } } - if( iLe>=0 ){ + if( iLe>=0 && sqlite3_value_type(apVal[0])==SQLITE_TEXT ){ pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe])); if( pCsr->zStop==0 ) return SQLITE_NOMEM; pCsr->nStop = (int)strlen(pCsr->zStop); @@ -194367,6 +201908,23 @@ SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer( */ static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *); +/* +** Search buffer z[], size n, for a '"' character. Or, if enable_parenthesis +** is defined, search for '(' and ')' as well. Return the index of the first +** such character in the buffer. If there is no such character, return -1. +*/ +static int findBarredChar(const char *z, int n){ + int ii; + for(ii=0; ii<n; ii++){ + if( (z[ii]=='"') + || (sqlite3_fts3_enable_parentheses && (z[ii]=='(' || z[ii]==')')) + ){ + return ii; + } + } + return -1; +} + /* ** Extract the next token from buffer z (length n) using the tokenizer ** and other information (column names etc.) in pParse. Create an Fts3Expr @@ -194391,16 +201949,9 @@ static int getNextToken( int rc; sqlite3_tokenizer_cursor *pCursor; Fts3Expr *pRet = 0; - int i = 0; - - /* Set variable i to the maximum number of bytes of input to tokenize. */ - for(i=0; i<n; i++){ - if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break; - if( z[i]=='"' ) break; - } - *pnConsumed = i; - rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor); + *pnConsumed = n; + rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor); if( rc==SQLITE_OK ){ const char *zToken; int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0; @@ -194408,7 +201959,18 @@ static int getNextToken( rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition); if( rc==SQLITE_OK ){ - nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken; + /* Check that this tokenization did not gobble up any " characters. Or, + ** if enable_parenthesis is true, that it did not gobble up any + ** open or close parenthesis characters either. If it did, call + ** getNextToken() again, but pass only that part of the input buffer + ** up to the first such character. */ + int iBarred = findBarredChar(z, iEnd); + if( iBarred>=0 ){ + pModule->xClose(pCursor); + return getNextToken(pParse, iCol, z, iBarred, ppExpr, pnConsumed); + } + + nByte = sizeof(Fts3Expr) + SZ_FTS3PHRASE(1) + nToken; pRet = (Fts3Expr *)sqlite3Fts3MallocZero(nByte); if( !pRet ){ rc = SQLITE_NOMEM; @@ -194418,7 +201980,7 @@ static int getNextToken( pRet->pPhrase->nToken = 1; pRet->pPhrase->iColumn = iCol; pRet->pPhrase->aToken[0].n = nToken; - pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1]; + pRet->pPhrase->aToken[0].z = (char*)&pRet->pPhrase->aToken[1]; memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken); if( iEnd<n && z[iEnd]=='*' ){ @@ -194442,7 +202004,11 @@ static int getNextToken( } *pnConsumed = iEnd; - }else if( i && rc==SQLITE_DONE ){ + }else if( n && rc==SQLITE_DONE ){ + int iBarred = findBarredChar(z, n); + if( iBarred>=0 ){ + *pnConsumed = iBarred; + } rc = SQLITE_OK; } @@ -194489,9 +202055,9 @@ static int getNextString( Fts3Expr *p = 0; sqlite3_tokenizer_cursor *pCursor = 0; char *zTemp = 0; - int nTemp = 0; + i64 nTemp = 0; - const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase); + const int nSpace = sizeof(Fts3Expr) + SZ_FTS3PHRASE(1); int nToken = 0; /* The final Fts3Expr data structure, including the Fts3Phrase, @@ -194525,10 +202091,11 @@ static int getNextString( Fts3PhraseToken *pToken; p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken)); - if( !p ) goto no_mem; - zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte); - if( !zTemp ) goto no_mem; + if( !zTemp || !p ){ + rc = SQLITE_NOMEM; + goto getnextstring_out; + } assert( nToken==ii ); pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii]; @@ -194543,9 +202110,6 @@ static int getNextString( nToken = ii+1; } } - - pModule->xClose(pCursor); - pCursor = 0; } if( rc==SQLITE_DONE ){ @@ -194553,7 +202117,10 @@ static int getNextString( char *zBuf = 0; p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp); - if( !p ) goto no_mem; + if( !p ){ + rc = SQLITE_NOMEM; + goto getnextstring_out; + } memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p); p->eType = FTSQUERY_PHRASE; p->pPhrase = (Fts3Phrase *)&p[1]; @@ -194561,11 +202128,9 @@ static int getNextString( p->pPhrase->nToken = nToken; zBuf = (char *)&p->pPhrase->aToken[nToken]; + assert( nTemp==0 || zTemp ); if( zTemp ){ memcpy(zBuf, zTemp, nTemp); - sqlite3_free(zTemp); - }else{ - assert( nTemp==0 ); } for(jj=0; jj<p->pPhrase->nToken; jj++){ @@ -194575,17 +202140,17 @@ static int getNextString( rc = SQLITE_OK; } - *ppExpr = p; - return rc; -no_mem: - + getnextstring_out: if( pCursor ){ pModule->xClose(pCursor); } sqlite3_free(zTemp); - sqlite3_free(p); - *ppExpr = 0; - return SQLITE_NOMEM; + if( rc!=SQLITE_OK ){ + sqlite3_free(p); + p = 0; + } + *ppExpr = p; + return rc; } /* @@ -194653,6 +202218,7 @@ static int getNextNode( assert( nKey==4 ); if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){ nKey += 1+sqlite3Fts3ReadInt(&zInput[nKey+1], &nNear); + if( nNear>=1000000000 ) nNear = 1000000000; } } @@ -194730,7 +202296,7 @@ static int getNextNode( iColLen = 0; for(ii=0; ii<pParse->nCol; ii++){ const char *zStr = pParse->azCol[ii]; - int nStr = (int)strlen(zStr); + int nStr = zStr ? (int)strlen(zStr) : 0; if( nInput>nStr && zInput[nStr]==':' && sqlite3_strnicmp(zStr, zInput, nStr)==0 ){ @@ -194864,7 +202430,7 @@ static int fts3ExprParse( /* The isRequirePhrase variable is set to true if a phrase or ** an expression contained in parenthesis is required. If a - ** binary operator (AND, OR, NOT or NEAR) is encounted when + ** binary operator (AND, OR, NOT or NEAR) is encountered when ** isRequirePhrase is set, this is a syntax error. */ if( !isPhrase && isRequirePhrase ){ @@ -195445,8 +203011,9 @@ static void fts3ExprTestCommon( ); } - if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){ - sqlite3Fts3ExprFree(pExpr); + if( rc==SQLITE_OK && fts3ExprCheckDepth(pExpr, SQLITE_FTS3_MAX_EXPR_DEPTH) ){ + sqlite3_result_error(context, "Expression nested too deep", -1); + }else if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){ sqlite3_result_error(context, "Error parsing expression", -1); }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){ sqlite3_result_error_nomem(context); @@ -195689,7 +203256,7 @@ static void fts3HashInsertElement( } -/* Resize the hash table so that it cantains "new_size" buckets. +/* Resize the hash table so that it contains "new_size" buckets. ** "new_size" must be a power of 2. The hash table might fail ** to resize if sqliteMalloc() fails. ** @@ -196144,7 +203711,7 @@ static int star_oh(const char *z){ /* ** If the word ends with zFrom and xCond() is true for the stem -** of the word that preceeds the zFrom ending, then change the +** of the word that precedes the zFrom ending, then change the ** ending to zTo. ** ** The input word *pz and zFrom are both in reverse order. zTo @@ -196507,10 +204074,11 @@ static int porterNext( if( c->iOffset>iStartOffset ){ int n = c->iOffset-iStartOffset; if( n>c->nAllocated ){ + i64 nNew = n + 20; char *pNew; - c->nAllocated = n+20; - pNew = sqlite3_realloc64(c->zToken, c->nAllocated); + pNew = sqlite3_realloc64(c->zToken, nNew); if( !pNew ) return SQLITE_NOMEM; + c->nAllocated = (int)nNew; c->zToken = pNew; } porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes); @@ -197655,7 +205223,7 @@ static int fts3tokFilterMethod( fts3tokResetCursor(pCsr); if( idxNum==1 ){ const char *zByte = (const char *)sqlite3_value_text(apVal[0]); - int nByte = sqlite3_value_bytes(apVal[0]); + sqlite3_int64 nByte = sqlite3_value_bytes(apVal[0]); pCsr->zInput = sqlite3_malloc64(nByte+1); if( pCsr->zInput==0 ){ rc = SQLITE_NOMEM; @@ -197869,9 +205437,9 @@ typedef struct SegmentWriter SegmentWriter; ** incrementally. See function fts3PendingListAppend() for details. */ struct PendingList { - int nData; + sqlite3_int64 nData; char *aData; - int nSpace; + sqlite3_int64 nSpace; sqlite3_int64 iLastDocid; sqlite3_int64 iLastCol; sqlite3_int64 iLastPos; @@ -198044,6 +205612,24 @@ struct SegmentNode { #define SQL_UPDATE_LEVEL_IDX 38 #define SQL_UPDATE_LEVEL 39 +/* +** Wrapper around sqlite3_prepare_v3() to ensure that SQLITE_PREPARE_FROM_DDL +** is always set. +*/ +SQLITE_PRIVATE int sqlite3Fts3PrepareStmt( + Fts3Table *p, /* Prepare for this connection */ + const char *zSql, /* SQL to prepare */ + int bPersist, /* True to set SQLITE_PREPARE_PERSISTENT */ + int bAllowVtab, /* True to omit SQLITE_PREPARE_NO_VTAB */ + sqlite3_stmt **pp /* OUT: Prepared statement */ +){ + int f = SQLITE_PREPARE_FROM_DDL + |((bAllowVtab==0) ? SQLITE_PREPARE_NO_VTAB : 0) + |(bPersist ? SQLITE_PREPARE_PERSISTENT : 0); + + return sqlite3_prepare_v3(p->db, zSql, -1, f, pp, NULL); +} + /* ** This function is used to obtain an SQLite prepared statement handle ** for the statement identified by the second argument. If successful, @@ -198169,12 +205755,12 @@ static int fts3SqlStmt( pStmt = p->aStmt[eStmt]; if( !pStmt ){ - int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB; + int bAllowVtab = 0; char *zSql; if( eStmt==SQL_CONTENT_INSERT ){ zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist); }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){ - f &= ~SQLITE_PREPARE_NO_VTAB; + bAllowVtab = 1; zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist); }else{ zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName); @@ -198182,7 +205768,7 @@ static int fts3SqlStmt( if( !zSql ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_prepare_v3(p->db, zSql, -1, f, &pStmt, NULL); + rc = sqlite3Fts3PrepareStmt(p, zSql, 1, bAllowVtab, &pStmt); sqlite3_free(zSql); assert( rc==SQLITE_OK || pStmt==0 ); p->aStmt[eStmt] = pStmt; @@ -198531,7 +206117,9 @@ static int fts3PendingTermsAddOne( pList = (PendingList *)fts3HashFind(pHash, zToken, nToken); if( pList ){ - p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem)); + assert( (i64)pList->nData+(i64)nToken+(i64)sizeof(Fts3HashElem) + <= (i64)p->nPendingData ); + p->nPendingData -= (int)(pList->nData + nToken + sizeof(Fts3HashElem)); } if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){ if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){ @@ -198544,7 +206132,9 @@ static int fts3PendingTermsAddOne( } } if( rc==SQLITE_OK ){ - p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem)); + assert( (i64)p->nPendingData + pList->nData + nToken + + sizeof(Fts3HashElem) <= 0x3fffffff ); + p->nPendingData += (int)(pList->nData + nToken + sizeof(Fts3HashElem)); } return rc; } @@ -200878,6 +208468,10 @@ static void fts3ReadEndBlockField( for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){ iVal = iVal*10 + (zText[i] - '0'); } + + /* This if() clause is just to avoid an integer overflow. The record is + ** corrupt in this case. */ + if( (i64)iVal==SMALLEST_INT64 ) iMul = 1; *pnByte = ((i64)iVal * (i64)iMul); } } @@ -201345,7 +208939,7 @@ static int fts3DoRebuild(Fts3Table *p){ if( !zSql ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); + rc = sqlite3Fts3PrepareStmt(p, zSql, 0, 1, &pStmt); sqlite3_free(zSql); } @@ -201485,8 +209079,8 @@ struct NodeWriter { ** to an appendable b-tree segment. */ struct IncrmergeWriter { - int nLeafEst; /* Space allocated for leaf blocks */ - int nWork; /* Number of leaf pages flushed */ + i64 nLeafEst; /* Space allocated for leaf blocks */ + i64 nWork; /* Number of leaf pages flushed */ sqlite3_int64 iAbsLevel; /* Absolute level of input segments */ int iIdx; /* Index of *output* segment in iAbsLevel+1 */ sqlite3_int64 iStart; /* Block number of first allocated block */ @@ -201727,7 +209321,7 @@ static int fts3IncrmergePush( ** ** It is assumed that the buffer associated with pNode is already large ** enough to accommodate the new entry. The buffer associated with pPrev -** is extended by this function if requrired. +** is extended by this function if required. ** ** If an error (i.e. OOM condition) occurs, an SQLite error code is ** returned. Otherwise, SQLITE_OK. @@ -202104,7 +209698,7 @@ static int fts3IncrmergeLoad( return FTS_CORRUPT_VTAB; } - pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT; + pWriter->nLeafEst = (int)(((iEnd - iStart)+1)/FTS_MAX_APPENDABLE_HEIGHT); pWriter->iStart = iStart; pWriter->iEnd = iEnd; pWriter->iAbsLevel = iAbsLevel; @@ -202232,7 +209826,7 @@ static int fts3IncrmergeWriter( ){ int rc; /* Return Code */ int i; /* Iterator variable */ - int nLeafEst = 0; /* Blocks allocated for leaf nodes */ + i64 nLeafEst = 0; /* Blocks allocated for leaf nodes */ sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */ sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */ @@ -202242,7 +209836,7 @@ static int fts3IncrmergeWriter( sqlite3_bind_int64(pLeafEst, 1, iAbsLevel); sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment); if( SQLITE_ROW==sqlite3_step(pLeafEst) ){ - nLeafEst = sqlite3_column_int(pLeafEst, 0); + nLeafEst = sqlite3_column_int64(pLeafEst, 0); } rc = sqlite3_reset(pLeafEst); } @@ -203012,38 +210606,42 @@ static u64 fts3ChecksumIndex( rc = sqlite3Fts3SegReaderStart(p, &csr, &filter); } - if( rc==SQLITE_OK ){ - while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){ - char *pCsr = csr.aDoclist; - char *pEnd = &pCsr[csr.nDoclist]; + while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p,&csr)) ){ + char *pCsr = csr.aDoclist; + char *pEnd = &pCsr[csr.nDoclist]; - i64 iDocid = 0; - i64 iCol = 0; - u64 iPos = 0; + i64 iDocid = 0; + int iCol = 0; + u64 iPos = 0; - pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid); - while( pCsr<pEnd ){ - u64 iVal = 0; - pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal); - if( pCsr<pEnd ){ - if( iVal==0 || iVal==1 ){ - iCol = 0; - iPos = 0; - if( iVal ){ - pCsr += sqlite3Fts3GetVarint(pCsr, &iCol); + rc = SQLITE_OK; + pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid); + while( pCsr<pEnd ){ + u64 iVal = 0; + pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal); + if( pCsr<pEnd ){ + if( iVal==0 || iVal==1 ){ + iCol = 0; + iPos = 0; + if( iVal ){ + pCsr += fts3GetVarint32(pCsr, &iCol); + }else{ + pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal); + if( p->bDescIdx ){ + iDocid = (i64)((u64)iDocid - iVal); }else{ - pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal); - if( p->bDescIdx ){ - iDocid = (i64)((u64)iDocid - iVal); - }else{ - iDocid = (i64)((u64)iDocid + iVal); - } + iDocid = (i64)((u64)iDocid + iVal); } + } + }else{ + iPos += (iVal - 2); + if( iPos>0x7FFFFFFF ){ + rc = SQLITE_CORRUPT_VTAB; + break; }else{ - iPos += (iVal - 2); cksum = cksum ^ fts3ChecksumEntry( csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid, - (int)iCol, (int)iPos + iCol, (int)iPos ); } } @@ -203070,6 +210668,7 @@ SQLITE_PRIVATE int sqlite3Fts3IntegrityCheck(Fts3Table *p, int *pbOk){ u64 cksum1 = 0; /* Checksum based on FTS index contents */ u64 cksum2 = 0; /* Checksum based on %_content contents */ sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */ + int bContentless = (p->zContentTbl && p->zContentTbl[0]=='\0'); /* This block calculates the checksum according to the FTS index. */ rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0); @@ -203089,7 +210688,7 @@ SQLITE_PRIVATE int sqlite3Fts3IntegrityCheck(Fts3Table *p, int *pbOk){ } /* This block calculates the checksum according to the %_content table */ - if( rc==SQLITE_OK ){ + if( rc==SQLITE_OK && !bContentless ){ sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule; sqlite3_stmt *pStmt = 0; char *zSql; @@ -203098,7 +210697,7 @@ SQLITE_PRIVATE int sqlite3Fts3IntegrityCheck(Fts3Table *p, int *pbOk){ if( !zSql ){ rc = SQLITE_NOMEM; }else{ - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); + rc = sqlite3Fts3PrepareStmt(p, zSql, 0, 1, &pStmt); sqlite3_free(zSql); } @@ -203147,7 +210746,7 @@ SQLITE_PRIVATE int sqlite3Fts3IntegrityCheck(Fts3Table *p, int *pbOk){ rc = SQLITE_OK; *pbOk = 0; }else{ - *pbOk = (rc==SQLITE_OK && cksum1==cksum2); + *pbOk = (rc==SQLITE_OK && (bContentless || cksum1==cksum2)); } return rc; } @@ -203228,7 +210827,7 @@ static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){ v = atoi(&zVal[9]); if( v>=24 && v<=p->nPgsz-35 ) p->nNodeSize = v; rc = SQLITE_OK; - }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){ + }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 11) ){ v = atoi(&zVal[11]); if( v>=64 && v<=FTS3_MAX_PENDING_DATA ) p->nMaxPendingData = v; rc = SQLITE_OK; @@ -203390,7 +210989,7 @@ SQLITE_PRIVATE int sqlite3Fts3DeferToken( /* ** SQLite value pRowid contains the rowid of a row that may or may not be ** present in the FTS3 table. If it is, delete it and adjust the contents -** of subsiduary data structures accordingly. +** of subsidiary data structures accordingly. */ static int fts3DeleteByRowid( Fts3Table *p, @@ -203625,10 +211224,6 @@ SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){ /* #include <string.h> */ /* #include <assert.h> */ -#ifndef SQLITE_AMALGAMATION -typedef sqlite3_int64 i64; -#endif - /* ** Characters that may appear in the second argument to matchinfo(). */ @@ -203716,9 +211311,13 @@ struct MatchinfoBuffer { int nElem; int bGlobal; /* Set if global data is loaded */ char *zMatchinfo; - u32 aMatchinfo[1]; + u32 aMI[FLEXARRAY]; }; +/* Size (in bytes) of a MatchinfoBuffer sufficient for N elements */ +#define SZ_MATCHINFOBUFFER(N) \ + (offsetof(MatchinfoBuffer,aMI)+(((N)+1)/2)*sizeof(u64)) + /* ** The snippet() and offsets() functions both return text values. An instance @@ -203740,16 +211339,15 @@ struct StrBuffer { /* ** Allocate a two-slot MatchinfoBuffer object. */ -static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){ +static MatchinfoBuffer *fts3MIBufferNew(i64 nElem, const char *zMatchinfo){ MatchinfoBuffer *pRet; - sqlite3_int64 nByte = sizeof(u32) * (2*(sqlite3_int64)nElem + 1) - + sizeof(MatchinfoBuffer); + sqlite3_int64 nByte = sizeof(u32) * (2*(i64)nElem+1) + SZ_MATCHINFOBUFFER(1); sqlite3_int64 nStr = strlen(zMatchinfo); pRet = sqlite3Fts3MallocZero(nByte + nStr+1); if( pRet ){ - pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet; - pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + pRet->aMI[0] = (u8*)(&pRet->aMI[1]) - (u8*)pRet; + pRet->aMI[1+nElem] = pRet->aMI[0] + sizeof(u32)*((int)nElem+1); pRet->nElem = (int)nElem; pRet->zMatchinfo = ((char*)pRet) + nByte; @@ -203763,10 +211361,10 @@ static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){ static void fts3MIBufferFree(void *p){ MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]); - assert( (u32*)p==&pBuf->aMatchinfo[1] - || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2] + assert( (u32*)p==&pBuf->aMI[1] + || (u32*)p==&pBuf->aMI[pBuf->nElem+2] ); - if( (u32*)p==&pBuf->aMatchinfo[1] ){ + if( (u32*)p==&pBuf->aMI[1] ){ pBuf->aRef[1] = 0; }else{ pBuf->aRef[2] = 0; @@ -203783,18 +211381,18 @@ static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){ if( p->aRef[1]==0 ){ p->aRef[1] = 1; - aOut = &p->aMatchinfo[1]; + aOut = &p->aMI[1]; xRet = fts3MIBufferFree; } else if( p->aRef[2]==0 ){ p->aRef[2] = 1; - aOut = &p->aMatchinfo[p->nElem+2]; + aOut = &p->aMI[p->nElem+2]; xRet = fts3MIBufferFree; }else{ aOut = (u32*)sqlite3_malloc64(p->nElem * sizeof(u32)); if( aOut ){ xRet = sqlite3_free; - if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32)); + if( p->bGlobal ) memcpy(aOut, &p->aMI[1], p->nElem*sizeof(u32)); } } @@ -203804,7 +211402,7 @@ static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){ static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){ p->bGlobal = 1; - memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32)); + memcpy(&p->aMI[2+p->nElem], &p->aMI[1], p->nElem*sizeof(u32)); } /* @@ -204137,6 +211735,7 @@ static int fts3BestSnippet( sqlite3_int64 nByte; /* Number of bytes of space to allocate */ int iBestScore = -1; /* Best snippet score found so far */ int i; /* Loop counter */ + Fts3Expr *pExpr = pCsr->pExpr; memset(&sIter, 0, sizeof(sIter)); @@ -204165,9 +211764,12 @@ static int fts3BestSnippet( sIter.nSnippet = nSnippet; sIter.nPhrase = nList; sIter.iCurrent = -1; - rc = sqlite3Fts3ExprIterate( - pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter - ); + rc = sqlite3Fts3ExprIterate(pExpr, fts3SnippetFindPositions, (void*)&sIter); + if( rc==SQLITE_OK ){ + /* Iterate through the expression twice, in case pointers garnered during + ** the first iteration are invalidated by a call to fts5EvalRestart(). */ + rc = sqlite3Fts3ExprIterate(pExpr, fts3SnippetFindPositions, (void*)&sIter); + } if( rc==SQLITE_OK ){ /* Set the *pmSeen output variable. */ @@ -204219,11 +211821,11 @@ static int fts3StringAppend( } /* If there is insufficient space allocated at StrBuffer.z, use realloc() - ** to grow the buffer until so that it is big enough to accomadate the + ** to grow the buffer until so that it is big enough to accommodate the ** appended data. */ - if( pStr->n+nAppend+1>=pStr->nAlloc ){ - sqlite3_int64 nAlloc = pStr->nAlloc+(sqlite3_int64)nAppend+100; + if( (i64)pStr->n+(i64)nAppend+1>=(i64)pStr->nAlloc ){ + i64 nAlloc = pStr->nAlloc+(i64)nAppend+100; char *zNew = sqlite3_realloc64(pStr->z, nAlloc); if( !zNew ){ return SQLITE_NOMEM; @@ -204495,7 +212097,7 @@ static int fts3ExprLHits( if( p->flag==FTS3_MATCHINFO_LHITS ){ p->aMatchinfo[iStart + iCol] = (u32)nHit; }else if( nHit ){ - p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F)); + p->aMatchinfo[iStart + iCol/32] |= (1U << (iCol&0x1F)); } } assert( *pIter==0x00 || *pIter==0x01 ); @@ -204614,8 +212216,8 @@ static int fts3MatchinfoCheck( return SQLITE_ERROR; } -static size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){ - size_t nVal; /* Number of integers output by cArg */ +static i64 fts3MatchinfoSize(MatchInfo *pInfo, char cArg){ + i64 nVal; /* Number of integers output by cArg */ switch( cArg ){ case FTS3_MATCHINFO_NDOC: @@ -204631,16 +212233,16 @@ static size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){ break; case FTS3_MATCHINFO_LHITS: - nVal = pInfo->nCol * pInfo->nPhrase; + nVal = (i64)pInfo->nCol * pInfo->nPhrase; break; case FTS3_MATCHINFO_LHITS_BM: - nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32); + nVal = (i64)pInfo->nPhrase * ((pInfo->nCol + 31) / 32); break; default: assert( cArg==FTS3_MATCHINFO_HITS ); - nVal = pInfo->nCol * pInfo->nPhrase * 3; + nVal = (i64)pInfo->nCol * pInfo->nPhrase * 3; break; } @@ -204922,7 +212524,7 @@ static int fts3MatchinfoValues( case FTS3_MATCHINFO_LHITS_BM: case FTS3_MATCHINFO_LHITS: { - size_t nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32); + i64 nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32); memset(pInfo->aMatchinfo, 0, nZero); rc = fts3ExprLHitGather(pCsr->pExpr, pInfo); break; @@ -204991,7 +212593,7 @@ static void fts3GetMatchinfo( ** initialize those elements that are constant for every row. */ if( pCsr->pMIBuffer==0 ){ - size_t nMatchinfo = 0; /* Number of u32 elements in match-info */ + i64 nMatchinfo = 0; /* Number of u32 elements in match-info */ int i; /* Used to iterate through zArg */ /* Determine the number of phrases in the query */ @@ -205076,9 +212678,8 @@ SQLITE_PRIVATE void sqlite3Fts3Snippet( return; } - /* Limit the snippet length to 64 tokens. */ - if( nToken<-64 ) nToken = -64; - if( nToken>+64 ) nToken = +64; + /* The snippet length should already have been limited to 64 tokens. */ + assert( nToken>=-64 && nToken<=64 ); for(nSnippet=1; 1; nSnippet++){ @@ -205194,6 +212795,22 @@ static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){ return rc; } +/* +** If expression pExpr is a phrase expression that uses an MSR query, +** restart it as a regular, non-incremental query. Return SQLITE_OK +** if successful, or an SQLite error code otherwise. +*/ +static int fts3ExprRestartIfCb(Fts3Expr *pExpr, int iPhrase, void *ctx){ + TermOffsetCtx *p = (TermOffsetCtx*)ctx; + int rc = SQLITE_OK; + UNUSED_PARAMETER(iPhrase); + if( pExpr->pPhrase && pExpr->pPhrase->bIncr ){ + rc = sqlite3Fts3MsrCancel(p->pCsr, pExpr); + pExpr->pPhrase->bIncr = 0; + } + return rc; +} + /* ** Implementation of offsets() function. */ @@ -205230,6 +212847,12 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets( sCtx.iDocid = pCsr->iPrevId; sCtx.pCsr = pCsr; + /* If a query restart will be required, do it here, rather than later of + ** after pointers to poslist buffers that may be invalidated by a restart + ** have been saved. */ + rc = sqlite3Fts3ExprIterate(pCsr->pExpr, fts3ExprRestartIfCb, (void*)&sCtx); + if( rc!=SQLITE_OK ) goto offsets_out; + /* Loop through the table columns, appending offset information to ** string-buffer res for each column. */ @@ -205393,13 +213016,11 @@ SQLITE_PRIVATE void sqlite3Fts3Matchinfo( /* #include "fts3_tokenizer.h" */ /* -** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied -** from the sqlite3 source file utf.c. If this file is compiled as part -** of the amalgamation, they are not required. +** The following two macros - FTS3_READ_UTF8 and FTS3_WRITE_UTF8 - have +** been copied from the sqlite3 source file utf.c. */ -#ifndef SQLITE_AMALGAMATION -static const unsigned char sqlite3Utf8Trans1[] = { +static const unsigned char fts3Utf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, @@ -205410,10 +213031,10 @@ static const unsigned char sqlite3Utf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, }; -#define READ_UTF8(zIn, zTerm, c) \ +#define FTS3_READ_UTF8(zIn, zTerm, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ - c = sqlite3Utf8Trans1[c-0xc0]; \ + c = fts3Utf8Trans1[c-0xc0]; \ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ @@ -205422,28 +213043,26 @@ static const unsigned char sqlite3Utf8Trans1[] = { || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ } -#define WRITE_UTF8(zOut, c) { \ - if( c<0x00080 ){ \ - *zOut++ = (u8)(c&0xFF); \ - } \ - else if( c<0x00800 ){ \ - *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ - *zOut++ = 0x80 + (u8)(c & 0x3F); \ - } \ - else if( c<0x10000 ){ \ - *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ - *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ - *zOut++ = 0x80 + (u8)(c & 0x3F); \ - }else{ \ - *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ - *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ - *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ - *zOut++ = 0x80 + (u8)(c & 0x3F); \ - } \ +#define FTS3_WRITE_UTF8(zOut, c) { \ + if( c<0x00080 ){ \ + *zOut++ = (u8)(c&0xFF); \ + } \ + else if( c<0x00800 ){ \ + *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + } \ + else if( c<0x10000 ){ \ + *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + }else{ \ + *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ + *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ + *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ + *zOut++ = 0x80 + (u8)(c & 0x3F); \ + } \ } -#endif /* ifndef SQLITE_AMALGAMATION */ - typedef struct unicode_tokenizer unicode_tokenizer; typedef struct unicode_cursor unicode_cursor; @@ -205509,7 +213128,7 @@ static int unicodeAddExceptions( assert( bAlnum==0 || bAlnum==1 ); while( z<zTerm ){ - READ_UTF8(z, zTerm, iCode); + FTS3_READ_UTF8(z, zTerm, iCode); assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 ); if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0 @@ -205528,7 +213147,7 @@ static int unicodeAddExceptions( z = (const unsigned char *)zIn; while( z<zTerm ){ - READ_UTF8(z, zTerm, iCode); + FTS3_READ_UTF8(z, zTerm, iCode); if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0 ){ @@ -205700,7 +213319,7 @@ static int unicodeNext( ** Return SQLITE_DONE early if this takes us all the way to the end of ** the input. */ while( z<zTerm ){ - READ_UTF8(z, zTerm, iCode); + FTS3_READ_UTF8(z, zTerm, iCode); if( unicodeIsAlnum(p, (int)iCode) ) break; zStart = z; } @@ -205723,12 +213342,12 @@ static int unicodeNext( zEnd = z; iOut = sqlite3FtsUnicodeFold((int)iCode, p->eRemoveDiacritic); if( iOut ){ - WRITE_UTF8(zOut, iOut); + FTS3_WRITE_UTF8(zOut, iOut); } /* If the cursor is not at EOF, read the next character */ if( z>=zTerm ) break; - READ_UTF8(z, zTerm, iCode); + FTS3_READ_UTF8(z, zTerm, iCode); }while( unicodeIsAlnum(p, (int)iCode) || sqlite3FtsUnicodeIsdiacritic((int)iCode) ); @@ -206176,8 +213795,8 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){ ** Beginning with version 3.45.0 (circa 2024-01-01), these routines also ** accept BLOB values that have JSON encoded using a binary representation ** called "JSONB". The name JSONB comes from PostgreSQL, however the on-disk -** format SQLite JSONB is completely different and incompatible with -** PostgreSQL JSONB. +** format for SQLite-JSONB is completely different and incompatible with +** PostgreSQL-JSONB. ** ** Decoding and interpreting JSONB is still O(N) where N is the size of ** the input, the same as text JSON. However, the constant of proportionality @@ -206234,7 +213853,7 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){ ** ** The payload size need not be expressed in its minimal form. For example, ** if the payload size is 10, the size can be expressed in any of 5 different -** ways: (1) (X>>4)==10, (2) (X>>4)==12 following by on 0x0a byte, +** ways: (1) (X>>4)==10, (2) (X>>4)==12 following by one 0x0a byte, ** (3) (X>>4)==13 followed by 0x00 and 0x0a, (4) (X>>4)==14 followed by ** 0x00 0x00 0x00 0x0a, or (5) (X>>4)==15 followed by 7 bytes of 0x00 and ** a single byte of 0x0a. The shorter forms are preferred, of course, but @@ -206244,7 +213863,7 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){ ** the size when it becomes known, resulting in a non-minimal encoding. ** ** The value (X>>4)==15 is not actually used in the current implementation -** (as SQLite is currently unable handle BLOBs larger than about 2GB) +** (as SQLite is currently unable to handle BLOBs larger than about 2GB) ** but is included in the design to allow for future enhancements. ** ** The payload follows the header. NULL, TRUE, and FALSE have no payload and @@ -206304,23 +213923,47 @@ static const char * const jsonbType[] = { ** increase for the text-JSON parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os). */ static const char jsonIsSpace[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +#ifdef SQLITE_ASCII +/*0 1 2 3 4 5 6 7 8 9 a b c d e f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, /* 0 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1 */ + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 6 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7 */ + + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 8 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 9 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* a */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* b */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* c */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* d */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* e */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* f */ +#endif +#ifdef SQLITE_EBCDIC +/*0 1 2 3 4 5 6 7 8 9 a b c d e f */ + 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, /* 0 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1 */ + 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3 */ + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 6 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7 */ + + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 8 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 9 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* a */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* b */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* c */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* d */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* e */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* f */ +#endif + }; #define jsonIsspace(x) (jsonIsSpace[(unsigned char)x]) @@ -206328,7 +213971,13 @@ static const char jsonIsSpace[] = { ** The set of all space characters recognized by jsonIsspace(). ** Useful as the second argument to strspn(). */ +#ifdef SQLITE_ASCII static const char jsonSpaces[] = "\011\012\015\040"; +#endif +#ifdef SQLITE_EBCDIC +static const char jsonSpaces[] = "\005\045\015\100"; +#endif + /* ** Characters that are special to JSON. Control characters, @@ -206337,23 +213986,46 @@ static const char jsonSpaces[] = "\011\012\015\040"; ** it in the set of special characters. */ static const char jsonIsOk[256] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 +#ifdef SQLITE_ASCII +/*0 1 2 3 4 5 6 7 8 9 a b c d e f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1 */ + 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, /* 2 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 3 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, /* 5 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 7 */ + + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 8 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 9 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* a */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* b */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* c */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* d */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* e */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 /* f */ +#endif +#ifdef SQLITE_EBCDIC +/*0 1 2 3 4 5 6 7 8 9 a b c d e f */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2 */ + 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, /* 3 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 5 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, /* 7 */ + + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 8 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 9 */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* a */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* b */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* c */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* d */ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* e */ + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 /* f */ +#endif }; /* Objects */ @@ -206413,7 +214085,8 @@ struct JsonString { /* Allowed values for JsonString.eErr */ #define JSTRING_OOM 0x01 /* Out of memory */ #define JSTRING_MALFORMED 0x02 /* Malformed JSONB */ -#define JSTRING_ERR 0x04 /* Error already sent to sqlite3_result */ +#define JSTRING_TOODEEP 0x04 /* JSON nested too deep */ +#define JSTRING_ERR 0x08 /* Error already sent to sqlite3_result */ /* The "subtype" set for text JSON values passed through using ** sqlite3_result_subtype() and sqlite3_value_subtype(). @@ -206428,7 +214101,10 @@ struct JsonString { #define JSON_SQL 0x02 /* Result is always SQL */ #define JSON_ABPATH 0x03 /* Allow abbreviated JSON path specs */ #define JSON_ISSET 0x04 /* json_set(), not json_insert() */ -#define JSON_BLOB 0x08 /* Use the BLOB output format */ +#define JSON_AINS 0x08 /* json_array_insert(), not json_insert() */ +#define JSON_BLOB 0x10 /* Use the BLOB output format */ + +#define JSON_INSERT_TYPE(X) (((X)&0xC)>>2) /* A parsed JSON value. Lifecycle: @@ -206474,6 +214150,7 @@ struct JsonParse { #define JEDIT_REPL 2 /* Overwrite if exists */ #define JEDIT_INS 3 /* Insert if not exists */ #define JEDIT_SET 4 /* Insert or overwrite */ +#define JEDIT_AINS 5 /* array_insert() */ /* ** Maximum nesting depth of JSON for this implementation. @@ -206493,13 +214170,14 @@ struct JsonParse { */ #define JSON_EDITABLE 0x01 /* Generate a writable JsonParse object */ #define JSON_KEEPERROR 0x02 /* Return non-NULL even if there is an error */ +#define JSON_NOCACHE 0x04 /* Do not use the JSON cache */ /************************************************************************** ** Forward references **************************************************************************/ static void jsonReturnStringAsBlob(JsonString*); -static int jsonFuncArgMightBeBinary(sqlite3_value *pJson); -static u32 jsonTranslateBlobToText(const JsonParse*,u32,JsonString*); +static int jsonArgIsJsonb(sqlite3_value *pJson, JsonParse *p); +static u32 jsonTranslateBlobToText(JsonParse*,u32,JsonString*); static void jsonReturnParse(sqlite3_context*,JsonParse*); static JsonParse *jsonParseFuncArg(sqlite3_context*,sqlite3_value*,u32); static void jsonParseFree(JsonParse*); @@ -206572,7 +214250,7 @@ static int jsonCacheInsert( ** most-recently used entry if it isn't so already. ** ** The JsonParse object returned still belongs to the Cache and might -** be deleted at any moment. If the caller whants the JsonParse to +** be deleted at any moment. If the caller wants the JsonParse to ** linger, it needs to increment the nPJRef reference counter. */ static JsonParse *jsonCacheSearch( @@ -206657,6 +214335,15 @@ static void jsonStringOom(JsonString *p){ jsonStringReset(p); } +/* Report JSON nested too deep +*/ +static void jsonStringTooDeep(JsonString *p){ + p->eErr |= JSTRING_TOODEEP; + assert( p->pCtx!=0 ); + sqlite3_result_error(p->pCtx, "JSON nested too deep", -1); + jsonStringReset(p); +} + /* Enlarge pJson->zBuf so that it can hold at least N more bytes. ** Return zero on success. Return non-zero on an OOM error */ @@ -206896,7 +214583,7 @@ static void jsonAppendSqlValue( break; } case SQLITE_FLOAT: { - jsonPrintf(100, p, "%!0.15g", sqlite3_value_double(pValue)); + jsonPrintf(100, p, "%!0.17g", sqlite3_value_double(pValue)); break; } case SQLITE_INTEGER: { @@ -206916,11 +214603,9 @@ static void jsonAppendSqlValue( break; } default: { - if( jsonFuncArgMightBeBinary(pValue) ){ - JsonParse px; - memset(&px, 0, sizeof(px)); - px.aBlob = (u8*)sqlite3_value_blob(pValue); - px.nBlob = sqlite3_value_bytes(pValue); + JsonParse px; + memset(&px, 0, sizeof(px)); + if( jsonArgIsJsonb(pValue, &px) ){ jsonTranslateBlobToText(&px, 0, p); }else if( p->eErr==0 ){ sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1); @@ -206948,6 +214633,7 @@ static void jsonReturnString( ){ assert( (pParse!=0)==(ctx!=0) ); assert( ctx==0 || ctx==p->pCtx ); + jsonStringTerminate(p); if( p->eErr==0 ){ int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(p->pCtx)); if( flags & JSON_BLOB ){ @@ -206955,7 +214641,7 @@ static void jsonReturnString( }else if( p->bStatic ){ sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed, SQLITE_TRANSIENT, SQLITE_UTF8); - }else if( jsonStringTerminate(p) ){ + }else{ if( pParse && pParse->bJsonIsRCStr==0 && pParse->nBlobAlloc>0 ){ int rc; pParse->zJson = sqlite3RCStrRef(p->zBuf); @@ -206971,11 +214657,11 @@ static void jsonReturnString( sqlite3_result_text64(p->pCtx, sqlite3RCStrRef(p->zBuf), p->nUsed, sqlite3RCStrUnref, SQLITE_UTF8); - }else{ - sqlite3_result_error_nomem(p->pCtx); } }else if( p->eErr & JSTRING_OOM ){ sqlite3_result_error_nomem(p->pCtx); + }else if( p->eErr & JSTRING_TOODEEP ){ + /* error already in p->pCtx */ }else if( p->eErr & JSTRING_MALFORMED ){ sqlite3_result_error(p->pCtx, "malformed JSON", -1); } @@ -207237,9 +214923,9 @@ static void jsonWrongNumArgs( ** ** Return the number of errors. */ -static int jsonBlobExpand(JsonParse *pParse, u32 N){ +static int jsonBlobExpand(JsonParse *pParse, u64 N){ u8 *aNew; - u32 t; + u64 t; assert( N>pParse->nBlobAlloc ); if( pParse->nBlobAlloc==0 ){ t = 100; @@ -207249,8 +214935,9 @@ static int jsonBlobExpand(JsonParse *pParse, u32 N){ if( t<N ) t = N+100; aNew = sqlite3DbRealloc(pParse->db, pParse->aBlob, t); if( aNew==0 ){ pParse->oom = 1; return 1; } + assert( t<0x7fffffff ); pParse->aBlob = aNew; - pParse->nBlobAlloc = t; + pParse->nBlobAlloc = (u32)t; return 0; } @@ -207264,7 +214951,7 @@ static int jsonBlobExpand(JsonParse *pParse, u32 N){ */ static int jsonBlobMakeEditable(JsonParse *pParse, u32 nExtra){ u8 *aOld; - u32 nSize; + u64 nSize; assert( !pParse->bReadOnly ); if( pParse->oom ) return 0; if( pParse->nBlobAlloc>0 ) return 1; @@ -207285,7 +214972,7 @@ static SQLITE_NOINLINE void jsonBlobExpandAndAppendOneByte( JsonParse *pParse, u8 c ){ - jsonBlobExpand(pParse, pParse->nBlob+1); + jsonBlobExpand(pParse, (u64)pParse->nBlob+1); if( pParse->oom==0 ){ assert( pParse->nBlob+1<=pParse->nBlobAlloc ); pParse->aBlob[pParse->nBlob++] = c; @@ -207305,19 +214992,19 @@ static void jsonBlobAppendOneByte(JsonParse *pParse, u8 c){ /* Slow version of jsonBlobAppendNode() that first resizes the ** pParse->aBlob structure. */ -static void jsonBlobAppendNode(JsonParse*,u8,u32,const void*); +static void jsonBlobAppendNode(JsonParse*,u8,u64,const void*); static SQLITE_NOINLINE void jsonBlobExpandAndAppendNode( JsonParse *pParse, u8 eType, - u32 szPayload, + u64 szPayload, const void *aPayload ){ - if( jsonBlobExpand(pParse, pParse->nBlob+szPayload+9) ) return; + if( jsonBlobExpand(pParse, (u64)pParse->nBlob+(u64)szPayload+9) ) return; jsonBlobAppendNode(pParse, eType, szPayload, aPayload); } -/* Append an node type byte together with the payload size and +/* Append a node type byte together with the payload size and ** possibly also the payload. ** ** If aPayload is not NULL, then it is a pointer to the payload which @@ -207329,7 +215016,7 @@ static SQLITE_NOINLINE void jsonBlobExpandAndAppendNode( static void jsonBlobAppendNode( JsonParse *pParse, /* The JsonParse object under construction */ u8 eType, /* Node type. One of JSONB_* */ - u32 szPayload, /* Number of bytes of payload */ + u64 szPayload, /* Number of bytes of payload */ const void *aPayload /* The payload. Might be NULL */ ){ u8 *a; @@ -207386,8 +215073,10 @@ static int jsonBlobChangePayloadSize( nExtra = 1; }else if( szType==13 ){ nExtra = 2; - }else{ + }else if( szType==14 ){ nExtra = 4; + }else{ + nExtra = 8; } if( szPayload<=11 ){ nNeeded = 0; @@ -207400,7 +215089,7 @@ static int jsonBlobChangePayloadSize( } delta = nNeeded - nExtra; if( delta ){ - u32 newSize = pParse->nBlob + delta; + u64 newSize = (u64)pParse->nBlob + delta; if( delta>0 ){ if( newSize>pParse->nBlobAlloc && jsonBlobExpand(pParse, newSize) ){ return 0; /* OOM error. Error state recorded in pParse->oom. */ @@ -207857,7 +215546,12 @@ static int jsonTranslateTextToBlob(JsonParse *pParse, u32 i){ || c=='n' || c=='r' || c=='t' || (c=='u' && jsonIs4Hex(&z[j+1])) ){ if( opcode==JSONB_TEXT ) opcode = JSONB_TEXTJ; - }else if( c=='\'' || c=='0' || c=='v' || c=='\n' + }else if( c=='\'' || c=='v' || c=='\n' +#ifdef SQLITE_BUG_COMPATIBLE_20250510 + || (c=='0') /* Legacy bug compatible */ +#else + || (c=='0' && !sqlite3Isdigit(z[j+1])) /* Correct implementation */ +#endif || (0xe2==(u8)c && 0x80==(u8)z[j+1] && (0xa8==(u8)z[j+2] || 0xa9==(u8)z[j+2])) || (c=='x' && jsonIs2Hex(&z[j+1])) ){ @@ -208178,12 +215872,8 @@ static int jsonConvertTextToBlob( */ static void jsonReturnStringAsBlob(JsonString *pStr){ JsonParse px; + assert( pStr->eErr==0 ); memset(&px, 0, sizeof(px)); - jsonStringTerminate(pStr); - if( pStr->eErr ){ - sqlite3_result_error_nomem(pStr->pCtx); - return; - } px.zJson = pStr->zBuf; px.nJson = pStr->nUsed; px.db = sqlite3_context_db_handle(pStr->pCtx); @@ -208198,21 +215888,132 @@ static void jsonReturnStringAsBlob(JsonString *pStr){ } } -/* The byte at index i is a node type-code. This routine +/* +** This a helper routine for jsonbPayloadSize() and +** jsonbPayloadSizeSemiInline(). This routine is called using tail +** recursion to handle the (relatively uncommon) cases where the +** the payload size is a 2, 4, or 8 byte integer. +*/ +static u32 jsonbPayloadSizeWide( + const JsonParse *pParse, /* JSON parsing context */ + u32 i, /* Index of the node type-code */ + u32 *pSz, /* Write payload size here */ + u8 x /* pParse->aBlob[i]>>4 */ +){ + u32 sz; + u32 n; + assert( i<pParse->nBlob ); + assert( x==(pParse->aBlob[i]>>4) ); + assert( x>=13 ); + if( x==13 ){ + if( i+2>=pParse->nBlob ){ + *pSz = 0; + return 0; + } + sz = (pParse->aBlob[i+1]<<8) + pParse->aBlob[i+2]; + n = 3; + }else if( x==14 ){ + if( i+4>=pParse->nBlob ){ + *pSz = 0; + return 0; + } + sz = ((u32)pParse->aBlob[i+1]<<24) + (pParse->aBlob[i+2]<<16) + + (pParse->aBlob[i+3]<<8) + pParse->aBlob[i+4]; + n = 5; + }else{ + if( i+8>=pParse->nBlob + || pParse->aBlob[i+1]!=0 + || pParse->aBlob[i+2]!=0 + || pParse->aBlob[i+3]!=0 + || pParse->aBlob[i+4]!=0 + ){ + *pSz = 0; + return 0; + } + sz = ((u32)pParse->aBlob[i+5]<<24) + (pParse->aBlob[i+6]<<16) + + (pParse->aBlob[i+7]<<8) + pParse->aBlob[i+8]; + n = 9; + } + testcase( (i64)i+sz+n > pParse->nBlob ); + testcase( (i64)i+sz+n > pParse->nBlob-pParse->delta + && (i64)i+sz+n > pParse->nBlob ); + testcase( pParse->delta>0 ); + testcase( pParse->delta<0 ); + /* Quirks with -Os and gcov cause the NO_TEST line below to show up as + ** false-positive coverage miss. The testcases() macros above are + ** sufficient to prove that the branch is in fact covered */ + if( (i64)i+sz+n > pParse->nBlob + && (i64)i+sz+n > pParse->nBlob-pParse->delta /*NO_TEST*/ + ){ + *pSz = 0; + return 0; + } + *pSz = sz; + return n; +} + +/* +** This is the main routine for determining the size of a node in JSONB. +** The jsonbPayloadSizeWide() above is a helper. The two routines +** jsonbPayloadSizeInline() and jsonbPayloadSizeSemiInline() below are +** optional optimizations. It is important to keep all these routines in +** sync. Agents reading this code: Help us humans to remember that! +** +** The byte at index i is a node type-code. This routine ** determines the payload size for that node and writes that ** payload size in to *pSz. It returns the offset from i to the ** beginning of the payload. Return 0 on error. */ -static u32 jsonbPayloadSize(const JsonParse *pParse, u32 i, u32 *pSz){ +static u32 jsonbPayloadSize( + const JsonParse *pParse, /* JSON parsing context */ + u32 i, /* Index of the node type-code */ + u32 *pSz /* Write payload size here */ +){ u8 x; u32 sz; u32 n; - if( NEVER(i>pParse->nBlob) ){ + if( i>=pParse->nBlob ){ + *pSz = 0; + return 0; + }else if( (x = pParse->aBlob[i]>>4)<=11 ){ + sz = x; + n = 1; + }else if( x==12 ){ + if( i+1>=pParse->nBlob ){ + *pSz = 0; + return 0; + } + sz = pParse->aBlob[i+1]; + n = 2; + }else{ + return jsonbPayloadSizeWide(pParse, i, pSz, x); + } + if( (i64)i+sz+n > pParse->nBlob + && (i64)i+sz+n > pParse->nBlob-pParse->delta + ){ *pSz = 0; return 0; } - x = pParse->aBlob[i]>>4; - if( x<=11 ){ + *pSz = sz; + return n; +} + +#if SQLITE_USES_INLINE +/* A separate inline version of jsonbPayloadSize(), used in one particulary +** performance-critical place. +*/ +static SQLITE_INLINE u32 jsonbPayloadSizeInline( + const JsonParse *pParse, /* JSON parsing context */ + u32 i, /* Index of the node type-code */ + u32 *pSz /* Write payload size here */ +){ + u8 x; + u32 sz; + u32 n; + if( i>=pParse->nBlob ){ + *pSz = 0; + return 0; + }else if( (x = pParse->aBlob[i]>>4)<=11 ){ sz = x; n = 1; }else if( x==12 ){ @@ -208247,20 +216048,74 @@ static u32 jsonbPayloadSize(const JsonParse *pParse, u32 i, u32 *pSz){ *pSz = 0; return 0; } - sz = (pParse->aBlob[i+5]<<24) + (pParse->aBlob[i+6]<<16) + + sz = ((u32)pParse->aBlob[i+5]<<24) + (pParse->aBlob[i+6]<<16) + (pParse->aBlob[i+7]<<8) + pParse->aBlob[i+8]; n = 9; } if( (i64)i+sz+n > pParse->nBlob && (i64)i+sz+n > pParse->nBlob-pParse->delta ){ - sz = 0; - n = 0; + *pSz = 0; + return 0; } *pSz = sz; return n; } +#else /* if !SQLITE_USES_INLINE */ + /* On compilers that do not support in-lining, just call the original + ** jsonbPayloadSize(). It's slower, but it gets the right answer. */ +# define jsonbPayloadSizeInline(a,b,c) jsonbPayloadSize(a,b,c) +#endif + +#if SQLITE_USES_INLINE +/* A separate inline version of jsonbPayloadSize() that implements the more +** common paths inline but then calls out to a subroutine for the uncommon +** paths. +** +** * It is guaranteed that the i parameter is a valid index for +** pParse->aBlob[]. There is no possibility of running of the end +** of the allocation. +** +** * Large sizes (greater than 255) are uncommon and are handled +** by a subroutine call to the jsonbPayloadSizeWide(). +*/ +static SQLITE_INLINE u32 jsonbPayloadSizeSemiInline( + const JsonParse *pParse, /* JSON parsing context */ + u32 i, /* Index of the node type-code */ + u32 *pSz /* Write payload size here */ +){ + u8 x; + u32 sz; + u32 n; + assert( i<pParse->nBlob ); + if( (x = pParse->aBlob[i]>>4)<=11 ){ + sz = x; + n = 1; + }else if( x==12 ){ + if( i+1>=pParse->nBlob ){ + *pSz = 0; + return 0; + } + sz = pParse->aBlob[i+1]; + n = 2; + }else{ + return jsonbPayloadSizeWide(pParse,i,pSz,x); + } + if( (i64)i+sz+n > pParse->nBlob + && (i64)i+sz+n > pParse->nBlob-pParse->delta + ){ + *pSz = 0; + return 0; + } + *pSz = sz; + return n; +} +#else /* if !SQLITE_USES_INLINE */ + /* On compilers that do not support in-lining, just call the original + ** jsonbPayloadSize(). It's slower, but it gets the right answer. */ +# define jsonbPayloadSizeSemiInline(a,b,c) jsonbPayloadSize(a,b,c) +#endif /* ** Translate the binary JSONB representation of JSON beginning at @@ -208276,13 +216131,13 @@ static u32 jsonbPayloadSize(const JsonParse *pParse, u32 i, u32 *pSz){ ** The pOut->eErr JSTRING_OOM flag is set on a OOM. */ static u32 jsonTranslateBlobToText( - const JsonParse *pParse, /* the complete parse of the JSON */ + JsonParse *pParse, /* the complete parse of the JSON */ u32 i, /* Start rendering at this index */ JsonString *pOut /* Write JSON here */ ){ u32 sz, n, j, iEnd; - n = jsonbPayloadSize(pParse, i, &sz); + n = jsonbPayloadSizeInline(pParse, i, &sz); if( n==0 ){ pOut->eErr |= JSTRING_MALFORMED; return pParse->nBlob+1; @@ -208337,7 +216192,8 @@ static u32 jsonTranslateBlobToText( if( sz==0 ) goto malformed_jsonb; if( zIn[0]=='-' ){ jsonAppendChar(pOut, '-'); - k++; + if( sz<=1 ) goto malformed_jsonb; + k = 1; } if( zIn[k]=='.' ){ jsonAppendChar(pOut, '0'); @@ -208352,9 +216208,12 @@ static u32 jsonTranslateBlobToText( } case JSONB_TEXT: case JSONB_TEXTJ: { - jsonAppendChar(pOut, '"'); - jsonAppendRaw(pOut, (const char*)&pParse->aBlob[i+n], sz); - jsonAppendChar(pOut, '"'); + if( pOut->nUsed+sz+2<=pOut->nAlloc || jsonStringGrow(pOut, sz+2)==0 ){ + pOut->zBuf[pOut->nUsed] = '"'; + memcpy(pOut->zBuf+pOut->nUsed+1,(const char*)&pParse->aBlob[i+n],sz); + pOut->zBuf[pOut->nUsed+sz+1] = '"'; + pOut->nUsed += sz+2; + } break; } case JSONB_TEXT5: { @@ -208397,7 +216256,7 @@ static u32 jsonTranslateBlobToText( jsonAppendChar(pOut, '\''); break; case 'v': - jsonAppendRawNZ(pOut, "\\u0009", 6); + jsonAppendRawNZ(pOut, "\\u000b", 6); break; case 'x': if( sz2<4 ){ @@ -208423,7 +216282,7 @@ static u32 jsonTranslateBlobToText( break; case 0xe2: /* '\' followed by either U+2028 or U+2029 is ignored as - ** whitespace. Not that in UTF8, U+2028 is 0xe2 0x80 0x29. + ** whitespace. Note that in UTF8, U+2028 is 0xe2 0x80 0x29. ** U+2029 is the same except for the last byte */ if( sz2<4 || 0x80!=(u8)zIn[2] @@ -208455,10 +216314,14 @@ static u32 jsonTranslateBlobToText( jsonAppendChar(pOut, '['); j = i+n; iEnd = j+sz; + if( ++pParse->iDepth > JSON_MAX_DEPTH ){ + jsonStringTooDeep(pOut); + } while( j<iEnd && pOut->eErr==0 ){ j = jsonTranslateBlobToText(pParse, j, pOut); jsonAppendChar(pOut, ','); } + pParse->iDepth--; if( j>iEnd ) pOut->eErr |= JSTRING_MALFORMED; if( sz>0 ) jsonStringTrimOneChar(pOut); jsonAppendChar(pOut, ']'); @@ -208469,10 +216332,14 @@ static u32 jsonTranslateBlobToText( jsonAppendChar(pOut, '{'); j = i+n; iEnd = j+sz; + if( ++pParse->iDepth > JSON_MAX_DEPTH ){ + jsonStringTooDeep(pOut); + } while( j<iEnd && pOut->eErr==0 ){ j = jsonTranslateBlobToText(pParse, j, pOut); jsonAppendChar(pOut, (x++ & 1) ? ',' : ':'); } + pParse->iDepth--; if( (x & 1)!=0 || j>iEnd ) pOut->eErr |= JSTRING_MALFORMED; if( sz>0 ) jsonStringTrimOneChar(pOut); jsonAppendChar(pOut, '}'); @@ -208529,7 +216396,7 @@ static u32 jsonTranslateBlobToPrettyText( u32 i /* Start rendering at this index */ ){ u32 sz, n, j, iEnd; - const JsonParse *pParse = pPretty->pParse; + JsonParse *pParse = pPretty->pParse; JsonString *pOut = pPretty->pOut; n = jsonbPayloadSize(pParse, i, &sz); if( n==0 ){ @@ -208544,10 +216411,16 @@ static u32 jsonTranslateBlobToPrettyText( if( j<iEnd ){ jsonAppendChar(pOut, '\n'); pPretty->nIndent++; + if( pPretty->nIndent >= JSON_MAX_DEPTH ){ + jsonStringTooDeep(pOut); + } while( pOut->eErr==0 ){ jsonPrettyIndent(pPretty); j = jsonTranslateBlobToPrettyText(pPretty, j); - if( j>=iEnd ) break; + if( j>=iEnd ){ + if( j>iEnd ) pOut->eErr |= JSTRING_MALFORMED; + break; + } jsonAppendRawNZ(pOut, ",\n", 2); } jsonAppendChar(pOut, '\n'); @@ -208565,6 +216438,10 @@ static u32 jsonTranslateBlobToPrettyText( if( j<iEnd ){ jsonAppendChar(pOut, '\n'); pPretty->nIndent++; + if( pPretty->nIndent >= JSON_MAX_DEPTH ){ + jsonStringTooDeep(pOut); + } + pParse->iDepth = pPretty->nIndent; while( pOut->eErr==0 ){ jsonPrettyIndent(pPretty); j = jsonTranslateBlobToText(pParse, j, pOut); @@ -208593,33 +216470,6 @@ static u32 jsonTranslateBlobToPrettyText( return i; } - -/* Return true if the input pJson -** -** For performance reasons, this routine does not do a detailed check of the -** input BLOB to ensure that it is well-formed. Hence, false positives are -** possible. False negatives should never occur, however. -*/ -static int jsonFuncArgMightBeBinary(sqlite3_value *pJson){ - u32 sz, n; - const u8 *aBlob; - int nBlob; - JsonParse s; - if( sqlite3_value_type(pJson)!=SQLITE_BLOB ) return 0; - aBlob = sqlite3_value_blob(pJson); - nBlob = sqlite3_value_bytes(pJson); - if( nBlob<1 ) return 0; - if( NEVER(aBlob==0) || (aBlob[0] & 0x0f)>JSONB_OBJECT ) return 0; - memset(&s, 0, sizeof(s)); - s.aBlob = (u8*)aBlob; - s.nBlob = nBlob; - n = jsonbPayloadSize(&s, 0, &sz); - if( n==0 ) return 0; - if( sz+n!=(u32)nBlob ) return 0; - if( (aBlob[0] & 0x0f)<=JSONB_FALSE && sz>0 ) return 0; - return sz+n==(u32)nBlob; -} - /* ** Given that a JSONB_ARRAY object starts at offset i, return ** the number of entries in that array. @@ -208630,7 +216480,7 @@ static u32 jsonbArrayCount(JsonParse *pParse, u32 iRoot){ n = jsonbPayloadSize(pParse, iRoot, &sz); iEnd = iRoot+n+sz; for(i=iRoot+n; n>0 && i<iEnd; i+=sz+n, k++){ - n = jsonbPayloadSize(pParse, i, &sz); + n = jsonbPayloadSizeSemiInline(pParse, i, &sz); } return k; } @@ -208652,6 +216502,82 @@ static void jsonAfterEditSizeAdjust(JsonParse *pParse, u32 iRoot){ pParse->delta += jsonBlobChangePayloadSize(pParse, iRoot, sz); } +/* +** If the JSONB at aIns[0..nIns-1] can be expanded (by denormalizing the +** size field) by d bytes, then write the expansion into aOut[] and +** return true. In this way, an overwrite happens without changing the +** size of the JSONB, which reduces memcpy() operations and also make it +** faster and easier to update the B-Tree entry that contains the JSONB +** in the database. +** +** If the expansion of aIns[] by d bytes cannot be (easily) accomplished +** then return false. +** +** The d parameter is guaranteed to be between 1 and 8. +** +** This routine is an optimization. A correct answer is obtained if it +** always leaves the output unchanged and returns false. +*/ +static int jsonBlobOverwrite( + u8 *aOut, /* Overwrite here */ + const u8 *aIns, /* New content */ + u32 nIns, /* Bytes of new content */ + u32 d /* Need to expand new content by this much */ +){ + u32 szPayload; /* Bytes of payload */ + u32 i; /* New header size, after expansion & a loop counter */ + u8 szHdr; /* Size of header before expansion */ + + /* Lookup table for finding the upper 4 bits of the first byte of the + ** expanded aIns[], based on the size of the expanded aIns[] header: + ** + ** 2 3 4 5 6 7 8 9 */ + static const u8 aType[] = { 0xc0, 0xd0, 0, 0xe0, 0, 0, 0, 0xf0 }; + + if( (aIns[0]&0x0f)<=2 ) return 0; /* Cannot enlarge NULL, true, false */ + switch( aIns[0]>>4 ){ + default: { /* aIns[] header size 1 */ + if( ((1<<d)&0x116)==0 ) return 0; /* d must be 1, 2, 4, or 8 */ + i = d + 1; /* New hdr sz: 2, 3, 5, or 9 */ + szHdr = 1; + break; + } + case 12: { /* aIns[] header size is 2 */ + if( ((1<<d)&0x8a)==0) return 0; /* d must be 1, 3, or 7 */ + i = d + 2; /* New hdr sz: 2, 5, or 9 */ + szHdr = 2; + break; + } + case 13: { /* aIns[] header size is 3 */ + if( d!=2 && d!=6 ) return 0; /* d must be 2 or 6 */ + i = d + 3; /* New hdr sz: 5 or 9 */ + szHdr = 3; + break; + } + case 14: { /* aIns[] header size is 5 */ + if( d!=4 ) return 0; /* d must be 4 */ + i = 9; /* New hdr sz: 9 */ + szHdr = 5; + break; + } + case 15: { /* aIns[] header size is 9 */ + return 0; /* No solution */ + } + } + assert( i>=2 && i<=9 && aType[i-2]!=0 ); + aOut[0] = (aIns[0] & 0x0f) | aType[i-2]; + memcpy(&aOut[i], &aIns[szHdr], nIns-szHdr); + szPayload = nIns - szHdr; + while( 1/*edit-by-break*/ ){ + i--; + aOut[i] = szPayload & 0xff; + if( i==1 ) break; + szPayload >>= 8; + } + assert( (szPayload>>8)==0 ); + return 1; +} + /* ** Modify the JSONB blob at pParse->aBlob by removing nDel bytes of ** content beginning at iDel, and replacing them with nIns bytes of @@ -208673,9 +216599,15 @@ static void jsonBlobEdit( u32 nIns /* Bytes of content to insert */ ){ i64 d = (i64)nIns - (i64)nDel; + assert( pParse->nBlob >= (u64)iDel + (u64)nDel ); + if( d<0 && d>=(-8) && aIns!=0 + && jsonBlobOverwrite(&pParse->aBlob[iDel], aIns, nIns, (int)-d) + ){ + return; + } if( d!=0 ){ if( pParse->nBlob + d > pParse->nBlobAlloc ){ - jsonBlobExpand(pParse, pParse->nBlob+d); + jsonBlobExpand(pParse, (u64)pParse->nBlob+d); if( pParse->oom ) return; } memmove(&pParse->aBlob[iDel+nIns], @@ -208684,7 +216616,9 @@ static void jsonBlobEdit( pParse->nBlob += d; pParse->delta += d; } - if( nIns && aIns ) memcpy(&pParse->aBlob[iDel], aIns, nIns); + if( nIns && aIns ){ + memcpy(&pParse->aBlob[iDel], aIns, nIns); + } } /* @@ -208769,7 +216703,21 @@ static u32 jsonUnescapeOneChar(const char *z, u32 n, u32 *piOut){ case 'r': { *piOut = '\r'; return 2; } case 't': { *piOut = '\t'; return 2; } case 'v': { *piOut = '\v'; return 2; } - case '0': { *piOut = 0; return 2; } + case '0': { + /* JSON5 requires that the \0 escape not be followed by a digit. + ** But SQLite did not enforce this restriction in versions 3.42.0 + ** through 3.49.2. That was a bug. But some applications might have + ** come to depend on that bug. Use the SQLITE_BUG_COMPATIBLE_20250510 + ** option to restore the old buggy behavior. */ +#ifdef SQLITE_BUG_COMPATIBLE_20250510 + /* Legacy bug-compatible behavior */ + *piOut = 0; +#else + /* Correct behavior */ + *piOut = (n>2 && sqlite3Isdigit(z[2])) ? JSON_INVALID_CHAR : 0; +#endif + return 2; + } case '\'': case '"': case '/': @@ -208894,7 +216842,9 @@ static int jsonLabelCompare( */ #define JSON_LOOKUP_ERROR 0xffffffff #define JSON_LOOKUP_NOTFOUND 0xfffffffe -#define JSON_LOOKUP_PATHERROR 0xfffffffd +#define JSON_LOOKUP_NOTARRAY 0xfffffffd +#define JSON_LOOKUP_TOODEEP 0xfffffffc +#define JSON_LOOKUP_PATHERROR 0xfffffffb #define JSON_LOOKUP_ISERROR(x) ((x)>=JSON_LOOKUP_PATHERROR) /* Forward declaration */ @@ -208923,7 +216873,7 @@ static u32 jsonLookupStep(JsonParse*,u32,const char*,u32); static u32 jsonCreateEditSubstructure( JsonParse *pParse, /* The original JSONB that is being edited */ JsonParse *pIns, /* Populate this with the blob data to insert */ - const char *zTail /* Tail of the path that determins substructure */ + const char *zTail /* Tail of the path that determines substructure */ ){ static const u8 emptyObject[] = { JSONB_ARRAY, JSONB_OBJECT }; int rc; @@ -208941,7 +216891,12 @@ static u32 jsonCreateEditSubstructure( pIns->eEdit = pParse->eEdit; pIns->nIns = pParse->nIns; pIns->aIns = pParse->aIns; + pIns->iDepth = pParse->iDepth+1; + if( pIns->iDepth >= JSON_MAX_DEPTH ){ + return JSON_LOOKUP_TOODEEP; + } rc = jsonLookupStep(pIns, 0, zTail, 0); + pParse->iDepth--; pParse->oom |= pIns->oom; } return rc; /* Error code only */ @@ -208958,9 +216913,9 @@ static u32 jsonCreateEditSubstructure( ** Return one of the JSON_LOOKUP error codes if problems are seen. ** ** This routine will also modify the blob. If pParse->eEdit is one of -** JEDIT_DEL, JEDIT_REPL, JEDIT_INS, or JEDIT_SET, then changes might be -** made to the selected value. If an edit is performed, then the return -** value does not necessarily point to the select element. If an edit +** JEDIT_DEL, JEDIT_REPL, JEDIT_INS, JEDIT_SET, or JEDIT_AINS, then changes +** might be made to the selected value. If an edit is performed, then the +** return value does not necessarily point to the select element. If an edit ** is performed, the return value is only useful for detecting error ** conditions. */ @@ -208986,6 +216941,13 @@ static u32 jsonLookupStep( jsonBlobEdit(pParse, iRoot, sz, 0, 0); }else if( pParse->eEdit==JEDIT_INS ){ /* Already exists, so json_insert() is a no-op */ + }else if( pParse->eEdit==JEDIT_AINS ){ + /* json_array_insert() */ + if( zPath[-1]!=']' ){ + return JSON_LOOKUP_NOTARRAY; + }else{ + jsonBlobEdit(pParse, iRoot, 0, pParse->aIns, pParse->nIns); + } }else{ /* json_set() or json_replace() */ jsonBlobEdit(pParse, iRoot, sz, pParse->aIns, pParse->nIns); @@ -209028,7 +216990,7 @@ static u32 jsonLookupStep( const char *zLabel; x = pParse->aBlob[j] & 0x0f; if( x<JSONB_TEXT || x>JSONB_TEXTRAW ) return JSON_LOOKUP_ERROR; - n = jsonbPayloadSize(pParse, j, &sz); + n = jsonbPayloadSizeSemiInline(pParse, j, &sz); if( n==0 ) return JSON_LOOKUP_ERROR; k = j+n; /* k is the index of the label text */ if( k+sz>=iEnd ) return JSON_LOOKUP_ERROR; @@ -209040,13 +217002,17 @@ static u32 jsonLookupStep( n = jsonbPayloadSize(pParse, v, &sz); if( n==0 || v+n+sz>iEnd ) return JSON_LOOKUP_ERROR; assert( j>0 ); + if( ++pParse->iDepth >= JSON_MAX_DEPTH ){ + return JSON_LOOKUP_TOODEEP; + } rc = jsonLookupStep(pParse, v, &zPath[i], j); + pParse->iDepth--; if( pParse->delta ) jsonAfterEditSizeAdjust(pParse, iRoot); return rc; } j = k+sz; if( ((pParse->aBlob[j])&0x0f)>JSONB_OBJECT ) return JSON_LOOKUP_ERROR; - n = jsonbPayloadSize(pParse, j, &sz); + n = jsonbPayloadSizeSemiInline(pParse, j, &sz); if( n==0 ) return JSON_LOOKUP_ERROR; j += n+sz; } @@ -209057,6 +217023,10 @@ static u32 jsonLookupStep( JsonParse ix; /* Header of the label to be inserted */ testcase( pParse->eEdit==JEDIT_INS ); testcase( pParse->eEdit==JEDIT_SET ); + testcase( pParse->eEdit==JEDIT_AINS ); + if( pParse->eEdit==JEDIT_AINS && sqlite3_strglob("*]",&zPath[i])!=0 ){ + return JSON_LOOKUP_NOTARRAY; + } memset(&ix, 0, sizeof(ix)); ix.db = pParse->db; jsonBlobAppendNode(&ix, rawKey?JSONB_TEXTRAW:JSONB_TEXT5, nKey, 0); @@ -209084,28 +217054,32 @@ static u32 jsonLookupStep( return rc; } }else if( zPath[0]=='[' ){ + u64 kk = 0; x = pParse->aBlob[iRoot] & 0x0f; if( x!=JSONB_ARRAY ) return JSON_LOOKUP_NOTFOUND; n = jsonbPayloadSize(pParse, iRoot, &sz); - k = 0; i = 1; while( sqlite3Isdigit(zPath[i]) ){ - k = k*10 + zPath[i] - '0'; + if( kk<0xffffffff ) kk = kk*10 + zPath[i] - '0'; + /* ^^^^^^^^^^--- Allow kk to be bigger than any JSON array so that + ** we get NOTFOUND instead of PATHERROR, without overflowing kk. */ i++; } if( i<2 || zPath[i]!=']' ){ if( zPath[1]=='#' ){ - k = jsonbArrayCount(pParse, iRoot); + kk = jsonbArrayCount(pParse, iRoot); i = 2; if( zPath[2]=='-' && sqlite3Isdigit(zPath[3]) ){ - unsigned int nn = 0; + u64 nn = 0; i = 3; do{ - nn = nn*10 + zPath[i] - '0'; + if( nn<0xffffffff ) nn = nn*10 + zPath[i] - '0'; + /* ^^^^^^^^^^--- Allow nn to be bigger than any JSON array to + ** get NOTFOUND instead of PATHERROR, without overflowing nn. */ i++; }while( sqlite3Isdigit(zPath[i]) ); - if( nn>k ) return JSON_LOOKUP_NOTFOUND; - k -= nn; + if( nn>kk ) return JSON_LOOKUP_NOTFOUND; + kk -= nn; } if( zPath[i]!=']' ){ return JSON_LOOKUP_PATHERROR; @@ -209117,21 +217091,26 @@ static u32 jsonLookupStep( j = iRoot+n; iEnd = j+sz; while( j<iEnd ){ - if( k==0 ){ + if( kk==0 ){ + if( ++pParse->iDepth >= JSON_MAX_DEPTH ){ + return JSON_LOOKUP_TOODEEP; + } rc = jsonLookupStep(pParse, j, &zPath[i+1], 0); + pParse->iDepth--; if( pParse->delta ) jsonAfterEditSizeAdjust(pParse, iRoot); return rc; } - k--; - n = jsonbPayloadSize(pParse, j, &sz); + kk--; + n = jsonbPayloadSizeSemiInline(pParse, j, &sz); if( n==0 ) return JSON_LOOKUP_ERROR; j += n+sz; } if( j>iEnd ) return JSON_LOOKUP_ERROR; - if( k>0 ) return JSON_LOOKUP_NOTFOUND; + if( kk>0 ) return JSON_LOOKUP_NOTFOUND; if( pParse->eEdit>=JEDIT_INS ){ JsonParse v; testcase( pParse->eEdit==JEDIT_INS ); + testcase( pParse->eEdit==JEDIT_AINS ); testcase( pParse->eEdit==JEDIT_SET ); rc = jsonCreateEditSubstructure(pParse, &v, &zPath[i+1]); if( !JSON_LOOKUP_ISERROR(rc) @@ -209177,19 +217156,27 @@ static void jsonReturnTextJsonFromBlob( ** ** If the value is a primitive, return it as an SQL value. ** If the value is an array or object, return it as either -** JSON text or the BLOB encoding, depending on the JSON_B flag -** on the userdata. +** JSON text or the BLOB encoding, depending on the eMode flag +** as follows: +** +** eMode==0 JSONB if the JSON_B flag is set in userdata or +** text if the JSON_B flag is omitted from userdata. +** +** eMode==1 Text +** +** eMode==2 JSONB */ static void jsonReturnFromBlob( JsonParse *pParse, /* Complete JSON parse tree */ u32 i, /* Index of the node */ sqlite3_context *pCtx, /* Return value for this function */ - int textOnly /* return text JSON. Disregard user-data */ + int eMode /* Format of return: text of JSONB */ ){ u32 n, sz; int rc; sqlite3 *db = sqlite3_context_db_handle(pCtx); + assert( eMode>=0 && eMode<=2 ); n = jsonbPayloadSize(pParse, i, &sz); if( n==0 ){ sqlite3_result_error(pCtx, "malformed JSON", -1); @@ -209230,7 +217217,19 @@ static void jsonReturnFromBlob( rc = sqlite3DecOrHexToI64(z, &iRes); sqlite3DbFree(db, z); if( rc==0 ){ - sqlite3_result_int64(pCtx, bNeg ? -iRes : iRes); + if( iRes<0 ){ + /* A hexadecimal literal with 16 significant digits and with the + ** high-order bit set is a negative integer in SQLite (and hence + ** iRes comes back as negative) but should be interpreted as a + ** positive value if it occurs within JSON. The value is too + ** large to appear as an SQLite integer so it must be converted + ** into floating point. */ + double r; + r = (double)*(sqlite3_uint64*)&iRes; + sqlite3_result_double(pCtx, bNeg ? -r : r); + }else{ + sqlite3_result_int64(pCtx, bNeg ? -iRes : iRes); + } }else if( rc==3 && bNeg ){ sqlite3_result_int64(pCtx, SMALLEST_INT64); }else if( rc==1 ){ @@ -209249,7 +217248,7 @@ static void jsonReturnFromBlob( to_double: z = sqlite3DbStrNDup(db, (const char*)&pParse->aBlob[i+n], (int)sz); if( z==0 ) goto returnfromblob_oom; - rc = sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8); + rc = sqlite3AtoF(z, &r); sqlite3DbFree(db, z); if( rc<=0 ) goto returnfromblob_malformed; sqlite3_result_double(pCtx, r); @@ -209269,7 +217268,7 @@ static void jsonReturnFromBlob( char *zOut; u32 nOut = sz; z = (const char*)&pParse->aBlob[i+n]; - zOut = sqlite3DbMallocRaw(db, nOut+1); + zOut = sqlite3DbMallocRaw(db, ((u64)nOut)+1); if( zOut==0 ) goto returnfromblob_oom; for(iIn=iOut=0; iIn<sz; iIn++){ char c = z[iIn]; @@ -209308,8 +217307,14 @@ static void jsonReturnFromBlob( } case JSONB_ARRAY: case JSONB_OBJECT: { - int flags = textOnly ? 0 : SQLITE_PTR_TO_INT(sqlite3_user_data(pCtx)); - if( flags & JSON_BLOB ){ + if( eMode==0 ){ + if( (SQLITE_PTR_TO_INT(sqlite3_user_data(pCtx)) & JSON_BLOB)!=0 ){ + eMode = 2; + }else{ + eMode = 1; + } + } + if( eMode==2 ){ sqlite3_result_blob(pCtx, &pParse->aBlob[i], sz+n, SQLITE_TRANSIENT); }else{ jsonReturnTextJsonFromBlob(pCtx, &pParse->aBlob[i], sz+n); @@ -209364,10 +217369,7 @@ static int jsonFunctionArgToBlob( return 0; } case SQLITE_BLOB: { - if( jsonFuncArgMightBeBinary(pArg) ){ - pParse->aBlob = (u8*)sqlite3_value_blob(pArg); - pParse->nBlob = sqlite3_value_bytes(pArg); - }else{ + if( !jsonArgIsJsonb(pArg, pParse) ){ sqlite3_result_error(ctx, "JSON cannot hold BLOB values", -1); return 1; } @@ -209392,8 +217394,7 @@ static int jsonFunctionArgToBlob( break; } case SQLITE_FLOAT: { - double r = sqlite3_value_double(pArg); - if( NEVER(sqlite3IsNaN(r)) ){ + if( NEVER(sqlite3IsNaN(sqlite3_value_double(pArg))) ){ jsonBlobAppendNode(pParse, JSONB_NULL, 0, 0); }else{ int n = sqlite3_value_bytes(pArg); @@ -209426,16 +217427,35 @@ static int jsonFunctionArgToBlob( } /* -** Generate a bad path error. +** Generate a path error. +** +** The specifics of the error are determined by the rc argument. +** +** rc error +** ----------------- ---------------------- +** JSON_LOOKUP_ARRAY "not an array" +** JSON_LOOKUP_TOODEEP "JSON nested too deep" +** JSON_LOOKUP_ERROR "malformed JSON" +** otherwise... "bad JSON path" ** ** If ctx is not NULL then push the error message into ctx and return NULL. ** If ctx is NULL, then return the text of the error message. */ static char *jsonBadPathError( sqlite3_context *ctx, /* The function call containing the error */ - const char *zPath /* The path with the problem */ + const char *zPath, /* The path with the problem */ + int rc /* Maybe JSON_LOOKUP_NOTARRAY */ ){ - char *zMsg = sqlite3_mprintf("bad JSON path: %Q", zPath); + char *zMsg; + if( rc==(int)JSON_LOOKUP_NOTARRAY ){ + zMsg = sqlite3_mprintf("not an array element: %Q", zPath); + }else if( rc==(int)JSON_LOOKUP_ERROR ){ + zMsg = sqlite3_mprintf("malformed JSON"); + }else if( rc==(int)JSON_LOOKUP_TOODEEP ){ + zMsg = sqlite3_mprintf("JSON path too deep"); + }else{ + zMsg = sqlite3_mprintf("bad JSON path: %Q", zPath); + } if( ctx==0 ) return zMsg; if( zMsg ){ sqlite3_result_error(ctx, zMsg, -1); @@ -209447,18 +217467,18 @@ static char *jsonBadPathError( } /* argv[0] is a BLOB that seems likely to be a JSONB. Subsequent -** arguments come in parse where each pair contains a JSON path and +** arguments come in pairs where each pair contains a JSON path and ** content to insert or set at that patch. Do the updates ** and return the result. ** ** The specific operation is determined by eEdit, which can be one -** of JEDIT_INS, JEDIT_REPL, or JEDIT_SET. +** of JEDIT_INS, JEDIT_REPL, JEDIT_SET, or JEDIT_AINS. */ static void jsonInsertIntoBlob( sqlite3_context *ctx, int argc, sqlite3_value **argv, - int eEdit /* JEDIT_INS, JEDIT_REPL, or JEDIT_SET */ + int eEdit /* JEDIT_INS, JEDIT_REPL, JEDIT_SET, JEDIT_AINS */ ){ int i; u32 rc = 0; @@ -209495,6 +217515,7 @@ static void jsonInsertIntoBlob( p->nIns = ax.nBlob; p->aIns = ax.aBlob; p->delta = 0; + p->iDepth = 0; rc = jsonLookupStep(p, 0, zPath+1, 0); } jsonParseReset(&ax); @@ -209507,38 +217528,53 @@ static void jsonInsertIntoBlob( jsonInsertIntoBlob_patherror: jsonParseFree(p); - if( rc==JSON_LOOKUP_ERROR ){ - sqlite3_result_error(ctx, "malformed JSON", -1); - }else{ - jsonBadPathError(ctx, zPath); - } + jsonBadPathError(ctx, zPath, rc); return; } /* ** If pArg is a blob that seems like a JSONB blob, then initialize ** p to point to that JSONB and return TRUE. If pArg does not seem like -** a JSONB blob, then return FALSE; -** -** This routine is only called if it is already known that pArg is a -** blob. The only open question is whether or not the blob appears -** to be a JSONB blob. +** a JSONB blob, then return FALSE. +** +** For small BLOBs (having no more than 7 bytes of payload) a full +** validity check is done. So for small BLOBs this routine only returns +** true if the value is guaranteed to be a valid JSONB. For larger BLOBs +** (8 byte or more of payload) only the size of the outermost element is +** checked to verify that the BLOB is superficially valid JSONB. +** +** A full JSONB validation is done on smaller BLOBs because those BLOBs might +** also be text JSON that has been incorrectly cast into a BLOB. +** (See tag-20240123-a and https://sqlite.org/forum/forumpost/012136abd5) +** If the BLOB is 9 bytes are larger, then it is not possible for the +** superficial size check done here to pass if the input is really text +** JSON so we do not need to look deeper in that case. +** +** Why we only need to do full JSONB validation for smaller BLOBs: +** +** The first byte of valid JSON text must be one of: '{', '[', '"', ' ', '\n', +** '\r', '\t', '-', or a digit '0' through '9'. Of these, only a subset +** can also be the first byte of JSONB: '{', '[', and digits '3' +** through '9'. In every one of those cases, the payload size is 7 bytes +** or less. So if we do full JSONB validation for every BLOB where the +** payload is less than 7 bytes, we will never get a false positive for +** JSONB on an input that is really text JSON. */ static int jsonArgIsJsonb(sqlite3_value *pArg, JsonParse *p){ u32 n, sz = 0; + u8 c; + if( sqlite3_value_type(pArg)!=SQLITE_BLOB ) return 0; p->aBlob = (u8*)sqlite3_value_blob(pArg); p->nBlob = (u32)sqlite3_value_bytes(pArg); - if( p->nBlob==0 ){ - p->aBlob = 0; - return 0; - } - if( NEVER(p->aBlob==0) ){ - return 0; - } - if( (p->aBlob[0] & 0x0f)<=JSONB_OBJECT + if( p->nBlob>0 + && ALWAYS(p->aBlob!=0) + && ((c = p->aBlob[0]) & 0x0f)<=JSONB_OBJECT && (n = jsonbPayloadSize(p, 0, &sz))>0 && sz+n==p->nBlob - && ((p->aBlob[0] & 0x0f)>JSONB_FALSE || sz==0) + && ((c & 0x0f)>JSONB_FALSE || sz==0) + && (sz>7 + || (c!=0x7b && c!=0x5b && !sqlite3Isdigit(c)) + || jsonbValidityCheck(p, 0, p->nBlob, 1)==0) ){ return 1; } @@ -209578,7 +217614,9 @@ static JsonParse *jsonParseFuncArg( if( eType==SQLITE_NULL ){ return 0; } - pFromCache = jsonCacheSearch(ctx, pArg); + if( (flgs & JSON_NOCACHE)==0 ){ + pFromCache = jsonCacheSearch(ctx, pArg); + } if( pFromCache ){ pFromCache->nJPRef++; if( (flgs & JSON_EDITABLE)==0 ){ @@ -209616,7 +217654,7 @@ static JsonParse *jsonParseFuncArg( ** JSON functions were suppose to work. From the beginning, blob was ** reserved for expansion and a blob value should have raised an error. ** But it did not, due to a bug. And many applications came to depend - ** upon this buggy behavior, espeically when using the CLI and reading + ** upon this buggy behavior, especially when using the CLI and reading ** JSON text using readfile(), which returns a blob. For this reason ** we will continue to support the bug moving forward. ** See for example https://sqlite.org/forum/forumpost/012136abd5292b8d @@ -209932,10 +217970,8 @@ static void jsonArrayLengthFunc( if( JSON_LOOKUP_ISERROR(i) ){ if( i==JSON_LOOKUP_NOTFOUND ){ /* no-op */ - }else if( i==JSON_LOOKUP_PATHERROR ){ - jsonBadPathError(ctx, zPath); }else{ - sqlite3_result_error(ctx, "malformed JSON", -1); + jsonBadPathError(ctx, zPath, i); } eErr = 1; i = 0; @@ -210038,7 +218074,7 @@ static void jsonExtractFunc( j = jsonLookupStep(p, 0, jx.zBuf, 0); jsonStringReset(&jx); }else{ - jsonBadPathError(ctx, zPath); + jsonBadPathError(ctx, zPath, 0); goto json_extract_error; } if( j<p->nBlob ){ @@ -210069,11 +218105,8 @@ static void jsonExtractFunc( jsonAppendSeparator(&jx); jsonAppendRawNZ(&jx, "null", 4); } - }else if( j==JSON_LOOKUP_ERROR ){ - sqlite3_result_error(ctx, "malformed JSON", -1); - goto json_extract_error; }else{ - jsonBadPathError(ctx, zPath); + jsonBadPathError(ctx, zPath, j); goto json_extract_error; } } @@ -210097,6 +218130,7 @@ static void jsonExtractFunc( #define JSON_MERGE_BADTARGET 1 /* Malformed TARGET blob */ #define JSON_MERGE_BADPATCH 2 /* Malformed PATCH blob */ #define JSON_MERGE_OOM 3 /* Out-of-memory condition */ +#define JSON_MERGE_TOODEEP 4 /* Nested too deep */ /* ** RFC-7396 MergePatch for two JSONB blobs. @@ -210148,7 +218182,8 @@ static int jsonMergePatch( JsonParse *pTarget, /* The JSON parser that contains the TARGET */ u32 iTarget, /* Index of TARGET in pTarget->aBlob[] */ const JsonParse *pPatch, /* The PATCH */ - u32 iPatch /* Index of PATCH in pPatch->aBlob[] */ + u32 iPatch, /* Index of PATCH in pPatch->aBlob[] */ + u32 iDepth /* Nesting depth */ ){ u8 x; /* Type of a single node */ u32 n, sz=0; /* Return values from jsonbPayloadSize() */ @@ -210257,7 +218292,8 @@ static int jsonMergePatch( /* Algorithm line 12 */ int rc, savedDelta = pTarget->delta; pTarget->delta = 0; - rc = jsonMergePatch(pTarget, iTValue, pPatch, iPValue); + if( iDepth>=JSON_MAX_DEPTH ) return JSON_MERGE_TOODEEP; + rc = jsonMergePatch(pTarget, iTValue, pPatch, iPValue, iDepth+1); if( rc ) return rc; pTarget->delta += savedDelta; } @@ -210278,7 +218314,8 @@ static int jsonMergePatch( pTarget->aBlob[iTEnd+szNew] = 0x00; savedDelta = pTarget->delta; pTarget->delta = 0; - rc = jsonMergePatch(pTarget, iTEnd+szNew,pPatch,iPValue); + if( iDepth>=JSON_MAX_DEPTH ) return JSON_MERGE_TOODEEP; + rc = jsonMergePatch(pTarget, iTEnd+szNew,pPatch,iPValue,iDepth+1); if( rc ) return rc; pTarget->delta += savedDelta; } @@ -210309,11 +218346,13 @@ static void jsonPatchFunc( if( pTarget==0 ) return; pPatch = jsonParseFuncArg(ctx, argv[1], 0); if( pPatch ){ - rc = jsonMergePatch(pTarget, 0, pPatch, 0); + rc = jsonMergePatch(pTarget, 0, pPatch, 0, 0); if( rc==JSON_MERGE_OK ){ jsonReturnParse(ctx, pTarget); }else if( rc==JSON_MERGE_OOM ){ sqlite3_result_error_nomem(ctx); + }else if( rc==JSON_MERGE_TOODEEP ){ + sqlite3_result_error(ctx, "JSON nested too deep", -1); }else{ sqlite3_result_error(ctx, "malformed JSON", -1); } @@ -210401,10 +218440,8 @@ static void jsonRemoveFunc( if( JSON_LOOKUP_ISERROR(rc) ){ if( rc==JSON_LOOKUP_NOTFOUND ){ continue; /* No-op */ - }else if( rc==JSON_LOOKUP_PATHERROR ){ - jsonBadPathError(ctx, zPath); }else{ - sqlite3_result_error(ctx, "malformed JSON", -1); + jsonBadPathError(ctx, zPath, rc); } goto json_remove_done; } @@ -210414,7 +218451,7 @@ static void jsonRemoveFunc( return; json_remove_patherror: - jsonBadPathError(ctx, zPath); + jsonBadPathError(ctx, zPath, 0); json_remove_done: jsonParseFree(p); @@ -210458,16 +218495,18 @@ static void jsonSetFunc( int argc, sqlite3_value **argv ){ - int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx)); - int bIsSet = (flags&JSON_ISSET)!=0; + int eInsType = JSON_INSERT_TYPE(flags); + static const char *azInsType[] = { "insert", "set", "array_insert" }; + static const u8 aEditType[] = { JEDIT_INS, JEDIT_SET, JEDIT_AINS }; if( argc<1 ) return; + assert( eInsType>=0 && eInsType<=2 ); if( (argc&1)==0 ) { - jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert"); + jsonWrongNumArgs(ctx, azInsType[eInsType]); return; } - jsonInsertIntoBlob(ctx, argc, argv, bIsSet ? JEDIT_SET : JEDIT_INS); + jsonInsertIntoBlob(ctx, argc, argv, aEditType[eInsType]); } /* @@ -210492,17 +218531,15 @@ static void jsonTypeFunc( zPath = (const char*)sqlite3_value_text(argv[1]); if( zPath==0 ) goto json_type_done; if( zPath[0]!='$' ){ - jsonBadPathError(ctx, zPath); + jsonBadPathError(ctx, zPath, 0); goto json_type_done; } i = jsonLookupStep(p, 0, zPath+1, 0); if( JSON_LOOKUP_ISERROR(i) ){ if( i==JSON_LOOKUP_NOTFOUND ){ /* no-op */ - }else if( i==JSON_LOOKUP_PATHERROR ){ - jsonBadPathError(ctx, zPath); }else{ - sqlite3_result_error(ctx, "malformed JSON", -1); + jsonBadPathError(ctx, zPath, i); } goto json_type_done; } @@ -210631,21 +218668,17 @@ static void jsonValidFunc( return; } case SQLITE_BLOB: { - if( jsonFuncArgMightBeBinary(argv[0]) ){ + JsonParse py; + memset(&py, 0, sizeof(py)); + if( jsonArgIsJsonb(argv[0], &py) ){ if( flags & 0x04 ){ /* Superficial checking only - accomplished by the - ** jsonFuncArgMightBeBinary() call above. */ + ** jsonArgIsJsonb() call above. */ res = 1; }else if( flags & 0x08 ){ /* Strict checking. Check by translating BLOB->TEXT->BLOB. If ** no errors occur, call that a "strict check". */ - JsonParse px; - u32 iErr; - memset(&px, 0, sizeof(px)); - px.aBlob = (u8*)sqlite3_value_blob(argv[0]); - px.nBlob = sqlite3_value_bytes(argv[0]); - iErr = jsonbValidityCheck(&px, 0, px.nBlob, 1); - res = iErr==0; + res = 0==jsonbValidityCheck(&py, 0, py.nBlob, 1); } break; } @@ -210658,7 +218691,7 @@ static void jsonValidFunc( if( (flags & 0x3)==0 ) break; memset(&px, 0, sizeof(px)); - p = jsonParseFuncArg(ctx, argv[0], JSON_KEEPERROR); + p = jsonParseFuncArg(ctx, argv[0], JSON_KEEPERROR|JSON_NOCACHE); if( p ){ if( p->oom ){ sqlite3_result_error_nomem(ctx); @@ -210703,9 +218736,7 @@ static void jsonErrorFunc( UNUSED_PARAMETER(argc); memset(&s, 0, sizeof(s)); s.db = sqlite3_context_db_handle(ctx); - if( jsonFuncArgMightBeBinary(argv[0]) ){ - s.aBlob = (u8*)sqlite3_value_blob(argv[0]); - s.nBlob = sqlite3_value_bytes(argv[0]); + if( jsonArgIsJsonb(argv[0], &s) ){ iErrPos = (i64)jsonbValidityCheck(&s, 0, s.nBlob, 1); }else{ s.zJson = (char*)sqlite3_value_text(argv[0]); @@ -210762,12 +218793,12 @@ static void jsonArrayStep( } static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){ JsonString *pStr; + int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx)); pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); if( pStr ){ - int flags; pStr->pCtx = ctx; - jsonAppendChar(pStr, ']'); - flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx)); + jsonAppendRawNZ(pStr, "]", 2); + jsonStringTrimOneChar(pStr); if( pStr->eErr ){ jsonReturnString(pStr, 0, 0); return; @@ -210788,6 +218819,9 @@ static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){ sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT); jsonStringTrimOneChar(pStr); } + }else if( flags & JSON_BLOB ){ + static const u8 emptyArray = 0x0b; + sqlite3_result_blob(ctx, &emptyArray, 1, SQLITE_STATIC); }else{ sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC); } @@ -210821,11 +218855,9 @@ static void jsonGroupInverse( UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); -#ifdef NEVER /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will ** always have been called to initialize it */ if( NEVER(!pStr) ) return; -#endif z = pStr->zBuf; for(i=1; i<pStr->nUsed && ((c = z[i])!=',' || inStr || nNest); i++){ if( c=='"' ){ @@ -210854,6 +218886,13 @@ static void jsonGroupInverse( ** json_group_obj(NAME,VALUE) ** ** Return a JSON object composed of all names and values in the aggregate. +** +** Rows for which NAME is NULL do not result in a new entry. However, we +** do initially insert a "@" entry into the growing string for each null entry +** and change the first character of the string to "@" to signal that the +** string contains null entries. The "@" markers are needed in order to +** correctly process xInverse() requests. The initial "@" is converted +** back into "{" and the "@" null values are removed by jsonObjectCompute(). */ static void jsonObjectStep( sqlite3_context *ctx, @@ -210866,6 +218905,8 @@ static void jsonObjectStep( UNUSED_PARAMETER(argc); pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr)); if( pStr ){ + z = (const char*)sqlite3_value_text(argv[0]); + n = sqlite3Strlen30(z); if( pStr->zBuf==0 ){ jsonStringInit(pStr, ctx); jsonAppendChar(pStr, '{'); @@ -210873,32 +218914,79 @@ static void jsonObjectStep( jsonAppendChar(pStr, ','); } pStr->pCtx = ctx; - z = (const char*)sqlite3_value_text(argv[0]); - n = sqlite3Strlen30(z); - jsonAppendString(pStr, z, n); - jsonAppendChar(pStr, ':'); - jsonAppendSqlValue(pStr, argv[1]); + if( z!=0 ){ + jsonAppendString(pStr, z, n); + jsonAppendChar(pStr, ':'); + jsonAppendSqlValue(pStr, argv[1]); + }else{ + pStr->zBuf[0] = '@'; + jsonAppendRawNZ(pStr, "@", 1); + } } } static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){ JsonString *pStr; + int flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx)); pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0); if( pStr ){ - int flags; - jsonAppendChar(pStr, '}'); + JsonString *pOgStr = pStr; + JsonString tmpStr; + jsonAppendRawNZ(pOgStr, "}", 2); /* Ensure it is zero-terminated */ + jsonStringTrimOneChar(pOgStr); /* Remove the zero terminator */ pStr->pCtx = ctx; - flags = SQLITE_PTR_TO_INT(sqlite3_user_data(ctx)); if( pStr->eErr ){ jsonReturnString(pStr, 0, 0); return; - }else if( flags & JSON_BLOB ){ + } + if( pStr->zBuf[0]!='{' ){ + /* The string contains null entries that need to be removed */ + u64 i, j; + int inStr = 0; + if( !isFinal ){ + /* Work with a temporary copy of the string if this is not the + ** final result */ + jsonStringInit(&tmpStr, ctx); + jsonAppendRawNZ(&tmpStr, pStr->zBuf, pStr->nUsed+1); + pStr = &tmpStr; + if( pStr->eErr ){ + jsonReturnString(pStr, 0, 0); + return; + } + jsonStringTrimOneChar(pStr); /* Remove zero terminator */ + } + /* Fix up the string by changing the initial "@" flag back to + ** to "{" and removing all subsequence "@" entries, with their + ** associated comma delimeters. */ + pStr->zBuf[0] = '{'; + for(i=j=1; i<pStr->nUsed; i++){ + char c = pStr->zBuf[i]; + if( c=='"' ){ + inStr = !inStr; + pStr->zBuf[j++] = '"'; + }else if( c=='\\' ){ + pStr->zBuf[j++] = '\\'; + pStr->zBuf[j++] = pStr->zBuf[++i]; + }else if( c=='@' && !inStr ){ + assert( i+1<pStr->nUsed ); + if( pStr->zBuf[i+1]==',' ){ + i++; + }else if( pStr->zBuf[j-1]==',' ){ + j--; + } + }else{ + pStr->zBuf[j++] = c; + } + } + pStr->zBuf[j] = 0; /* Restore zero terminator */ + pStr->nUsed = j; /* Truncate the string */ + } + if( flags & JSON_BLOB ){ jsonReturnStringAsBlob(pStr); if( isFinal ){ if( !pStr->bStatic ) sqlite3RCStrUnref(pStr->zBuf); }else{ - jsonStringTrimOneChar(pStr); + jsonStringTrimOneChar(pOgStr); } - return; }else if( isFinal ){ sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, pStr->bStatic ? SQLITE_TRANSIENT : @@ -210906,8 +218994,12 @@ static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){ pStr->bStatic = 1; }else{ sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT); - jsonStringTrimOneChar(pStr); + jsonStringTrimOneChar(pOgStr); } + if( pStr!=pOgStr ) jsonStringReset(pStr); + }else if( flags & JSON_BLOB ){ + static const unsigned char emptyObject = 0x0c; + sqlite3_result_blob(ctx, &emptyObject, 1, SQLITE_STATIC); }else{ sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC); } @@ -210944,6 +219036,7 @@ struct JsonEachCursor { u32 nRoot; /* Size of the root path in bytes */ u8 eType; /* Type of the container for element i */ u8 bRecursive; /* True for json_tree(). False for json_each() */ + u8 eMode; /* 1 for json_each(). 2 for jsonb_each() */ u32 nParent; /* Current nesting depth */ u32 nParentAlloc; /* Space allocated for aParent[] */ JsonParent *aParent; /* Parent elements of i */ @@ -210955,6 +219048,8 @@ typedef struct JsonEachConnection JsonEachConnection; struct JsonEachConnection { sqlite3_vtab base; /* Base class - must be first */ sqlite3 *db; /* Database connection */ + u8 eMode; /* 1 for json_each(). 2 for jsonb_each() */ + u8 bRecursive; /* True for json_tree(). False for json_each() */ }; @@ -210997,6 +219092,8 @@ static int jsonEachConnect( if( pNew==0 ) return SQLITE_NOMEM; sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS); pNew->db = db; + pNew->eMode = argv[0][4]=='b' ? 2 : 1; + pNew->bRecursive = argv[0][4+pNew->eMode]=='t'; } return rc; } @@ -211008,8 +219105,8 @@ static int jsonEachDisconnect(sqlite3_vtab *pVtab){ return SQLITE_OK; } -/* constructor for a JsonEachCursor object for json_each(). */ -static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ +/* constructor for a JsonEachCursor object for json_each()/json_tree(). */ +static int jsonEachOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ JsonEachConnection *pVtab = (JsonEachConnection*)p; JsonEachCursor *pCur; @@ -211017,21 +219114,13 @@ static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ pCur = sqlite3DbMallocZero(pVtab->db, sizeof(*pCur)); if( pCur==0 ) return SQLITE_NOMEM; pCur->db = pVtab->db; + pCur->eMode = pVtab->eMode; + pCur->bRecursive = pVtab->bRecursive; jsonStringZero(&pCur->path); *ppCursor = &pCur->base; return SQLITE_OK; } -/* constructor for a JsonEachCursor object for json_tree(). */ -static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ - int rc = jsonEachOpenEach(p, ppCursor); - if( rc==SQLITE_OK ){ - JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor; - pCur->bRecursive = 1; - } - return rc; -} - /* Reset a JsonEachCursor back to its original state. Free any memory ** held. */ static void jsonEachCursorReset(JsonEachCursor *p){ @@ -211072,7 +219161,9 @@ static int jsonSkipLabel(JsonEachCursor *p){ if( p->eType==JSONB_OBJECT ){ u32 sz = 0; u32 n = jsonbPayloadSize(&p->sParse, p->i, &sz); - return p->i + n + sz; + sz += p->i + n; + if( sz >= p->sParse.nBlob ) sz = p->i; + return sz; }else{ return p->i; } @@ -211111,6 +219202,15 @@ static void jsonAppendPathName(JsonEachCursor *p){ } } +/* Report a "malformed JSON" or OOM error against the cursor. +*/ +static int jsonEachMalformedInput(sqlite3_vtab_cursor *cur){ + sqlite3_free(cur->pVtab->zErrMsg); + cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON"); + jsonEachCursorReset((JsonEachCursor*)cur); + return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM; +} + /* Advance the cursor to the next element for json_tree() */ static int jsonEachNext(sqlite3_vtab_cursor *cur){ JsonEachCursor *p = (JsonEachCursor*)cur; @@ -211122,6 +219222,7 @@ static int jsonEachNext(sqlite3_vtab_cursor *cur){ u32 i = jsonSkipLabel(p); x = p->sParse.aBlob[i] & 0x0f; n = jsonbPayloadSize(&p->sParse, i, &sz); + if( n==0 )return jsonEachMalformedInput(cur); if( x==JSONB_OBJECT || x==JSONB_ARRAY ){ JsonParent *pParent; if( p->nParent>=p->nParentAlloc ){ @@ -211167,6 +219268,7 @@ static int jsonEachNext(sqlite3_vtab_cursor *cur){ u32 n, sz = 0; u32 i = jsonSkipLabel(p); n = jsonbPayloadSize(&p->sParse, i, &sz); + if( n==0 )return jsonEachMalformedInput(cur); p->i = i + n + sz; } if( p->eType==JSONB_ARRAY && p->nParent ){ @@ -211236,7 +219338,7 @@ static int jsonEachColumn( } case JEACH_VALUE: { u32 i = jsonSkipLabel(p); - jsonReturnFromBlob(&p->sParse, i, ctx, 1); + jsonReturnFromBlob(&p->sParse, i, ctx, p->eMode); if( (p->sParse.aBlob[i] & 0x0f)>=JSONB_ARRAY ){ sqlite3_result_subtype(ctx, JSON_SUBTYPE); } @@ -211280,7 +219382,7 @@ static int jsonEachColumn( break; } default: { - sqlite3_result_text(ctx, p->path.zBuf, p->nRoot, SQLITE_STATIC); + sqlite3_result_text(ctx, p->path.zBuf, p->nRoot, SQLITE_TRANSIENT); break; } case JEACH_JSON: { @@ -211390,9 +219492,8 @@ static int jsonEachFilter( memset(&p->sParse, 0, sizeof(p->sParse)); p->sParse.nJPRef = 1; p->sParse.db = p->db; - if( jsonFuncArgMightBeBinary(argv[0]) ){ - p->sParse.nBlob = sqlite3_value_bytes(argv[0]); - p->sParse.aBlob = (u8*)sqlite3_value_blob(argv[0]); + if( jsonArgIsJsonb(argv[0], &p->sParse) ){ + /* We have JSONB */ }else{ p->sParse.zJson = (char*)sqlite3_value_text(argv[0]); p->sParse.nJson = sqlite3_value_bytes(argv[0]); @@ -211404,7 +219505,7 @@ static int jsonEachFilter( if( p->sParse.oom ){ return SQLITE_NOMEM; } - goto json_each_malformed_input; + return jsonEachMalformedInput(cur); } } if( idxNum==3 ){ @@ -211412,7 +219513,7 @@ static int jsonEachFilter( if( zRoot==0 ) return SQLITE_OK; if( zRoot[0]!='$' ){ sqlite3_free(cur->pVtab->zErrMsg); - cur->pVtab->zErrMsg = jsonBadPathError(0, zRoot); + cur->pVtab->zErrMsg = jsonBadPathError(0, zRoot, 0); jsonEachCursorReset(p); return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM; } @@ -211430,7 +219531,7 @@ static int jsonEachFilter( return SQLITE_OK; } sqlite3_free(cur->pVtab->zErrMsg); - cur->pVtab->zErrMsg = jsonBadPathError(0, zRoot); + cur->pVtab->zErrMsg = jsonBadPathError(0, zRoot, 0); jsonEachCursorReset(p); return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM; } @@ -211465,12 +219566,6 @@ static int jsonEachFilter( p->aParent[0].iValue = i; } return SQLITE_OK; - -json_each_malformed_input: - sqlite3_free(cur->pVtab->zErrMsg); - cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON"); - jsonEachCursorReset(p); - return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM; } /* The methods of the json_each virtual table */ @@ -211481,36 +219576,7 @@ static sqlite3_module jsonEachModule = { jsonEachBestIndex, /* xBestIndex */ jsonEachDisconnect, /* xDisconnect */ 0, /* xDestroy */ - jsonEachOpenEach, /* xOpen - open a cursor */ - jsonEachClose, /* xClose - close a cursor */ - jsonEachFilter, /* xFilter - configure scan constraints */ - jsonEachNext, /* xNext - advance a cursor */ - jsonEachEof, /* xEof - check for end of scan */ - jsonEachColumn, /* xColumn - read data */ - jsonEachRowid, /* xRowid - read data */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindMethod */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0, /* xShadowName */ - 0 /* xIntegrity */ -}; - -/* The methods of the json_tree virtual table. */ -static sqlite3_module jsonTreeModule = { - 0, /* iVersion */ - 0, /* xCreate */ - jsonEachConnect, /* xConnect */ - jsonEachBestIndex, /* xBestIndex */ - jsonEachDisconnect, /* xDisconnect */ - 0, /* xDestroy */ - jsonEachOpenTree, /* xOpen - open a cursor */ + jsonEachOpen, /* xOpen - open a cursor */ jsonEachClose, /* xClose - close a cursor */ jsonEachFilter, /* xFilter - configure scan constraints */ jsonEachNext, /* xNext - advance a cursor */ @@ -211549,6 +219615,8 @@ SQLITE_PRIVATE void sqlite3RegisterJsonFunctions(void){ JFUNCTION(jsonb, 1,1,0, 0,1,0, jsonRemoveFunc), JFUNCTION(json_array, -1,0,1, 1,0,0, jsonArrayFunc), JFUNCTION(jsonb_array, -1,0,1, 1,1,0, jsonArrayFunc), + JFUNCTION(json_array_insert, -1,1,1, 1,0,JSON_AINS, jsonSetFunc), + JFUNCTION(jsonb_array_insert,-1,1,0, 1,1,JSON_AINS, jsonSetFunc), JFUNCTION(json_array_length, 1,1,0, 0,0,0, jsonArrayLengthFunc), JFUNCTION(json_array_length, 2,1,0, 0,0,0, jsonArrayLengthFunc), JFUNCTION(json_error_position,1,1,0, 0,0,0, jsonErrorFunc), @@ -211599,22 +219667,21 @@ SQLITE_PRIVATE void sqlite3RegisterJsonFunctions(void){ #if !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON) /* -** Register the JSON table-valued functions +** Register the JSON table-valued function named zName and return a +** pointer to its Module object. Return NULL if something goes wrong. */ -SQLITE_PRIVATE int sqlite3JsonTableFunctions(sqlite3 *db){ - int rc = SQLITE_OK; - static const struct { - const char *zName; - sqlite3_module *pModule; - } aMod[] = { - { "json_each", &jsonEachModule }, - { "json_tree", &jsonTreeModule }, - }; +SQLITE_PRIVATE Module *sqlite3JsonVtabRegister(sqlite3 *db, const char *zName){ unsigned int i; - for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){ - rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0); + static const char *azModule[] = { + "json_each", "json_tree", "jsonb_each", "jsonb_tree" + }; + assert( sqlite3HashFind(&db->aModule, zName)==0 ); + for(i=0; i<sizeof(azModule)/sizeof(azModule[0]); i++){ + if( sqlite3StrICmp(azModule[i],zName)==0 ){ + return sqlite3VtabCreateModule(db, azModule[i], &jsonEachModule, 0, 0); + } } - return rc; + return 0; } #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && !defined(SQLITE_OMIT_JSON) */ @@ -211684,7 +219751,9 @@ SQLITE_PRIVATE int sqlite3JsonTableFunctions(sqlite3 *db){ #else /* #include "sqlite3.h" */ #endif -SQLITE_PRIVATE int sqlite3GetToken(const unsigned char*,int*); /* In the SQLite core */ +SQLITE_PRIVATE sqlite3_int64 sqlite3GetToken(const unsigned char*,int*); /* In SQLite core */ + +/* #include <stddef.h> */ /* ** If building separately, we will need some setup that is normally @@ -211716,6 +219785,14 @@ typedef unsigned int u32; # define ALWAYS(X) (X) # define NEVER(X) (X) #endif +#ifndef offsetof +# define offsetof(ST,M) ((size_t)((char*)&((ST*)0)->M - (char*)0)) +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) +# define FLEXARRAY +#else +# define FLEXARRAY 1 +#endif #endif /* !defined(SQLITE_AMALGAMATION) */ /* Macro to check for 4-byte alignment. Only used inside of assert() */ @@ -211778,7 +219855,7 @@ struct Rtree { u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */ u8 nBytesPerCell; /* Bytes consumed per cell */ u8 inWrTrans; /* True if inside write transaction */ - u8 nAux; /* # of auxiliary columns in %_rowid */ + u16 nAux; /* # of auxiliary columns in %_rowid */ #ifdef SQLITE_ENABLE_GEOPOLY u8 nAuxNotNull; /* Number of initial not-null aux columns */ #endif @@ -211918,7 +219995,7 @@ struct RtreeCursor { sqlite3_stmt *pReadAux; /* Statement to read aux-data */ RtreeSearchPoint sPoint; /* Cached next search point */ RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */ - u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */ + u32 anQueue[RTREE_MAX_DEPTH+2]; /* Number of queued entries by iLevel */ }; /* Return the Rtree of a RtreeCursor */ @@ -212036,9 +220113,13 @@ struct RtreeMatchArg { RtreeGeomCallback cb; /* Info about the callback functions */ int nParam; /* Number of parameters to the SQL function */ sqlite3_value **apSqlParam; /* Original SQL parameter values */ - RtreeDValue aParam[1]; /* Values for parameters to the SQL function */ + RtreeDValue aParam[FLEXARRAY]; /* Values for parameters to the SQL function */ }; +/* Size of an RtreeMatchArg object with N parameters */ +#define SZ_RTREEMATCHARG(N) \ + (offsetof(RtreeMatchArg,aParam)+(N)*sizeof(RtreeDValue)) + #ifndef MAX # define MAX(x,y) ((x) < (y) ? (y) : (x)) #endif @@ -212094,7 +220175,7 @@ struct RtreeMatchArg { ** ** For best performance, an attempt is made to guess at the byte-order ** using C-preprocessor macros. If that is unsuccessful, or if -** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined +** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined ** at run-time. */ #ifndef SQLITE_BYTEORDER /* Replicate changes at tag-20230904a */ @@ -212150,8 +220231,11 @@ static void readCoord(u8 *p, RtreeCoord *pCoord){ ); #endif } + static i64 readInt64(u8 *p){ -#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 +#if defined(SQLITE_AMALGAMATION) + return (i64)sqlite3Get8byte(p); +#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 u64 x; memcpy(&x, p, 8); return (i64)_byteswap_uint64(x); @@ -212231,6 +220315,18 @@ static int writeInt64(u8 *p, i64 i){ return 8; } +/* +** Translate pVal into a 32-bit integer. If pVal is an integer +** that is larger than 32 bits, the cap it at the largest or +** smallest 32-bit integer. +*/ +static int rtreeValueInt32(sqlite3_value *pVal){ + i64 v64 = sqlite3_value_int64(pVal); + if( v64>2147483647 ) return 2147483647; + if( v64<-2147483648LL ) return (int)-2147483648LL; + return (int)v64; +} + /* ** Increment the reference count of node p. */ @@ -212369,6 +220465,9 @@ static int nodeAcquire( rc = SQLITE_CORRUPT_VTAB; RTREE_IS_CORRUPT(pRtree); } + }else if( iNode<=0 ){ + RTREE_IS_CORRUPT(pRtree); + rc = SQLITE_CORRUPT_VTAB; }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){ pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize); if( !pNode ){ @@ -212394,7 +220493,7 @@ static int nodeAcquire( */ if( rc==SQLITE_OK && pNode && iNode==1 ){ pRtree->iDepth = readInt16(pNode->zData); - if( pRtree->iDepth>RTREE_MAX_DEPTH ){ + if( pRtree->iDepth>=RTREE_MAX_DEPTH ){ rc = SQLITE_CORRUPT_VTAB; RTREE_IS_CORRUPT(pRtree); } @@ -212508,7 +220607,17 @@ static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){ sqlite3_bind_null(p, 2); if( pNode->iNode==0 && rc==SQLITE_OK ){ pNode->iNode = sqlite3_last_insert_rowid(pRtree->db); - nodeHashInsert(pRtree, pNode); + if( pNode->iNode==0 ){ + /* If the SQL statement has succeeded but sqlite3_last_insert_rowid() + ** returns 0, then the shadow table schema has been corrupted somehow + ** (e.g. the %_node table has been replaced by a WITHOUT ROWID table). + ** It would be dangerous to continue in this case as the hash table + ** implementation assumes iNode==0 means that the node is not part + ** of the hash table. */ + rc = SQLITE_CORRUPT_VTAB; + }else{ + nodeHashInsert(pRtree, pNode); + } } } return rc; @@ -212645,7 +220754,17 @@ static void rtreeRelease(Rtree *pRtree){ pRtree->inWrTrans = 0; assert( pRtree->nCursor==0 ); nodeBlobReset(pRtree); - assert( pRtree->nNodeRef==0 || pRtree->bCorrupt ); + if( pRtree->nNodeRef ){ + int i; + assert( pRtree->bCorrupt ); + for(i=0; i<HASHSIZE; i++){ + while( pRtree->aHash[i] ){ + RtreeNode *pNext = pRtree->aHash[i]->pNext; + sqlite3_free(pRtree->aHash[i]); + pRtree->aHash[i] = pNext; + } + } + } sqlite3_finalize(pRtree->pWriteNode); sqlite3_finalize(pRtree->pDeleteNode); sqlite3_finalize(pRtree->pReadRowid); @@ -212743,6 +220862,12 @@ static void resetCursor(RtreeCursor *pCsr){ pCsr->base.pVtab = (sqlite3_vtab*)pRtree; pCsr->pReadAux = pStmt; + /* The following will only fail if the previous sqlite3_step() call failed, + ** in which case the error has already been caught. This statement never + ** encounters an error within an sqlite3_column_xxx() function, as it + ** calls sqlite3_column_value(), which does not use malloc(). So it is safe + ** to ignore the error code here. */ + sqlite3_reset(pStmt); } /* @@ -212994,7 +221119,7 @@ static int nodeRowidIndex( ){ int ii; int nCell = NCELL(pNode); - assert( nCell<200 ); + assert( nCell<65536 && nCell>=0 ); for(ii=0; ii<nCell; ii++){ if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){ *piIndex = ii; @@ -213256,7 +221381,10 @@ static int rtreeStepToLeaf(RtreeCursor *pCur){ pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc); if( rc ) return rc; nCell = NCELL(pNode); - assert( nCell<200 ); + if( nCell>RTREE_MAXCELLS ){ + RTREE_IS_CORRUPT(pRtree); + return SQLITE_CORRUPT_VTAB; + } pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell); while( p->iCell<nCell ){ sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1; @@ -213727,7 +221855,7 @@ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ } /* -** Return the N-dimensional volumn of the cell stored in *p. +** Return the N-dimensional volume of the cell stored in *p. */ static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){ RtreeDValue area = (RtreeDValue)1; @@ -213931,7 +222059,7 @@ static int AdjustTree( int iCell; cnt++; - if( NEVER(cnt>100) ){ + if( cnt>100 ){ RTREE_IS_CORRUPT(pRtree); return SQLITE_CORRUPT_VTAB; } @@ -214289,15 +222417,6 @@ static int SplitNode( rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight); } - if( rc==SQLITE_OK ){ - rc = nodeRelease(pRtree, pRight); - pRight = 0; - } - if( rc==SQLITE_OK ){ - rc = nodeRelease(pRtree, pLeft); - pLeft = 0; - } - splitnode_out: nodeRelease(pRtree, pRight); nodeRelease(pRtree, pLeft); @@ -214482,7 +222601,7 @@ static int rtreeInsertCell( rc = SplitNode(pRtree, pNode, pCell, iHeight); }else{ rc = AdjustTree(pRtree, pNode, pCell); - if( ALWAYS(rc==SQLITE_OK) ){ + if( rc==SQLITE_OK ){ if( iHeight==0 ){ rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode); }else{ @@ -214621,12 +222740,6 @@ static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){ return rc; } -/* -** Rounding constants for float->double conversion. -*/ -#define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */ -#define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */ - #if !defined(SQLITE_RTREE_INT_ONLY) /* ** Convert an sqlite3_value into an RtreeValue (presumably a float) @@ -214636,7 +222749,10 @@ static RtreeValue rtreeValueDown(sqlite3_value *v){ double d = sqlite3_value_double(v); float f = (float)d; if( f>d ){ - f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS)); + unsigned int x; + memcpy(&x, &f, 4); + x = (x & 0x80000000)!=0 ? x+1 : x-1; + memcpy(&f, &x, 4); } return f; } @@ -214644,12 +222760,40 @@ static RtreeValue rtreeValueUp(sqlite3_value *v){ double d = sqlite3_value_double(v); float f = (float)d; if( f<d ){ - f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY)); + unsigned int x; + memcpy(&x, &f, 4); + x = (x & 0x80000000)!=0 ? x-1 : x+1; + memcpy(&f, &x, 4); } return f; } #endif /* !defined(SQLITE_RTREE_INT_ONLY) */ +#if !defined(SQLITE_RTREE_INT_ONLY) && defined(SQLITE_DEBUG) +/* +** SQL function: rtree_round32(V,F) +** +** Convert the floating point value V to the nearest 32-bit float +** and return that 32-bit float value. Round up if F is true, or +** down if F is falsed. +** +** Debugging and testing use only. +*/ +static void rtreeRoundFunc( + sqlite3_context *ctx, + int nArg, + sqlite3_value **apArg +){ + float f; + if( sqlite3_value_int(apArg[1]) ){ + f = rtreeValueUp(apArg[0]); + }else{ + f = rtreeValueDown(apArg[0]); + } + sqlite3_result_double(ctx, (double)f); +} +#endif /* !defined(SQLITE_RTREE_INT_ONLY) && defined(SQLITE_DEBUG) */ + /* ** A constraint has failed while inserting a row into an rtree table. ** Assuming no OOM error occurs, this function sets the error message @@ -214762,8 +222906,8 @@ static int rtreeUpdate( #endif { for(ii=0; ii<nn; ii+=2){ - cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]); - cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]); + cell.aCoord[ii].i = rtreeValueInt32(aData[ii+3]); + cell.aCoord[ii+1].i = rtreeValueInt32(aData[ii+4]); if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){ rc = rtreeConstraintError(pRtree, ii+1); goto constraint; @@ -215242,7 +223386,7 @@ static int rtreeInit( "Auxiliary rtree columns must be last" /* 4 */ }; - assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */ + assert( RTREE_MAX_AUX_COLUMN<256 ); if( argc<6 || argc>RTREE_MAX_AUX_COLUMN+3 ){ *pzErr = sqlite3_mprintf("%s", aErrMsg[2 + (argc>=6)]); return SQLITE_ERROR; @@ -215365,19 +223509,21 @@ static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ int nData; int errCode; sqlite3_str *pOut; + i64 nDim64; UNUSED_PARAMETER(nArg); memset(&node, 0, sizeof(RtreeNode)); memset(&tree, 0, sizeof(Rtree)); - tree.nDim = (u8)sqlite3_value_int(apArg[0]); - if( tree.nDim<1 || tree.nDim>5 ) return; + nDim64 = sqlite3_value_int64(apArg[0]); + if( nDim64<1 || nDim64>5 ) return; + tree.nDim = (u8)nDim64; tree.nDim2 = tree.nDim*2; tree.nBytesPerCell = 8 + 8 * tree.nDim; node.zData = (u8 *)sqlite3_value_blob(apArg[1]); if( node.zData==0 ) return; nData = sqlite3_value_bytes(apArg[1]); if( nData<4 ) return; - if( nData<NCELL(&node)*tree.nBytesPerCell ) return; + if( nData<4+NCELL(&node)*tree.nBytesPerCell ) return; pOut = sqlite3_str_new(0); for(ii=0; ii<NCELL(&node); ii++){ @@ -215397,8 +223543,8 @@ static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ sqlite3_str_append(pOut, "}", 1); } errCode = sqlite3_str_errcode(pOut); - sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free); sqlite3_result_error_code(ctx, errCode); + sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free); } /* This routine implements an SQL function that returns the "depth" parameter @@ -215493,7 +223639,7 @@ static sqlite3_stmt *rtreeCheckPrepare( /* ** The second and subsequent arguments to this function are a printf() ** style format string and arguments. This function formats the string and -** appends it to the report being accumuated in pCheck. +** appends it to the report being accumulated in pCheck. */ static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){ va_list ap; @@ -216110,7 +224256,7 @@ static int geopolyParseNumber(GeoParse *p, GeoCoord *pVal){ /* The sqlite3AtoF() routine is much much faster than atof(), if it ** is available */ double r; - (void)sqlite3AtoF((const char*)p->z, &r, j, SQLITE_UTF8); + (void)sqlite3AtoF((const char*)p->z, &r); *pVal = r; #else *pVal = (GeoCoord)atof((const char*)p->z); @@ -216168,7 +224314,7 @@ static GeoPoly *geopolyParseJson(const unsigned char *z, int *pRc){ break; } if( geopolySkipSpace(&s)==']' - && s.nVertex>=4 + && s.nVertex>=4 && s.nVertex<16777216 && s.a[0]==s.a[s.nVertex*2-2] && s.a[1]==s.a[s.nVertex*2-1] && (s.z++, geopolySkipSpace(&s)==0) @@ -216494,6 +224640,8 @@ static double geopolySine(double r){ ** ** Construct a simple, convex, regular polygon centered at X, Y ** with circumradius R and with N sides. +** +** Maximum N is 1000. Maximum R is 1.0e+300. */ static void geopolyRegularFunc( sqlite3_context *context, @@ -216503,12 +224651,12 @@ static void geopolyRegularFunc( double x = sqlite3_value_double(argv[0]); double y = sqlite3_value_double(argv[1]); double r = sqlite3_value_double(argv[2]); - int n = sqlite3_value_int(argv[3]); + i64 n = sqlite3_value_int64(argv[3]); int i; GeoPoly *p; (void)argc; - if( n<3 || r<=0.0 ) return; + if( n<3 || r<=0.0 || r>=1e300 ) return; if( n>1000 ) n = 1000; p = sqlite3_malloc64( sizeof(*p) + (n-1)*2*sizeof(GeoCoord) ); if( p==0 ){ @@ -216681,7 +224829,7 @@ static void geopolyBBoxFinal( ** Determine if point (x0,y0) is beneath line segment (x1,y1)->(x2,y2). ** Returns: ** -** +2 x0,y0 is on the line segement +** +2 x0,y0 is on the line segment ** ** +1 x0,y0 is beneath line segment ** @@ -216787,7 +224935,7 @@ static void geopolyWithinFunc( sqlite3_free(p2); } -/* Objects used by the overlap algorihm. */ +/* Objects used by the overlap algorithm. */ typedef struct GeoEvent GeoEvent; typedef struct GeoSegment GeoSegment; typedef struct GeoOverlap GeoOverlap; @@ -217161,6 +225309,11 @@ static int geopolyInit( int ii; (void)pAux; + if( argc>=RTREE_MAX_AUX_COLUMN+4 ){ + *pzErr = sqlite3_mprintf("Too many columns for a geopoly table"); + return SQLITE_ERROR; + } + sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS); @@ -217768,6 +225921,12 @@ SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){ if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0); } +#if defined(SQLITE_DEBUG) && !defined(SQLITE_RTREE_INT_ONLY) + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function(db, "rtree_round", 2, utf8, 0, + rtreeRoundFunc, 0, 0); + } +#endif /* SQLITE_DEBUG && !SQLITE_RTREE_INT_ONLY */ if( rc==SQLITE_OK ){ #ifdef SQLITE_RTREE_INT_ONLY void *c = (void *)RTREE_COORD_INT32; @@ -217834,8 +225993,7 @@ static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){ sqlite3_int64 nBlob; int memErr = 0; - nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue) - + nArg*sizeof(sqlite3_value*); + nBlob = SZ_RTREEMATCHARG(nArg) + nArg*sizeof(sqlite3_value*); pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob); if( !pBlob ){ sqlite3_result_error_nomem(ctx); @@ -217914,7 +226072,7 @@ SQLITE_API int sqlite3_rtree_query_callback( ); } -#if !SQLITE_CORE +#ifndef SQLITE_CORE #ifdef _WIN32 __declspec(dllexport) #endif @@ -218039,6 +226197,9 @@ static const unsigned char icuUtf8Trans1[] = { while( (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ + if( c<0x80 \ + || (c&0xFFFFF800)==0xD800 \ + || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ } #define SQLITE_ICU_SKIP_UTF8(zIn) \ @@ -218296,7 +226457,7 @@ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ const UChar *zInput; /* Pointer to input string */ UChar *zOutput = 0; /* Pointer to output buffer */ int nInput; /* Size of utf-16 input string in bytes */ - int nOut; /* Size of output buffer in bytes */ + sqlite3_int64 nOut; /* Size of output buffer in bytes */ int cnt; int bToUpper; /* True for toupper(), false for tolower() */ UErrorCode status; @@ -218319,7 +226480,7 @@ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ } for(cnt=0; cnt<2; cnt++){ - UChar *zNew = sqlite3_realloc(zOutput, nOut); + UChar *zNew = sqlite3_realloc64(zOutput, nOut); if( zNew==0 ){ sqlite3_free(zOutput); sqlite3_result_error_nomem(p); @@ -218328,9 +226489,9 @@ static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){ zOutput = zNew; status = U_ZERO_ERROR; if( bToUpper ){ - nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); + nOut = 2LL*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); }else{ - nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); + nOut = 2LL*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status); } if( U_SUCCESS(status) ){ @@ -218450,6 +226611,7 @@ static void icuLoadCollation( } sqlite3_result_error(p, sqlite3_str_value(pStr), -1); sqlite3_free(sqlite3_str_finish(pStr)); + ucol_close(pUCollator); return; } } @@ -218505,7 +226667,7 @@ SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){ return rc; } -#if !SQLITE_CORE +#ifndef SQLITE_CORE #ifdef _WIN32 __declspec(dllexport) #endif @@ -218930,7 +227092,7 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule( ** ** "RBU" stands for "Resumable Bulk Update". As in a large database update ** transmitted via a wireless network to a mobile device. A transaction -** applied using this extension is hence refered to as an "RBU update". +** applied using this extension is hence referred to as an "RBU update". ** ** ** LIMITATIONS @@ -219227,7 +227389,7 @@ SQLITE_API sqlite3rbu *sqlite3rbu_open( ** the next call to sqlite3rbu_vacuum() opens a handle that starts a ** new RBU vacuum operation. ** -** As with sqlite3rbu_open(), Zipvfs users should rever to the comment +** As with sqlite3rbu_open(), Zipvfs users should refer to the comment ** describing the sqlite3rbu_create_vfs() API function below for ** a description of the complications associated with using RBU with ** zipvfs databases. @@ -219323,7 +227485,7 @@ SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu); ** ** If the RBU update has been completely applied, mark the RBU database ** as fully applied. Otherwise, assuming no error has occurred, save the -** current state of the RBU update appliation to the RBU database. +** current state of the RBU update application to the RBU database. ** ** If an error has already occurred as part of an sqlite3rbu_step() ** or sqlite3rbu_open() call, or if one occurs within this function, an @@ -219943,16 +228105,26 @@ static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36, -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1, + + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; unsigned int v = 0; int c; unsigned char *z = (unsigned char*)*pz; - unsigned char *zStart = z; - while( (c = zValue[0x7f&*(z++)])>=0 ){ - v = (v<<6) + c; + unsigned char *zEnd = z + (*pLen); + while( z<zEnd && (c = zValue[*z])>=0 ){ + v = (v<<6) + c; + z++; } - z--; - *pLen -= (int)(z - zStart); + + *pLen -= (int)(z - (unsigned char*)*pz); *pz = (char*)z; return v; } @@ -220021,21 +228193,22 @@ static int rbuDeltaApply( int lenDelta, /* Length of the delta */ char *zOut /* Write the output into this preallocated buffer */ ){ - unsigned int limit; - unsigned int total = 0; + sqlite3_uint64 limit; + sqlite3_uint64 total = 0; #if RBU_ENABLE_DELTA_CKSUM char *zOrigOut = zOut; #endif limit = rbuDeltaGetInt(&zDelta, &lenDelta); - if( *zDelta!='\n' ){ + if( lenDelta<=0 || *zDelta!='\n' ){ /* ERROR: size integer not terminated by "\n" */ return -1; } - zDelta++; lenDelta--; - while( *zDelta && lenDelta>0 ){ + zDelta++; lenDelta--; /* Skip the \n */ + while( lenDelta>0 && zDelta[0] ){ unsigned int cnt, ofst; cnt = rbuDeltaGetInt(&zDelta, &lenDelta); + if( lenDelta<=0 ) return -1; switch( zDelta[0] ){ case '@': { zDelta++; lenDelta--; @@ -220050,7 +228223,7 @@ static int rbuDeltaApply( /* ERROR: copy exceeds output file size */ return -1; } - if( (int)(ofst+cnt) > lenSrc ){ + if( (u64)ofst+(u64)cnt > (u64)lenSrc ){ /* ERROR: copy extends past end of input */ return -1; } @@ -220065,7 +228238,7 @@ static int rbuDeltaApply( /* ERROR: insert command gives an output larger than predicted */ return -1; } - if( (int)cnt>lenDelta ){ + if( cnt>lenDelta ){ /* ERROR: insert count exceeds size of delta */ return -1; } @@ -220103,7 +228276,7 @@ static int rbuDeltaApply( static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){ int size; size = rbuDeltaGetInt(&zDelta, &lenDelta); - if( *zDelta!='\n' ){ + if( lenDelta<=0 || *zDelta!='\n' ){ /* ERROR: size integer not terminated by "\n" */ return -1; } @@ -220151,7 +228324,7 @@ static void rbuFossilDeltaFunc( return; } - aOut = sqlite3_malloc(nOut+1); + aOut = sqlite3_malloc64((i64)nOut+1); if( aOut==0 ){ sqlite3_result_error_nomem(context); }else{ @@ -220834,15 +229007,27 @@ static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){ /* Check that all non-HIDDEN columns in the destination table are also ** present in the input table. Populate the abTblPk[], azTblType[] and - ** aiTblOrder[] arrays at the same time. */ + ** aiTblOrder[] arrays at the same time. + ** + ** RBU does not support tables with GENERATED columns. If the target + ** table has any, return an error. */ if( p->rc==SQLITE_OK ){ p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, - sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl) + sqlite3_mprintf("PRAGMA table_xinfo(%Q)", pIter->zTbl) ); } while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ const char *zName = (const char*)sqlite3_column_text(pStmt, 1); - if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */ + int eHidden = sqlite3_column_int(pStmt, 6); + if( zName==0 ) break; /* An OOM. Bail out */ + if( eHidden==1 ) continue; /* Hidden column. Ignore */ + if( eHidden!=0 ){ + p->rc = SQLITE_ERROR; + p->zErrmsg = sqlite3_mprintf( + "generated columns not supported: %s.%s", pIter->zTbl, zName + ); + break; + } for(i=iOrder; i<pIter->nTblCol; i++){ if( 0==strcmp(zName, pIter->azTblCol[i]) ) break; } @@ -221695,9 +229880,9 @@ static char *rbuObjIterGetIndexWhere(sqlite3rbu *p, RbuObjIter *pIter){ char c = zSql[i]; /* If necessary, grow the pIter->aIdxCol[] array */ - if( iIdxCol==nIdxAlloc ){ - RbuSpan *aIdxCol = (RbuSpan*)sqlite3_realloc( - pIter->aIdxCol, (nIdxAlloc+16)*sizeof(RbuSpan) + if( iIdxCol>=(nIdxAlloc-1) ){ + RbuSpan *aIdxCol = (RbuSpan*)sqlite3_realloc64( + pIter->aIdxCol, nIdxAlloc*sizeof(RbuSpan) + 16*sizeof(RbuSpan) ); if( aIdxCol==0 ){ rc = SQLITE_NOMEM; @@ -222078,13 +230263,13 @@ static int rbuGetUpdateStmt( char *zUpdate = 0; pUp->zMask = (char*)&pUp[1]; - memcpy(pUp->zMask, zMask, pIter->nTblCol); pUp->pNext = pIter->pRbuUpdate; pIter->pRbuUpdate = pUp; if( zSet ){ const char *zPrefix = ""; - + assert( p->rc==SQLITE_OK ); + memcpy(pUp->zMask, zMask, pIter->nTblCol); if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_"; zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s", zPrefix, pIter->zTbl, zSet, zWhere @@ -222174,6 +230359,9 @@ static RbuState *rbuLoadState(sqlite3rbu *p){ case RBU_STATE_ROW: pRet->nRow = sqlite3_column_int(pStmt, 1); + if( pRet->nRow<0 ){ + rc = SQLITE_CORRUPT; + } break; case RBU_STATE_PROGRESS: @@ -223082,7 +231270,12 @@ static void rbuCreateTargetSchema(sqlite3rbu *p){ while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){ const char *zSql = (const char*)sqlite3_column_text(pSql, 0); - p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg); + sqlite3_stmt *pStmt = 0; + p->rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, zSql); + if( p->rc==SQLITE_OK ){ + sqlite3_step(pStmt); + rbuFinalize(p, pStmt); + } } rbuFinalize(p, pSql); if( p->rc!=SQLITE_OK ) return; @@ -224249,7 +232442,7 @@ static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ /* If this is an RBU vacuum operation and this is the target database, ** pretend that it has at least one page. Otherwise, SQLite will not - ** check for the existance of a *-wal file. rbuVfsRead() contains + ** check for the existence of a *-wal file. rbuVfsRead() contains ** similar logic. */ if( rc==SQLITE_OK && *pSize==0 && p->pRbu && rbuIsVacuum(p->pRbu) @@ -225489,12 +233682,14 @@ static int statNext(sqlite3_vtab_cursor *pCursor){ while( p->iCell<p->nCell ){ StatCell *pCell = &p->aCell[p->iCell]; while( pCell->iOvfl<pCell->nOvfl ){ - int nUsable, iOvfl; + int nUsable; + int iOvfl = pCell->iOvfl; sqlite3BtreeEnter(pBt); nUsable = sqlite3BtreeGetPageSize(pBt) - sqlite3BtreeGetReserveNoMutex(pBt); sqlite3BtreeLeave(pBt); pCsr->nPage++; + pCsr->iPageno = pCell->aOvfl[iOvfl]; statSizeAndOffset(pCsr); if( pCell->iOvfl<pCell->nOvfl-1 ){ pCsr->nPayload += nUsable - 4; @@ -225502,11 +233697,9 @@ static int statNext(sqlite3_vtab_cursor *pCursor){ pCsr->nPayload += pCell->nLastOvfl; pCsr->nUnused += nUsable - 4 - pCell->nLastOvfl; } - iOvfl = pCell->iOvfl; pCell->iOvfl++; if( !pCsr->isAgg ){ pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0); - pCsr->iPageno = pCell->aOvfl[iOvfl]; pCsr->zPagetype = "overflow"; pCsr->zPath = z = sqlite3_mprintf( "%s%.3x+%.6x", p->zPath, p->iCell, iOvfl @@ -225832,8 +234025,8 @@ typedef struct DbpageCursor DbpageCursor; struct DbpageCursor { sqlite3_vtab_cursor base; /* Base class. Must be first */ - int pgno; /* Current page number */ - int mxPgno; /* Last page to visit on this scan */ + Pgno pgno; /* Current page number */ + Pgno mxPgno; /* Last page to visit on this scan */ Pager *pPager; /* Pager being read/written */ DbPage *pPage1; /* Page 1 of the database */ int iDb; /* Index of database to analyze */ @@ -225970,7 +234163,7 @@ static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ }else{ memset(pCsr, 0, sizeof(DbpageCursor)); pCsr->base.pVtab = pVTab; - pCsr->pgno = -1; + pCsr->pgno = 0; } *ppCursor = (sqlite3_vtab_cursor *)pCsr; @@ -226023,7 +234216,8 @@ static int dbpageFilter( sqlite3 *db = pTab->db; Btree *pBt; - (void)idxStr; + UNUSED_PARAMETER(idxStr); + UNUSED_PARAMETER(argc); /* Default setting is no rows of result */ pCsr->pgno = 1; @@ -226044,12 +234238,13 @@ static int dbpageFilter( pCsr->szPage = sqlite3BtreeGetPageSize(pBt); pCsr->mxPgno = sqlite3BtreeLastPage(pBt); if( idxNum & 1 ){ + i64 iPg = sqlite3_value_int64(argv[idxNum>>1]); assert( argc>(idxNum>>1) ); - pCsr->pgno = sqlite3_value_int(argv[idxNum>>1]); - if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){ + if( iPg<1 || iPg>pCsr->mxPgno ){ pCsr->pgno = 1; pCsr->mxPgno = 0; }else{ + pCsr->pgno = (Pgno)iPg; pCsr->mxPgno = pCsr->pgno; } }else{ @@ -226069,12 +234264,12 @@ static int dbpageColumn( int rc = SQLITE_OK; switch( i ){ case 0: { /* pgno */ - sqlite3_result_int(ctx, pCsr->pgno); + sqlite3_result_int64(ctx, (sqlite3_int64)pCsr->pgno); break; } case 1: { /* data */ DbPage *pDbPage = 0; - if( pCsr->pgno==((PENDING_BYTE/pCsr->szPage)+1) ){ + if( pCsr->pgno==(Pgno)((PENDING_BYTE/pCsr->szPage)+1) ){ /* The pending byte page. Assume it is zeroed out. Attempting to ** request this page from the page is an SQLITE_CORRUPT error. */ sqlite3_result_zeroblob(ctx, pCsr->szPage); @@ -226103,6 +234298,24 @@ static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ return SQLITE_OK; } +/* +** Open write transactions. Since we do not know in advance which database +** files will be written by the sqlite_dbpage virtual table, start a write +** transaction on them all. +** +** Return SQLITE_OK if successful, or an SQLite error code otherwise. +*/ +static int dbpageBeginTrans(DbpageTable *pTab){ + sqlite3 *db = pTab->db; + int rc = SQLITE_OK; + int i; + for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ + Btree *pBt = db->aDb[i].pBt; + if( pBt ) rc = sqlite3BtreeBeginTrans(pBt, 1, 0); + } + return rc; +} + static int dbpageUpdate( sqlite3_vtab *pVtab, int argc, @@ -226111,6 +234324,7 @@ static int dbpageUpdate( ){ DbpageTable *pTab = (DbpageTable *)pVtab; Pgno pgno; + sqlite3_int64 pgno64; DbPage *pDbPage = 0; int rc = SQLITE_OK; char *zErr = 0; @@ -226130,11 +234344,11 @@ static int dbpageUpdate( goto update_fail; } if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ - pgno = (Pgno)sqlite3_value_int(argv[2]); + pgno64 = sqlite3_value_int64(argv[2]); isInsert = 1; }else{ - pgno = sqlite3_value_int(argv[0]); - if( (Pgno)sqlite3_value_int(argv[1])!=pgno ){ + pgno64 = (Pgno)sqlite3_value_int64(argv[0]); + if( sqlite3_value_int64(argv[1])!=pgno64 ){ zErr = "cannot insert"; goto update_fail; } @@ -226151,10 +234365,11 @@ static int dbpageUpdate( } } pBt = pTab->db->aDb[iDb].pBt; - if( pgno<1 || NEVER(pBt==0) ){ + if( pgno64<1 || pgno64>4294967294U || NEVER(pBt==0) ){ zErr = "bad page number"; goto update_fail; } + pgno = (Pgno)pgno64; szPage = sqlite3BtreeGetPageSize(pBt); if( sqlite3_value_type(argv[3])!=SQLITE_BLOB || sqlite3_value_bytes(argv[3])!=szPage @@ -226163,13 +234378,19 @@ static int dbpageUpdate( /* "INSERT INTO dbpage($PGNO,NULL)" causes page number $PGNO and ** all subsequent pages to be deleted. */ pTab->iDbTrunc = iDb; - pgno--; - pTab->pgnoTrunc = pgno; + pTab->pgnoTrunc = pgno-1; + pgno = 1; }else{ zErr = "bad page value"; goto update_fail; } } + + if( dbpageBeginTrans(pTab)!=SQLITE_OK ){ + zErr = "failed to open transaction"; + goto update_fail; + } + pPager = sqlite3BtreePager(pBt); rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0); if( rc==SQLITE_OK ){ @@ -226180,27 +234401,21 @@ static int dbpageUpdate( pTab->pgnoTrunc = 0; } } + if( rc!=SQLITE_OK ){ + pTab->pgnoTrunc = 0; + } sqlite3PagerUnref(pDbPage); return rc; update_fail: + pTab->pgnoTrunc = 0; sqlite3_free(pVtab->zErrMsg); pVtab->zErrMsg = sqlite3_mprintf("%s", zErr); return SQLITE_ERROR; } -/* Since we do not know in advance which database files will be -** written by the sqlite_dbpage virtual table, start a write transaction -** on them all. -*/ static int dbpageBegin(sqlite3_vtab *pVtab){ DbpageTable *pTab = (DbpageTable *)pVtab; - sqlite3 *db = pTab->db; - int i; - for(i=0; i<db->nDb; i++){ - Btree *pBt = db->aDb[i].pBt; - if( pBt ) (void)sqlite3BtreeBeginTrans(pBt, 1, 0); - } pTab->pgnoTrunc = 0; return SQLITE_OK; } @@ -226212,7 +234427,11 @@ static int dbpageSync(sqlite3_vtab *pVtab){ if( pTab->pgnoTrunc>0 ){ Btree *pBt = pTab->db->aDb[pTab->iDbTrunc].pBt; Pager *pPager = sqlite3BtreePager(pBt); - sqlite3PagerTruncateImage(pPager, pTab->pgnoTrunc); + sqlite3BtreeEnter(pBt); + if( pTab->pgnoTrunc<sqlite3BtreeLastPage(pBt) ){ + sqlite3PagerTruncateImage(pPager, pTab->pgnoTrunc); + } + sqlite3BtreeLeave(pBt); } pTab->pgnoTrunc = 0; return SQLITE_OK; @@ -226232,7 +234451,7 @@ static int dbpageRollbackTo(sqlite3_vtab *pVtab, int notUsed1){ */ SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ static sqlite3_module dbpage_module = { - 0, /* iVersion */ + 2, /* iVersion */ dbpageConnect, /* xCreate */ dbpageConnect, /* xConnect */ dbpageBestIndex, /* xBestIndex */ @@ -226265,6 +234484,573 @@ SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; } #endif /* SQLITE_ENABLE_DBSTAT_VTAB */ /************** End of dbpage.c **********************************************/ +/************** Begin file carray.c ******************************************/ +/* +** 2016-06-29 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file implements a table-valued-function that +** returns the values in a C-language array. +** Examples: +** +** SELECT * FROM carray($ptr,5) +** +** The query above returns 5 integers contained in a C-language array +** at the address $ptr. $ptr is a pointer to the array of integers. +** The pointer value must be assigned to $ptr using the +** sqlite3_bind_pointer() interface with a pointer type of "carray". +** For example: +** +** static int aX[] = { 53, 9, 17, 2231, 4, 99 }; +** int i = sqlite3_bind_parameter_index(pStmt, "$ptr"); +** sqlite3_bind_pointer(pStmt, i, aX, "carray", 0); +** +** There is an optional third parameter to determine the datatype of +** the C-language array. Allowed values of the third parameter are +** 'int32', 'int64', 'double', 'char*', 'struct iovec'. Example: +** +** SELECT * FROM carray($ptr,10,'char*'); +** +** The default value of the third parameter is 'int32'. +** +** HOW IT WORKS +** +** The carray "function" is really a virtual table with the +** following schema: +** +** CREATE TABLE carray( +** value, +** pointer HIDDEN, +** count HIDDEN, +** ctype TEXT HIDDEN +** ); +** +** If the hidden columns "pointer" and "count" are unconstrained, then +** the virtual table has no rows. Otherwise, the virtual table interprets +** the integer value of "pointer" as a pointer to the array and "count" +** as the number of elements in the array. The virtual table steps through +** the array, element by element. +*/ +#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_CARRAY) +/* #include "sqliteInt.h" */ +#if defined(_WIN32) || defined(__RTP__) || defined(_WRS_KERNEL) + struct iovec { + void *iov_base; + size_t iov_len; + }; +#else +# include <sys/uio.h> +#endif + +/* +** Names of allowed datatypes +*/ +static const char *azCarrayType[] = { + "int32", "int64", "double", "char*", "struct iovec" +}; + +/* +** Structure used to hold the sqlite3_carray_bind() information +*/ +typedef struct carray_bind carray_bind; +struct carray_bind { + void *aData; /* The data */ + int nData; /* Number of elements */ + int mFlags; /* Control flags */ + void (*xDel)(void*); /* Destructor for aData */ + void *pDel; /* Alternative argument to xDel() */ +}; + + +/* carray_cursor is a subclass of sqlite3_vtab_cursor which will +** serve as the underlying representation of a cursor that scans +** over rows of the result +*/ +typedef struct carray_cursor carray_cursor; +struct carray_cursor { + sqlite3_vtab_cursor base; /* Base class - must be first */ + sqlite3_int64 iRowid; /* The rowid */ + void *pPtr; /* Pointer to the array of values */ + sqlite3_int64 iCnt; /* Number of integers in the array */ + unsigned char eType; /* One of the CARRAY_type values */ +}; + +/* +** The carrayConnect() method is invoked to create a new +** carray_vtab that describes the carray virtual table. +** +** Think of this routine as the constructor for carray_vtab objects. +** +** All this routine needs to do is: +** +** (1) Allocate the carray_vtab object and initialize all fields. +** +** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the +** result set of queries against carray will look like. +*/ +static int carrayConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + sqlite3_vtab *pNew; + int rc; + +/* Column numbers */ +#define CARRAY_COLUMN_VALUE 0 +#define CARRAY_COLUMN_POINTER 1 +#define CARRAY_COLUMN_COUNT 2 +#define CARRAY_COLUMN_CTYPE 3 + + rc = sqlite3_declare_vtab(db, + "CREATE TABLE x(value,pointer hidden,count hidden,ctype hidden)"); + if( rc==SQLITE_OK ){ + pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) ); + if( pNew==0 ) return SQLITE_NOMEM; + memset(pNew, 0, sizeof(*pNew)); + } + return rc; +} + +/* +** This method is the destructor for carray_cursor objects. +*/ +static int carrayDisconnect(sqlite3_vtab *pVtab){ + sqlite3_free(pVtab); + return SQLITE_OK; +} + +/* +** Constructor for a new carray_cursor object. +*/ +static int carrayOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ + carray_cursor *pCur; + pCur = sqlite3_malloc( sizeof(*pCur) ); + if( pCur==0 ) return SQLITE_NOMEM; + memset(pCur, 0, sizeof(*pCur)); + *ppCursor = &pCur->base; + return SQLITE_OK; +} + +/* +** Destructor for a carray_cursor. +*/ +static int carrayClose(sqlite3_vtab_cursor *cur){ + sqlite3_free(cur); + return SQLITE_OK; +} + + +/* +** Advance a carray_cursor to its next row of output. +*/ +static int carrayNext(sqlite3_vtab_cursor *cur){ + carray_cursor *pCur = (carray_cursor*)cur; + pCur->iRowid++; + return SQLITE_OK; +} + +/* +** Return values of columns for the row at which the carray_cursor +** is currently pointing. +*/ +static int carrayColumn( + sqlite3_vtab_cursor *cur, /* The cursor */ + sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ + int i /* Which column to return */ +){ + carray_cursor *pCur = (carray_cursor*)cur; + sqlite3_int64 x = 0; + switch( i ){ + case CARRAY_COLUMN_POINTER: return SQLITE_OK; + case CARRAY_COLUMN_COUNT: x = pCur->iCnt; break; + case CARRAY_COLUMN_CTYPE: { + sqlite3_result_text(ctx, azCarrayType[pCur->eType], -1, SQLITE_STATIC); + return SQLITE_OK; + } + default: { + switch( pCur->eType ){ + case CARRAY_INT32: { + int *p = (int*)pCur->pPtr; + sqlite3_result_int(ctx, p[pCur->iRowid-1]); + return SQLITE_OK; + } + case CARRAY_INT64: { + sqlite3_int64 *p = (sqlite3_int64*)pCur->pPtr; + sqlite3_result_int64(ctx, p[pCur->iRowid-1]); + return SQLITE_OK; + } + case CARRAY_DOUBLE: { + double *p = (double*)pCur->pPtr; + sqlite3_result_double(ctx, p[pCur->iRowid-1]); + return SQLITE_OK; + } + case CARRAY_TEXT: { + const char **p = (const char**)pCur->pPtr; + sqlite3_result_text(ctx, p[pCur->iRowid-1], -1, SQLITE_TRANSIENT); + return SQLITE_OK; + } + default: { + const struct iovec *p = (struct iovec*)pCur->pPtr; + assert( pCur->eType==CARRAY_BLOB ); + p += pCur->iRowid-1; + if( p->iov_len>0x7fffffff ){ + sqlite3_result_error_toobig(ctx); + return SQLITE_TOOBIG; + }else{ + sqlite3_result_blob(ctx, p->iov_base, (int)p->iov_len, + SQLITE_TRANSIENT); + } + return SQLITE_OK; + } + } + } + } + sqlite3_result_int64(ctx, x); + return SQLITE_OK; +} + +/* +** Return the rowid for the current row. In this implementation, the +** rowid is the same as the output value. +*/ +static int carrayRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ + carray_cursor *pCur = (carray_cursor*)cur; + *pRowid = pCur->iRowid; + return SQLITE_OK; +} + +/* +** Return TRUE if the cursor has been moved off of the last +** row of output. +*/ +static int carrayEof(sqlite3_vtab_cursor *cur){ + carray_cursor *pCur = (carray_cursor*)cur; + return pCur->iRowid>pCur->iCnt; +} + +/* +** This method is called to "rewind" the carray_cursor object back +** to the first row of output. +*/ +static int carrayFilter( + sqlite3_vtab_cursor *pVtabCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + carray_cursor *pCur = (carray_cursor *)pVtabCursor; + pCur->pPtr = 0; + pCur->iCnt = 0; + switch( idxNum ){ + case 1: { + carray_bind *pBind = sqlite3_value_pointer(argv[0], "carray-bind"); + if( pBind==0 ) break; + pCur->pPtr = pBind->aData; + pCur->iCnt = pBind->nData; + pCur->eType = pBind->mFlags & 0x07; + break; + } + case 2: + case 3: { + pCur->pPtr = sqlite3_value_pointer(argv[0], "carray"); + pCur->iCnt = pCur->pPtr ? sqlite3_value_int64(argv[1]) : 0; + if( idxNum<3 ){ + pCur->eType = CARRAY_INT32; + }else{ + unsigned char i; + const char *zType = (const char*)sqlite3_value_text(argv[2]); + for(i=0; i<sizeof(azCarrayType)/sizeof(azCarrayType[0]); i++){ + if( sqlite3_stricmp(zType, azCarrayType[i])==0 ) break; + } + if( i>=sizeof(azCarrayType)/sizeof(azCarrayType[0]) ){ + pVtabCursor->pVtab->zErrMsg = sqlite3_mprintf( + "unknown datatype: %Q", zType); + return SQLITE_ERROR; + }else{ + pCur->eType = i; + } + } + break; + } + } + pCur->iRowid = 1; + return SQLITE_OK; +} + +/* +** SQLite will invoke this method one or more times while planning a query +** that uses the carray virtual table. This routine needs to create +** a query plan for each invocation and compute an estimated cost for that +** plan. +** +** In this implementation idxNum is used to represent the +** query plan. idxStr is unused. +** +** idxNum is: +** +** 1 If only the pointer= constraint exists. In this case, the +** parameter must be bound using sqlite3_carray_bind(). +** +** 2 if the pointer= and count= constraints exist. +** +** 3 if the ctype= constraint also exists. +** +** idxNum is 0 otherwise and carray becomes an empty table. +*/ +static int carrayBestIndex( + sqlite3_vtab *tab, + sqlite3_index_info *pIdxInfo +){ + int i; /* Loop over constraints */ + int ptrIdx = -1; /* Index of the pointer= constraint, or -1 if none */ + int cntIdx = -1; /* Index of the count= constraint, or -1 if none */ + int ctypeIdx = -1; /* Index of the ctype= constraint, or -1 if none */ + unsigned seen = 0; /* Bitmask of == constrainted columns */ + + const struct sqlite3_index_constraint *pConstraint; + pConstraint = pIdxInfo->aConstraint; + for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){ + if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; + if( pConstraint->iColumn>=0 ) seen |= 1 << pConstraint->iColumn; + if( pConstraint->usable==0 ) continue; + switch( pConstraint->iColumn ){ + case CARRAY_COLUMN_POINTER: + ptrIdx = i; + break; + case CARRAY_COLUMN_COUNT: + cntIdx = i; + break; + case CARRAY_COLUMN_CTYPE: + ctypeIdx = i; + break; + } + } + if( ptrIdx>=0 ){ + pIdxInfo->aConstraintUsage[ptrIdx].argvIndex = 1; + pIdxInfo->aConstraintUsage[ptrIdx].omit = 1; + pIdxInfo->estimatedCost = (double)1; + pIdxInfo->estimatedRows = 100; + pIdxInfo->idxNum = 1; + if( cntIdx>=0 ){ + pIdxInfo->aConstraintUsage[cntIdx].argvIndex = 2; + pIdxInfo->aConstraintUsage[cntIdx].omit = 1; + pIdxInfo->idxNum = 2; + if( ctypeIdx>=0 ){ + pIdxInfo->aConstraintUsage[ctypeIdx].argvIndex = 3; + pIdxInfo->aConstraintUsage[ctypeIdx].omit = 1; + pIdxInfo->idxNum = 3; + }else if( seen & (1<<CARRAY_COLUMN_CTYPE) ){ + /* In a three-argument carray(), we need to know the value of all + ** three arguments */ + return SQLITE_CONSTRAINT; + } + }else if( seen & (1<<CARRAY_COLUMN_COUNT) ){ + /* In a two-argument carray(), we need to know the value of both + ** arguments */ + return SQLITE_CONSTRAINT; + } + }else{ + pIdxInfo->estimatedCost = (double)2147483647; + pIdxInfo->estimatedRows = 2147483647; + pIdxInfo->idxNum = 0; + } + return SQLITE_OK; +} + +/* +** This following structure defines all the methods for the +** carray virtual table. +*/ +static sqlite3_module carrayModule = { + 0, /* iVersion */ + 0, /* xCreate */ + carrayConnect, /* xConnect */ + carrayBestIndex, /* xBestIndex */ + carrayDisconnect, /* xDisconnect */ + 0, /* xDestroy */ + carrayOpen, /* xOpen - open a cursor */ + carrayClose, /* xClose - close a cursor */ + carrayFilter, /* xFilter - configure scan constraints */ + carrayNext, /* xNext - advance a cursor */ + carrayEof, /* xEof - check for end of scan */ + carrayColumn, /* xColumn - read data */ + carrayRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0, /* xShadow */ + 0 /* xIntegrity */ +}; + +/* +** Destructor for the carray_bind object +*/ +static void carrayBindDel(void *pPtr){ + carray_bind *p = (carray_bind*)pPtr; + if( p->xDel!=SQLITE_STATIC ){ + p->xDel(p->pDel); + } + sqlite3_free(p); +} + +/* +** Invoke this interface in order to bind to the single-argument +** version of CARRAY(). +** +** pStmt The prepared statement to which to bind +** idx The index of the parameter of pStmt to which to bind +** aData The data to be bound +** nData The number of elements in aData +** mFlags One of SQLITE_CARRAY_xxxx indicating datatype of aData +** xDestroy Destructor for pDestroy or aData if pDestroy==NULL. +** pDestroy Invoke xDestroy on this pointer if not NULL +** +** The destructor is called pDestroy if pDestroy!=NULL, or against +** aData if pDestroy==NULL. +*/ +SQLITE_API int sqlite3_carray_bind_v2( + sqlite3_stmt *pStmt, + int idx, + void *aData, + int nData, + int mFlags, + void (*xDestroy)(void*), + void *pDestroy +){ + carray_bind *pNew = 0; + int i; + int rc = SQLITE_OK; + + /* Ensure that the mFlags value is acceptable. */ + assert( CARRAY_INT32==0 && CARRAY_INT64==1 && CARRAY_DOUBLE==2 ); + assert( CARRAY_TEXT==3 && CARRAY_BLOB==4 ); + if( mFlags<CARRAY_INT32 || mFlags>CARRAY_BLOB ){ + rc = SQLITE_ERROR; + goto carray_bind_error; + } + + pNew = sqlite3_malloc64(sizeof(*pNew)); + if( pNew==0 ){ + rc = SQLITE_NOMEM; + goto carray_bind_error; + } + + pNew->nData = nData; + pNew->mFlags = mFlags; + if( xDestroy==SQLITE_TRANSIENT ){ + sqlite3_int64 sz = nData; + switch( mFlags ){ + case CARRAY_INT32: sz *= 4; break; + case CARRAY_INT64: sz *= 8; break; + case CARRAY_DOUBLE: sz *= 8; break; + case CARRAY_TEXT: sz *= sizeof(char*); break; + default: sz *= sizeof(struct iovec); break; + } + if( mFlags==CARRAY_TEXT ){ + for(i=0; i<nData; i++){ + const char *z = ((char**)aData)[i]; + if( z ) sz += strlen(z) + 1; + } + }else if( mFlags==CARRAY_BLOB ){ + for(i=0; i<nData; i++){ + sz += ((struct iovec*)aData)[i].iov_len; + } + } + + pNew->aData = sqlite3_malloc64( sz ); + if( pNew->aData==0 ){ + rc = SQLITE_NOMEM; + goto carray_bind_error; + } + + if( mFlags==CARRAY_TEXT ){ + char **az = (char**)pNew->aData; + char *z = (char*)&az[nData]; + for(i=0; i<nData; i++){ + const char *zData = ((char**)aData)[i]; + sqlite3_int64 n; + if( zData==0 ){ + az[i] = 0; + continue; + } + az[i] = z; + n = strlen(zData); + memcpy(z, zData, n+1); + z += n+1; + } + }else if( mFlags==CARRAY_BLOB ){ + struct iovec *p = (struct iovec*)pNew->aData; + unsigned char *z = (unsigned char*)&p[nData]; + for(i=0; i<nData; i++){ + size_t n = ((struct iovec*)aData)[i].iov_len; + p[i].iov_len = n; + p[i].iov_base = z; + z += n; + memcpy(p[i].iov_base, ((struct iovec*)aData)[i].iov_base, n); + } + }else{ + memcpy(pNew->aData, aData, sz); + } + pNew->xDel = sqlite3_free; + pNew->pDel = pNew->aData; + }else{ + pNew->aData = aData; + pNew->xDel = xDestroy; + pNew->pDel = pDestroy; + } + return sqlite3_bind_pointer(pStmt, idx, pNew, "carray-bind", carrayBindDel); + + carray_bind_error: + if( xDestroy!=SQLITE_STATIC && xDestroy!=SQLITE_TRANSIENT ){ + xDestroy(pDestroy); + } + sqlite3_free(pNew); + return rc; +} + +/* +** Invoke this interface in order to bind to the single-argument +** version of CARRAY(). Same as sqlite3_carray_bind_v2() with the +** pDestroy parameter set to NULL. +*/ +SQLITE_API int sqlite3_carray_bind( + sqlite3_stmt *pStmt, + int idx, + void *aData, + int nData, + int mFlags, + void (*xDestroy)(void*) +){ + return sqlite3_carray_bind_v2(pStmt,idx,aData,nData,mFlags,xDestroy,aData); +} + +/* +** Invoke this routine to register the carray() function. +*/ +SQLITE_PRIVATE Module *sqlite3CarrayRegister(sqlite3 *db){ + return sqlite3VtabCreateModule(db, "carray", &carrayModule, 0, 0); +} + +#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_CARRAY) */ + +/************** End of carray.c **********************************************/ /************** Begin file sqlite3session.c **********************************/ #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK) @@ -226407,11 +235193,13 @@ struct sqlite3_changeset_iter { struct SessionTable { SessionTable *pNext; char *zName; /* Local name of table */ - int nCol; /* Number of columns in table zName */ + int nCol; /* Number of non-hidden columns */ + int nTotalCol; /* Number of columns including hidden */ int bStat1; /* True if this is sqlite_stat1 */ int bRowid; /* True if this table uses rowid for PK */ const char **azCol; /* Column names */ const char **azDflt; /* Default value expressions */ + int *aiIdx; /* Index to pass to xNew/xOld */ u8 *abPK; /* Array of primary key flags */ int nEntry; /* Total number of entries in hash table */ int nChange; /* Size of apChange[] array */ @@ -226612,7 +235400,24 @@ static int sessionVarintLen(int iVal){ ** bytes read. */ static int sessionVarintGet(const u8 *aBuf, int *piVal){ - return getVarint32(aBuf, *piVal); + int ret = getVarint32(aBuf, *piVal); + *piVal = (*piVal & 0x7FFFFFFF); + return ret; +} + +/* +** Read a varint value from buffer aBuf[], size nBuf bytes, into *piVal. +** Return the number of bytes read. +*/ +static int sessionVarintGetSafe(const u8 *aBuf, int nBuf, int *piVal){ + u8 aCopy[9]; + const u8 *aRead = aBuf; + memset(aCopy, 0, sizeof(aCopy)); + if( nBuf<sizeof(aCopy) ){ + memcpy(aCopy, aBuf, nBuf); + aRead = aCopy; + } + return sessionVarintGet(aRead, piVal); } /* Load an unaligned and unsigned 32-bit integer */ @@ -226643,6 +235448,19 @@ static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){ aBuf[7] = (i>> 0) & 0xFF; } +/* +** Write a double value to the buffer aBuf[]. +*/ +static void sessionPutDouble(u8 *aBuf, double r){ + /* TODO: SQLite does something special to deal with mixed-endian + ** floating point values (e.g. ARM7). This code probably should + ** too. */ + u64 i; + assert( sizeof(double)==8 && sizeof(u64)==8 ); + memcpy(&i, &r, 8); + sessionPutI64(aBuf, i); +} + /* ** This function is used to serialize the contents of value pValue (see ** comment titled "RECORD FORMAT" above). @@ -226680,16 +235498,13 @@ static int sessionSerializeValue( /* TODO: SQLite does something special to deal with mixed-endian ** floating point values (e.g. ARM7). This code probably should ** too. */ - u64 i; if( eType==SQLITE_INTEGER ){ - i = (u64)sqlite3_value_int64(pValue); + u64 i = (u64)sqlite3_value_int64(pValue); + sessionPutI64(&aBuf[1], i); }else{ - double r; - assert( sizeof(double)==8 && sizeof(u64)==8 ); - r = sqlite3_value_double(pValue); - memcpy(&i, &r, 8); + double r = sqlite3_value_double(pValue); + sessionPutDouble(&aBuf[1], r); } - sessionPutI64(&aBuf[1], i); } nByte = 9; break; @@ -226814,22 +235629,22 @@ static int sessionPreupdateHash( unsigned int h = 0; /* Hash value to return */ int i; /* Used to iterate through columns */ + assert( pTab->nTotalCol==pSession->hook.xCount(pSession->hook.pCtx) ); if( pTab->bRowid ){ - assert( pTab->nCol-1==pSession->hook.xCount(pSession->hook.pCtx) ); h = sessionHashAppendI64(h, iRowid); }else{ assert( *pbNullPK==0 ); - assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) ); for(i=0; i<pTab->nCol; i++){ if( pTab->abPK[i] ){ int rc; int eType; sqlite3_value *pVal; + int iIdx = pTab->aiIdx[i]; if( bNew ){ - rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal); + rc = pSession->hook.xNew(pSession->hook.pCtx, iIdx, &pVal); }else{ - rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal); + rc = pSession->hook.xOld(pSession->hook.pCtx, iIdx, &pVal); } if( rc!=SQLITE_OK ) return rc; @@ -226879,10 +235694,11 @@ static int sessionSerialLen(const u8 *a){ int n; assert( a!=0 ); e = *a; - if( e==0 || e==0xFF ) return 1; - if( e==SQLITE_NULL ) return 1; if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9; - return sessionVarintGet(&a[1], &n) + 1 + n; + if( e==SQLITE_TEXT || e==SQLITE_BLOB ){ + return sessionVarintGet(&a[1], &n) + 1 + n; + } + return 1; } /* @@ -226905,31 +235721,31 @@ static unsigned int sessionChangeHash( u8 *a = aRecord; /* Used to iterate through change record */ for(i=0; i<pTab->nCol; i++){ - int eType = *a; int isPK = pTab->abPK[i]; if( bPkOnly && isPK==0 ) continue; - /* It is not possible for eType to be SQLITE_NULL here. The session - ** module does not record changes for rows with NULL values stored in - ** primary key columns. */ - assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT - || eType==SQLITE_TEXT || eType==SQLITE_BLOB - || eType==SQLITE_NULL || eType==0 - ); - assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) ); - if( isPK ){ - a++; + int eType = *a++; + + assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT + || eType==SQLITE_TEXT || eType==SQLITE_BLOB + || eType==SQLITE_NULL || eType==0 + ); + h = sessionHashAppendType(h, eType); if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ h = sessionHashAppendI64(h, sessionGetI64(a)); a += 8; - }else{ + }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ int n; a += sessionVarintGet(a, &n); h = sessionHashAppendBlob(h, n, a); a += n; } + /* It should not be possible for eType to be SQLITE_NULL or 0x00 here, + ** as the session module does not record changes for rows with NULL + ** values stored in primary key columns. But a corrupt changesets + ** may contain such a value. */ }else{ a += sessionSerialLen(a); } @@ -227166,6 +235982,7 @@ static int sessionPreupdateEqual( sqlite3_value *pVal; /* Value returned by preupdate_new/old */ int rc; /* Error code from preupdate_new/old */ int eType = *a++; /* Type of value from change record */ + int iIdx = pTab->aiIdx[iCol]; /* The following calls to preupdate_new() and preupdate_old() can not ** fail. This is because they cache their return values, and by the @@ -227174,10 +235991,10 @@ static int sessionPreupdateEqual( ** this (that the method has already been called). */ if( op==SQLITE_INSERT ){ /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */ - rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal); + rc = pSession->hook.xNew(pSession->hook.pCtx, iIdx, &pVal); }else{ /* assert( db->pPreUpdate->pUnpacked ); */ - rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal); + rc = pSession->hook.xOld(pSession->hook.pCtx, iIdx, &pVal); } assert( rc==SQLITE_OK ); (void)rc; /* Suppress warning about unused variable */ @@ -227302,9 +236119,11 @@ static int sessionTableInfo( const char *zDb, /* Name of attached database (e.g. "main") */ const char *zThis, /* Table name */ int *pnCol, /* OUT: number of columns */ + int *pnTotalCol, /* OUT: number of hidden columns */ const char **pzTab, /* OUT: Copy of zThis */ const char ***pazCol, /* OUT: Array of column names for table */ const char ***pazDflt, /* OUT: Array of default value expressions */ + int **paiIdx, /* OUT: Array of xNew/xOld indexes */ u8 **pabPK, /* OUT: Array of booleans - true for PK col */ int *pbRowid /* OUT: True if only PK is a rowid */ ){ @@ -227319,6 +236138,7 @@ static int sessionTableInfo( char **azCol = 0; char **azDflt = 0; u8 *abPK = 0; + int *aiIdx = 0; int bRowid = 0; /* Set to true to use rowid as PK */ assert( pazCol && pabPK ); @@ -227326,6 +236146,8 @@ static int sessionTableInfo( *pazCol = 0; *pabPK = 0; *pnCol = 0; + if( pnTotalCol ) *pnTotalCol = 0; + if( paiIdx ) *paiIdx = 0; if( pzTab ) *pzTab = 0; if( pazDflt ) *pazDflt = 0; @@ -227335,9 +236157,9 @@ static int sessionTableInfo( if( rc==SQLITE_OK ){ /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */ zPragma = sqlite3_mprintf( - "SELECT 0, 'tbl', '', 0, '', 1 UNION ALL " - "SELECT 1, 'idx', '', 0, '', 2 UNION ALL " - "SELECT 2, 'stat', '', 0, '', 0" + "SELECT 0, 'tbl', '', 0, '', 1, 0 UNION ALL " + "SELECT 1, 'idx', '', 0, '', 2, 0 UNION ALL " + "SELECT 2, 'stat', '', 0, '', 0, 0" ); }else if( rc==SQLITE_ERROR ){ zPragma = sqlite3_mprintf(""); @@ -227345,7 +236167,7 @@ static int sessionTableInfo( return rc; } }else{ - zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis); + zPragma = sqlite3_mprintf("PRAGMA '%q'.table_xinfo('%q')", zDb, zThis); } if( !zPragma ){ return SQLITE_NOMEM; @@ -227362,7 +236184,9 @@ static int sessionTableInfo( while( SQLITE_ROW==sqlite3_step(pStmt) ){ nByte += sqlite3_column_bytes(pStmt, 1); /* name */ nByte += sqlite3_column_bytes(pStmt, 4); /* dflt_value */ - nDbCol++; + if( sqlite3_column_int(pStmt, 6)==0 ){ /* !hidden */ + nDbCol++; + } if( sqlite3_column_int(pStmt, 5) ) bRowid = 0; /* pk */ } if( nDbCol==0 ) bRowid = 0; @@ -227371,7 +236195,7 @@ static int sessionTableInfo( rc = sqlite3_reset(pStmt); if( rc==SQLITE_OK ){ - nByte += nDbCol * (sizeof(const char *)*2 + sizeof(u8) + 1 + 1); + nByte += nDbCol * (sizeof(const char *)*2 +sizeof(int)+sizeof(u8) + 1 + 1); pAlloc = sessionMalloc64(pSession, nByte); if( pAlloc==0 ){ rc = SQLITE_NOMEM; @@ -227382,8 +236206,8 @@ static int sessionTableInfo( if( rc==SQLITE_OK ){ azCol = (char **)pAlloc; azDflt = (char**)&azCol[nDbCol]; - pAlloc = (u8 *)&azDflt[nDbCol]; - abPK = (u8 *)pAlloc; + aiIdx = (int*)&azDflt[nDbCol]; + abPK = (u8 *)&aiIdx[nDbCol]; pAlloc = &abPK[nDbCol]; if( pzTab ){ memcpy(pAlloc, zThis, nThis+1); @@ -227398,27 +236222,32 @@ static int sessionTableInfo( azCol[i] = (char*)pAlloc; pAlloc += nName+1; abPK[i] = 1; + aiIdx[i] = -1; i++; } while( SQLITE_ROW==sqlite3_step(pStmt) ){ - int nName = sqlite3_column_bytes(pStmt, 1); - int nDflt = sqlite3_column_bytes(pStmt, 4); - const unsigned char *zName = sqlite3_column_text(pStmt, 1); - const unsigned char *zDflt = sqlite3_column_text(pStmt, 4); - - if( zName==0 ) break; - memcpy(pAlloc, zName, nName+1); - azCol[i] = (char *)pAlloc; - pAlloc += nName+1; - if( zDflt ){ - memcpy(pAlloc, zDflt, nDflt+1); - azDflt[i] = (char *)pAlloc; - pAlloc += nDflt+1; - }else{ - azDflt[i] = 0; + if( sqlite3_column_int(pStmt, 6)==0 ){ /* !hidden */ + int nName = sqlite3_column_bytes(pStmt, 1); + int nDflt = sqlite3_column_bytes(pStmt, 4); + const unsigned char *zName = sqlite3_column_text(pStmt, 1); + const unsigned char *zDflt = sqlite3_column_text(pStmt, 4); + + if( zName==0 ) break; + memcpy(pAlloc, zName, nName+1); + azCol[i] = (char *)pAlloc; + pAlloc += nName+1; + if( zDflt ){ + memcpy(pAlloc, zDflt, nDflt+1); + azDflt[i] = (char *)pAlloc; + pAlloc += nDflt+1; + }else{ + azDflt[i] = 0; + } + abPK[i] = sqlite3_column_int(pStmt, 5); + aiIdx[i] = sqlite3_column_int(pStmt, 0); + i++; } - abPK[i] = sqlite3_column_int(pStmt, 5); - i++; + if( pnTotalCol ) (*pnTotalCol)++; } rc = sqlite3_reset(pStmt); } @@ -227431,6 +236260,7 @@ static int sessionTableInfo( if( pazDflt ) *pazDflt = (const char**)azDflt; *pabPK = abPK; *pnCol = nDbCol; + if( paiIdx ) *paiIdx = aiIdx; }else{ sessionFree(pSession, azCol); } @@ -227442,7 +236272,7 @@ static int sessionTableInfo( /* ** This function is called to initialize the SessionTable.nCol, azCol[] ** abPK[] and azDflt[] members of SessionTable object pTab. If these -** fields are already initilialized, this function is a no-op. +** fields are already initialized, this function is a no-op. ** ** If an error occurs, an error code is stored in sqlite3_session.rc and ** non-zero returned. Or, if no error occurs but the table has no primary @@ -227461,8 +236291,11 @@ static int sessionInitTable( if( pTab->nCol==0 ){ u8 *abPK; assert( pTab->azCol==0 || pTab->abPK==0 ); + sqlite3_free(pTab->azCol); + pTab->abPK = 0; rc = sessionTableInfo(pSession, db, zDb, - pTab->zName, &pTab->nCol, 0, &pTab->azCol, &pTab->azDflt, &abPK, + pTab->zName, &pTab->nCol, &pTab->nTotalCol, 0, &pTab->azCol, + &pTab->azDflt, &pTab->aiIdx, &abPK, ((pSession==0 || pSession->bImplicitPK) ? &pTab->bRowid : 0) ); if( rc==SQLITE_OK ){ @@ -227497,15 +236330,17 @@ static int sessionInitTable( */ static int sessionReinitTable(sqlite3_session *pSession, SessionTable *pTab){ int nCol = 0; + int nTotalCol = 0; const char **azCol = 0; const char **azDflt = 0; + int *aiIdx = 0; u8 *abPK = 0; int bRowid = 0; assert( pSession->rc==SQLITE_OK ); pSession->rc = sessionTableInfo(pSession, pSession->db, pSession->zDb, - pTab->zName, &nCol, 0, &azCol, &azDflt, &abPK, + pTab->zName, &nCol, &nTotalCol, 0, &azCol, &azDflt, &aiIdx, &abPK, (pSession->bImplicitPK ? &bRowid : 0) ); if( pSession->rc==SQLITE_OK ){ @@ -227528,8 +236363,10 @@ static int sessionReinitTable(sqlite3_session *pSession, SessionTable *pTab){ const char **a = pTab->azCol; pTab->azCol = azCol; pTab->nCol = nCol; + pTab->nTotalCol = nTotalCol; pTab->azDflt = azDflt; pTab->abPK = abPK; + pTab->aiIdx = aiIdx; azCol = a; } if( pSession->bEnableSize ){ @@ -227600,9 +236437,7 @@ static void sessionUpdateOneChange( case SQLITE_FLOAT: { double rVal = sqlite3_column_double(pDflt, iField); - i64 iVal = 0; - memcpy(&iVal, &rVal, sizeof(rVal)); - sessionPutI64(&pNew->aRecord[pNew->nRecord], iVal); + sessionPutDouble(&pNew->aRecord[pNew->nRecord], rVal); pNew->nRecord += 8; break; } @@ -227698,7 +236533,7 @@ static void sessionAppendStr( int *pRc ){ int nStr = sqlite3Strlen30(zStr); - if( 0==sessionBufferGrow(p, nStr+1, pRc) ){ + if( 0==sessionBufferGrow(p, (i64)nStr+1, pRc) ){ memcpy(&p->aBuf[p->nBuf], zStr, nStr); p->nBuf += nStr; p->aBuf[p->nBuf] = 0x00; @@ -227766,6 +236601,16 @@ static int sessionPrepareDfltStmt( return rc; } +/* +** Finalize statement pStmt. If (*pRc) is SQLITE_OK when this function is +** called, set it to the results of the sqlite3_finalize() call. Or, if +** it is already set to an error code, leave it as is. +*/ +static void sessionFinalizeStmt(sqlite3_stmt *pStmt, int *pRc){ + int rc = sqlite3_finalize(pStmt); + if( *pRc==SQLITE_OK ) *pRc = rc; +} + /* ** Table pTab has one or more existing change-records with old.* records ** with fewer than pTab->nCol columns. This function updates all such @@ -227788,9 +236633,8 @@ static int sessionUpdateChanges(sqlite3_session *pSession, SessionTable *pTab){ } } + sessionFinalizeStmt(pStmt, &rc); pSession->rc = rc; - rc = sqlite3_finalize(pStmt); - if( pSession->rc==SQLITE_OK ) pSession->rc = rc; return pSession->rc; } @@ -227847,7 +236691,7 @@ static int sessionUpdateMaxSize( int ii; for(ii=0; ii<pTab->nCol; ii++){ sqlite3_value *p = 0; - pSession->hook.xNew(pSession->hook.pCtx, ii, &p); + pSession->hook.xNew(pSession->hook.pCtx, pTab->aiIdx[ii], &p); sessionSerializeValue(0, p, &nNew); } } @@ -227867,8 +236711,9 @@ static int sessionUpdateMaxSize( int bChanged = 1; int nOld = 0; int eType; + int iIdx = pTab->aiIdx[ii]; sqlite3_value *p = 0; - pSession->hook.xNew(pSession->hook.pCtx, ii-pTab->bRowid, &p); + pSession->hook.xNew(pSession->hook.pCtx, iIdx, &p); if( p==0 ){ return SQLITE_NOMEM; } @@ -227965,11 +236810,11 @@ static void sessionPreupdateOneChange( /* Check the number of columns in this xPreUpdate call matches the ** number of columns in the table. */ nExpect = pSession->hook.xCount(pSession->hook.pCtx); - if( (pTab->nCol-pTab->bRowid)<nExpect ){ + if( pTab->nTotalCol<nExpect ){ if( sessionReinitTable(pSession, pTab) ) return; if( sessionUpdateChanges(pSession, pTab) ) return; } - if( (pTab->nCol-pTab->bRowid)!=nExpect ){ + if( pTab->nTotalCol!=nExpect ){ pSession->rc = SQLITE_SCHEMA; return; } @@ -228026,14 +236871,15 @@ static void sessionPreupdateOneChange( /* Figure out how large an allocation is required */ nByte = sizeof(SessionChange); - for(i=0; i<(pTab->nCol-pTab->bRowid); i++){ + for(i=pTab->bRowid; i<pTab->nCol; i++){ + int iIdx = pTab->aiIdx[i]; sqlite3_value *p = 0; if( op!=SQLITE_INSERT ){ /* This may fail if the column has a non-NULL default and was added ** using ALTER TABLE ADD COLUMN after this record was created. */ - rc = pSession->hook.xOld(pSession->hook.pCtx, i, &p); + rc = pSession->hook.xOld(pSession->hook.pCtx, iIdx, &p); }else if( pTab->abPK[i] ){ - TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p); + TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx,iIdx,&p); assert( trc==SQLITE_OK ); } @@ -228068,12 +236914,13 @@ static void sessionPreupdateOneChange( sessionPutI64(&pC->aRecord[1], iRowid); nByte = 9; } - for(i=0; i<(pTab->nCol-pTab->bRowid); i++){ + for(i=pTab->bRowid; i<pTab->nCol; i++){ sqlite3_value *p = 0; + int iIdx = pTab->aiIdx[i]; if( op!=SQLITE_INSERT ){ - pSession->hook.xOld(pSession->hook.pCtx, i, &p); + pSession->hook.xOld(pSession->hook.pCtx, iIdx, &p); }else if( pTab->abPK[i] ){ - pSession->hook.xNew(pSession->hook.pCtx, i, &p); + pSession->hook.xNew(pSession->hook.pCtx, iIdx, &p); } sessionSerializeValue(&pC->aRecord[nByte], p, &nByte); } @@ -228355,7 +237202,7 @@ static int sessionDiffFindNew( rc = SQLITE_NOMEM; }else{ sqlite3_stmt *pStmt; - rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0); + rc = sqlite3_prepare_v2(pSession->db, zStmt, -1, &pStmt, 0); if( rc==SQLITE_OK ){ SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx; pDiffCtx->pStmt = pStmt; @@ -228418,7 +237265,7 @@ static int sessionDiffFindModified( rc = SQLITE_NOMEM; }else{ sqlite3_stmt *pStmt; - rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0); + rc = sqlite3_prepare_v2(pSession->db, zStmt, -1, &pStmt, 0); if( rc==SQLITE_OK ){ SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx; @@ -228460,7 +237307,9 @@ SQLITE_API int sqlite3session_diff( SessionTable *pTo; /* Table zTbl */ /* Locate and if necessary initialize the target table object */ + pSession->bAutoAttach++; rc = sessionFindTable(pSession, zTbl, &pTo); + pSession->bAutoAttach--; if( pTo==0 ) goto diff_out; if( sessionInitTable(pSession, pTo, pSession->db, pSession->zDb) ){ rc = pSession->rc; @@ -228471,16 +237320,43 @@ SQLITE_API int sqlite3session_diff( if( rc==SQLITE_OK ){ int bHasPk = 0; int bMismatch = 0; - int nCol; /* Columns in zFrom.zTbl */ + int nCol = 0; /* Columns in zFrom.zTbl */ int bRowid = 0; - u8 *abPK; + u8 *abPK = 0; const char **azCol = 0; - rc = sessionTableInfo(0, db, zFrom, zTbl, &nCol, 0, &azCol, 0, &abPK, - pSession->bImplicitPK ? &bRowid : 0 - ); + char *zDbExists = 0; + + /* Check that database zFrom is attached. */ + zDbExists = sqlite3_mprintf("SELECT * FROM %Q.sqlite_schema", zFrom); + if( zDbExists==0 ){ + rc = SQLITE_NOMEM; + }else{ + sqlite3_stmt *pDbExists = 0; + rc = sqlite3_prepare_v2(db, zDbExists, -1, &pDbExists, 0); + if( rc==SQLITE_ERROR ){ + rc = SQLITE_OK; + nCol = -1; + } + sqlite3_finalize(pDbExists); + sqlite3_free(zDbExists); + } + + if( rc==SQLITE_OK && nCol==0 ){ + rc = sessionTableInfo(0, db, zFrom, zTbl, + &nCol, 0, 0, &azCol, 0, 0, &abPK, + pSession->bImplicitPK ? &bRowid : 0 + ); + } if( rc==SQLITE_OK ){ if( pTo->nCol!=nCol ){ - bMismatch = 1; + if( nCol<=0 ){ + rc = SQLITE_SCHEMA; + if( pzErrMsg ){ + *pzErrMsg = sqlite3_mprintf("no such table: %s.%s", zFrom, zTbl); + } + }else{ + bMismatch = 1; + } }else{ int i; for(i=0; i<nCol; i++){ @@ -228799,9 +237675,11 @@ static void sessionAppendIdent( char *zOut = (char *)&p->aBuf[p->nBuf]; const char *zIn = zStr; *zOut++ = '"'; - while( *zIn ){ - if( *zIn=='"' ) *zOut++ = '"'; - *zOut++ = *(zIn++); + if( zIn!=0 ){ + while( *zIn ){ + if( *zIn=='"' ) *zOut++ = '"'; + *zOut++ = *(zIn++); + } } *zOut++ = '"'; p->nBuf = (int)((u8 *)zOut - p->aBuf); @@ -228825,15 +237703,14 @@ static void sessionAppendCol( int eType = sqlite3_column_type(pStmt, iCol); sessionAppendByte(p, (u8)eType, pRc); if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ - sqlite3_int64 i; u8 aBuf[8]; if( eType==SQLITE_INTEGER ){ - i = sqlite3_column_int64(pStmt, iCol); + sqlite3_int64 i = sqlite3_column_int64(pStmt, iCol); + sessionPutI64(aBuf, i); }else{ double r = sqlite3_column_double(pStmt, iCol); - memcpy(&i, &r, 8); + sessionPutDouble(aBuf, r); } - sessionPutI64(aBuf, i); sessionAppendBlob(p, aBuf, 8, pRc); } if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){ @@ -229026,6 +237903,46 @@ static int sessionAppendDelete( return rc; } +static int sessionPrepare( + sqlite3 *db, + sqlite3_stmt **pp, + char **pzErrmsg, + const char *zSql +){ + int rc = sqlite3_prepare_v2(db, zSql, -1, pp, 0); + if( pzErrmsg && rc!=SQLITE_OK ){ + *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); + } + return rc; +} + +/* +** Prepare the statement specified by printf format zFmt and its trailing +** arguments. +*/ +static void sessionPrepareMprintf( + int *pRc, + sqlite3 *db, + sqlite3_stmt **pp, + char **pzErrmsg, + const char *zFmt, + ... +){ + if( *pRc==SQLITE_OK ){ + char *zSql; + va_list ap; + va_start(ap, zFmt); + zSql = sqlite3_vmprintf(zFmt, ap); + if( zSql==0 ){ + *pRc = SQLITE_NOMEM; + }else{ + *pRc = sessionPrepare(db, pp, pzErrmsg, zSql); + sqlite3_free(zSql); + } + va_end(ap); + } +} + /* ** Formulate and prepare a SELECT statement to retrieve a row from table ** zTab in database zDb based on its primary key. i.e. @@ -229047,15 +237964,15 @@ static int sessionSelectStmt( int nCol, /* Number of columns in table */ const char **azCol, /* Names of table columns */ u8 *abPK, /* PRIMARY KEY array */ - sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */ + sqlite3_stmt **ppStmt, /* OUT: Prepared SELECT statement */ + char **pzErrmsg /* OUT: Error message */ ){ int rc = SQLITE_OK; char *zSql = 0; const char *zSep = ""; - const char *zCols = bRowid ? SESSIONS_ROWID ", *" : "*"; - int nSql = -1; int i; + SessionBuffer cols = {0, 0, 0}; SessionBuffer nooptest = {0, 0, 0}; SessionBuffer pkfield = {0, 0, 0}; SessionBuffer pkvar = {0, 0, 0}; @@ -229068,9 +237985,16 @@ static int sessionSelectStmt( sessionAppendStr(&pkvar, "?1, (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", &rc ); - zCols = "tbl, ?2, stat"; + sessionAppendStr(&cols, "tbl, ?2, stat", &rc); }else{ +#if 0 + if( bRowid ){ + sessionAppendStr(&cols, SESSIONS_ROWID, &rc); + } +#endif for(i=0; i<nCol; i++){ + if( cols.nBuf ) sessionAppendStr(&cols, ", ", &rc); + sessionAppendIdent(&cols, azCol[i], &rc); if( abPK[i] ){ sessionAppendStr(&pkfield, zSep, &rc); sessionAppendStr(&pkvar, zSep, &rc); @@ -229088,7 +238012,7 @@ static int sessionSelectStmt( if( rc==SQLITE_OK ){ zSql = sqlite3_mprintf( "SELECT %s%s FROM %Q.%Q WHERE (%s) IS (%s)", - zCols, (bIgnoreNoop ? (char*)nooptest.aBuf : ""), + (char*)cols.aBuf, (bIgnoreNoop ? (char*)nooptest.aBuf : ""), zDb, zTab, (char*)pkfield.aBuf, (char*)pkvar.aBuf ); if( zSql==0 ) rc = SQLITE_NOMEM; @@ -229125,12 +238049,13 @@ static int sessionSelectStmt( #endif if( rc==SQLITE_OK ){ - rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0); + rc = sessionPrepare(db, ppStmt, pzErrmsg, zSql); } sqlite3_free(zSql); sqlite3_free(nooptest.aBuf); sqlite3_free(pkfield.aBuf); sqlite3_free(pkvar.aBuf); + sqlite3_free(cols.aBuf); return rc; } @@ -229246,7 +238171,7 @@ static int sessionGenerateChangeset( ){ sqlite3 *db = pSession->db; /* Source database handle */ SessionTable *pTab; /* Used to iterate through attached tables */ - SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */ + SessionBuffer buf = {0,0,0}; /* Buffer in which to accumulate changeset */ int rc; /* Return code */ assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0) ); @@ -229262,10 +238187,13 @@ static int sessionGenerateChangeset( } if( pSession->rc ) return pSession->rc; - rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0); - if( rc!=SQLITE_OK ) return rc; sqlite3_mutex_enter(sqlite3_db_mutex(db)); + rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0); + if( rc!=SQLITE_OK ){ + sqlite3_mutex_leave(sqlite3_db_mutex(db)); + return rc; + } for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){ if( pTab->nEntry ){ @@ -229288,7 +238216,7 @@ static int sessionGenerateChangeset( /* Build and compile a statement to execute: */ if( rc==SQLITE_OK ){ rc = sessionSelectStmt(db, 0, pSession->zDb, - zName, pTab->bRowid, pTab->nCol, pTab->azCol, pTab->abPK, &pSel + zName, pTab->bRowid, pTab->nCol, pTab->azCol, pTab->abPK, &pSel, 0 ); } @@ -229599,14 +238527,15 @@ SQLITE_API int sqlite3changeset_start_v2_strm( ** object and the buffer is full, discard some data to free up space. */ static void sessionDiscardData(SessionInput *pIn){ - if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){ - int nMove = pIn->buf.nBuf - pIn->iNext; + if( pIn->xInput && pIn->iCurrent>=sessions_strm_chunk_size ){ + int nMove = pIn->buf.nBuf - pIn->iCurrent; assert( nMove>=0 ); if( nMove>0 ){ - memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove); + memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iCurrent], nMove); } - pIn->buf.nBuf -= pIn->iNext; - pIn->iNext = 0; + pIn->buf.nBuf -= pIn->iCurrent; + pIn->iNext -= pIn->iCurrent; + pIn->iCurrent = 0; pIn->nData = pIn->buf.nBuf; } } @@ -229747,7 +238676,8 @@ static int sessionReadRecord( u8 *aVal = &pIn->aData[pIn->iNext]; if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ int nByte; - pIn->iNext += sessionVarintGet(aVal, &nByte); + int nRem = pIn->nData - pIn->iNext; + pIn->iNext += sessionVarintGetSafe(aVal, nRem, &nByte); rc = sessionInputBuffer(pIn, nByte); if( rc==SQLITE_OK ){ if( nByte<0 || nByte>pIn->nData-pIn->iNext ){ @@ -229800,7 +238730,8 @@ static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){ rc = sessionInputBuffer(pIn, 9); if( rc==SQLITE_OK ){ - nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol); + int nBuf = pIn->nData - pIn->iNext; + nRead += sessionVarintGetSafe(&pIn->aData[pIn->iNext], nBuf, &nCol); /* The hard upper limit for the number of columns in an SQLite ** database table is, according to sqliteLimit.h, 32676. So ** consider any table-header that purports to have more than 65536 @@ -229820,8 +238751,15 @@ static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){ while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){ nRead++; } + + /* Break out of the loop if if the nul-terminator byte has been found. + ** Otherwise, read some more input data and keep seeking. If there is + ** no more input data, consider the changeset corrupt. */ if( (pIn->iNext + nRead)<pIn->nData ) break; rc = sessionInputBuffer(pIn, nRead + 100); + if( rc==SQLITE_OK && (pIn->iNext + nRead)>=pIn->nData ){ + rc = SQLITE_CORRUPT_BKPT; + } } *pnByte = nRead+1; return rc; @@ -229842,22 +238780,32 @@ static int sessionChangesetBufferRecord( int *pnByte /* OUT: Size of record in bytes */ ){ int rc = SQLITE_OK; - int nByte = 0; + i64 nByte = 0; int i; for(i=0; rc==SQLITE_OK && i<nCol; i++){ int eType; rc = sessionInputBuffer(pIn, nByte + 10); if( rc==SQLITE_OK ){ - eType = pIn->aData[pIn->iNext + nByte++]; - if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ - int n; - nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n); - nByte += n; - rc = sessionInputBuffer(pIn, nByte); - }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ - nByte += 8; + if( pIn->iNext+nByte>=pIn->nData ){ + rc = SQLITE_CORRUPT_BKPT; + }else{ + eType = pIn->aData[pIn->iNext + nByte++]; + if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){ + int n; + int nRem = pIn->nData - (pIn->iNext + nByte); + nByte += sessionVarintGetSafe(&pIn->aData[pIn->iNext+nByte], nRem,&n); + nByte += n; + rc = sessionInputBuffer(pIn, nByte); + }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ + nByte += 8; + }else if( eType!=0 && eType!=SQLITE_NULL ){ + rc = SQLITE_CORRUPT_BKPT; + } } } + if( rc==SQLITE_OK && (pIn->iNext+nByte)>pIn->nData ){ + rc = SQLITE_CORRUPT_BKPT; + } } *pnByte = nByte; return rc; @@ -229953,15 +238901,15 @@ static int sessionChangesetNextOne( memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2); } - /* Make sure the buffer contains at least 10 bytes of input data, or all - ** remaining data if there are less than 10 bytes available. This is - ** sufficient either for the 'T' or 'P' byte and the varint that follows - ** it, or for the two single byte values otherwise. */ + /* Make sure the buffer contains at least 2 bytes of input data, or all + ** remaining data if there are less than 2 bytes available. This is + ** sufficient either for the 'T' or 'P' byte that begins a new table, + ** or for the "op" and "bIndirect" single bytes otherwise. */ p->rc = sessionInputBuffer(&p->in, 2); if( p->rc!=SQLITE_OK ) return p->rc; - sessionDiscardData(&p->in); p->in.iCurrent = p->in.iNext; + sessionDiscardData(&p->in); /* If the iterator is already at the end of the changeset, return DONE. */ if( p->in.iNext>=p->in.nData ){ @@ -229986,11 +238934,13 @@ static int sessionChangesetNextOne( return (p->rc = SQLITE_CORRUPT_BKPT); } - p->op = op; - p->bIndirect = p->in.aData[p->in.iNext++]; - if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){ + if( (op!=SQLITE_UPDATE && op!=SQLITE_DELETE && op!=SQLITE_INSERT) + || (p->in.iNext>=p->in.nData) + ){ return (p->rc = SQLITE_CORRUPT_BKPT); } + p->op = op; + p->bIndirect = p->in.aData[p->in.iNext++]; if( paRec ){ int nVal; /* Number of values to buffer */ @@ -230299,7 +239249,13 @@ static int sessionChangesetInvert( /* Test for EOF. */ if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert; - if( pInput->iNext>=pInput->nData ) break; + if( pInput->iNext+1>=pInput->nData ){ + if( pInput->iNext!=pInput->nData ){ + rc = SQLITE_CORRUPT_BKPT; + goto finished_invert; + } + break; + } eType = pInput->aData[pInput->iNext]; switch( eType ){ @@ -230495,7 +239451,9 @@ struct SessionApplyCtx { u8 bRebaseStarted; /* If table header is already in rebase */ u8 bRebase; /* True to collect rebase information */ u8 bIgnoreNoop; /* True to ignore no-op conflicts */ + u8 bNoUpdateLoop; /* No update-loop processing */ int bRowid; + char *zErr; /* Error message, if any */ }; /* Number of prepared UPDATE statements to cache. */ @@ -230721,7 +239679,7 @@ static int sessionDeleteRow( } if( rc==SQLITE_OK ){ - rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0); + rc = sessionPrepare(db, &p->pDelete, &p->zErr, (char*)buf.aBuf); } sqlite3_free(buf.aBuf); @@ -230748,7 +239706,7 @@ static int sessionSelectRow( ){ /* TODO */ return sessionSelectStmt(db, p->bIgnoreNoop, - "main", zTab, p->bRowid, p->nCol, p->azCol, p->abPK, &p->pSelect + "main", zTab, p->bRowid, p->nCol, p->azCol, p->abPK, &p->pSelect, &p->zErr ); } @@ -230785,16 +239743,12 @@ static int sessionInsertRow( sessionAppendStr(&buf, ")", &rc); if( rc==SQLITE_OK ){ - rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0); + rc = sessionPrepare(db, &p->pInsert, &p->zErr, (char*)buf.aBuf); } sqlite3_free(buf.aBuf); return rc; } -static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){ - return sqlite3_prepare_v2(db, zSql, -1, pp, 0); -} - /* ** Prepare statements for applying changes to the sqlite_stat1 table. ** These are similar to those created by sessionSelectRow(), @@ -230804,14 +239758,14 @@ static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){ static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){ int rc = sessionSelectRow(db, "sqlite_stat1", p); if( rc==SQLITE_OK ){ - rc = sessionPrepare(db, &p->pInsert, + rc = sessionPrepare(db, &p->pInsert, 0, "INSERT INTO main.sqlite_stat1 VALUES(?1, " "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, " "?3)" ); } if( rc==SQLITE_OK ){ - rc = sessionPrepare(db, &p->pDelete, + rc = sessionPrepare(db, &p->pDelete, 0, "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS " "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END " "AND (?4 OR stat IS ?3)" @@ -231035,7 +239989,7 @@ static int sessionConflictHandler( void *pCtx, /* First argument for conflict handler */ int *pbReplace /* OUT: Set to true if PK row is found */ ){ - int res = 0; /* Value returned by conflict handler */ + int res = SQLITE_CHANGESET_OMIT;/* Value returned by conflict handler */ int rc; int nCol; int op; @@ -231056,11 +240010,9 @@ static int sessionConflictHandler( if( rc==SQLITE_ROW ){ /* There exists another row with the new.* primary key. */ - if( p->bIgnoreNoop - && sqlite3_column_int(p->pSelect, sqlite3_column_count(p->pSelect)-1) + if( 0==p->bIgnoreNoop + || 0==sqlite3_column_int(p->pSelect, sqlite3_column_count(p->pSelect)-1) ){ - res = SQLITE_CHANGESET_OMIT; - }else{ pIter->pConflict = p->pSelect; res = xConflict(pCtx, eType, pIter); pIter->pConflict = 0; @@ -231073,8 +240025,10 @@ static int sessionConflictHandler( u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent]; int nBlob = pIter->in.iNext - pIter->in.iCurrent; sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc); - return SQLITE_OK; - }else{ + return rc; + }else if( p->bIgnoreNoop==0 || op!=SQLITE_DELETE + || eType==SQLITE_CHANGESET_CONFLICT + ){ /* No other row with the new.* primary key. */ res = xConflict(pCtx, eType+1, pIter); if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE; @@ -231172,7 +240126,7 @@ static int sessionApplyOneOp( sqlite3_step(p->pDelete); rc = sqlite3_reset(p->pDelete); - if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 && p->bIgnoreNoop==0 ){ + if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){ rc = sessionConflictHandler( SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry ); @@ -231193,7 +240147,7 @@ static int sessionApplyOneOp( for(i=0; rc==SQLITE_OK && i<nCol; i++){ sqlite3_value *pOld = sessionChangesetOld(pIter, i); sqlite3_value *pNew = sessionChangesetNew(pIter, i); - if( p->abPK[i] || (bPatchset==0 && pOld) ){ + if( pOld && (p->abPK[i] || bPatchset==0) ){ rc = sessionBindValue(pUp, i*2+2, pOld); } if( rc==SQLITE_OK && pNew ){ @@ -231319,7 +240273,321 @@ static int sessionApplyOneWithRetry( } /* -** Retry the changes accumulated in the pApply->constraints buffer. +** Create an iterator to iterate through the retry buffer pRetry. +*/ +static int sessionRetryIterInit( + SessionBuffer *pRetry, /* Buffer to iterate through */ + int bPatchset, /* True for patchset, false for changeset */ + const char *zTab, /* Table name */ + SessionApplyCtx *pApply, /* Session apply context */ + sqlite3_changeset_iter **ppIter /* OUT: New iterator */ +){ + sqlite3_changeset_iter *pRet = 0; + int rc = SQLITE_OK; + + rc = sessionChangesetStart( + &pRet, 0, 0, pRetry->nBuf, pRetry->aBuf, pApply->bInvertConstraints, 1 + ); + if( rc==SQLITE_OK ){ + size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*); + pRet->bPatchset = bPatchset; + pRet->zTab = (char*)zTab; + pRet->nCol = pApply->nCol; + pRet->abPK = pApply->abPK; + sessionBufferGrow(&pRet->tblhdr, nByte, &rc); + pRet->apValue = (sqlite3_value**)pRet->tblhdr.aBuf; + if( rc==SQLITE_OK ){ + memset(pRet->apValue, 0, nByte); + }else{ + sqlite3changeset_finalize(pRet); + pRet = 0; + } + } + + *ppIter = pRet; + return rc; +} + +/* +** Attempt to apply all the changes in retry buffer pRetry to the database. +** Except, if parameter iSkip is greater than or equal to 0, skip change +** iSkip. +*/ +static int sessionApplyRetryBuffer( + SessionBuffer *pRetry, /* Buffer to apply changes from */ + int iSkip, /* If >=0, index of change to omit */ + sqlite3 *db, /* Database handle */ + int bPatchset, /* True for patchset, false for changeset */ + const char *zTab, /* Name of table to write to */ + SessionApplyCtx *pApply, /* Apply context */ + int(*xConflict)(void*, int, sqlite3_changeset_iter*), + void *pCtx /* First argument passed to xConflict */ +){ + int rc = SQLITE_OK; + int rc2 = SQLITE_OK; + int ii = 0; + sqlite3_changeset_iter *pIter = 0; + + assert( pApply->constraints.nBuf==0 ); + + rc = sessionRetryIterInit(pRetry, bPatchset, zTab, pApply, &pIter); + + for(ii=0; rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter); ii++){ + if( ii!=iSkip ){ + rc = sessionApplyOneWithRetry(db, pIter, pApply, xConflict, pCtx); + } + } + + rc2 = sqlite3changeset_finalize(pIter); + if( rc==SQLITE_OK ) rc = rc2; + assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 ); + + return rc; +} + +/* +** Buffer aUnique[] is pApply->nCol entries in size. This function sets +** aUnique[i] to true if column i of table zTab in the "main" database +** of db is part of at least one UNIQUE constraint, or to false otherwise. +** +** If the table has a unique index on an expression, or a partial unique +** index, all entries of aUnique[] are set to true. +** +** SQLITE_OK is returned if successful, or an SQLite error code otherwise. +*/ +static int sessionUniqueColumns( + sqlite3 *db, /* Database handle */ + const char *zTab, /* Table name */ + SessionApplyCtx *pApply, /* Apply context */ + u8 *aUnique /* OUT: Array of pApply->nCol flags */ +){ + sqlite3_stmt *pList = 0; /* PRAGMA index_list */ + int rc = SQLITE_OK; + + /* Ordinary PRAGMA statements are used here instead of the equivalent + ** table-valued functions (pragma_index_list() etc.) so that this works + ** in builds with SQLITE_OMIT_VIRTUALTABLE defined. */ + memset(aUnique, 0, pApply->nCol); + sessionPrepareMprintf(&rc, db, &pList, &pApply->zErr, + "PRAGMA main.index_list(%Q)", zTab + ); + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){ + /* Columns of PRAGMA index_list are (seq, name, unique, origin, partial) */ + const char *zIdx = (const char*)sqlite3_column_text(pList, 1); + int bUnique = sqlite3_column_int(pList, 2); + int bPartial = sqlite3_column_int(pList, 4); + sqlite3_stmt *pInfo = 0; /* PRAGMA index_xinfo */ + + if( bUnique==0 ) continue; + sessionPrepareMprintf(&rc, db, &pInfo, &pApply->zErr, + "PRAGMA main.index_xinfo(%Q)", zIdx + ); + while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pInfo) ){ + /* Columns of PRAGMA index_xinfo are (seqno, cid, name, desc, coll, key)*/ + int iCid = sqlite3_column_int(pInfo, 1); + const char *zCol = (const char*)sqlite3_column_text(pInfo, 2); + int bKey = sqlite3_column_int(pInfo, 5); + int ii; + if( bKey==0 ) continue; + for(ii=0; ii<pApply->nCol; ii++){ + if( bPartial + || iCid==-2 + || (zCol && 0==sqlite3_stricmp(zCol, pApply->azCol[ii])) + ){ + aUnique[ii] = 1; + } + } + } + if( rc==SQLITE_OK ){ + rc = sqlite3_finalize(pInfo); + }else{ + sqlite3_finalize(pInfo); + } + } + if( rc==SQLITE_OK ){ + rc = sqlite3_finalize(pList); + }else{ + sqlite3_finalize(pList); + } + + return rc; +} + +/* +** Iterator pUp points to an UPDATE change. This function updates the +** affected row to set each column modified by the UPDATE change that +** is also part of at least one UNIQUE constraint to a "random" value, +** and creates another UPDATE statement that may be used to later set +** all columns modified by pUp to the actual values required by pUp. +** +** Each random value has the same type as the final value required by +** pUp for the same column: +** +** NULL -> NULL +** INTEGER -> random() +** REAL -> random() +** TEXT -> CAST(random() AS TEXT) +** BLOB -> unhex(hex(random())) +** +** If none of the columns modified by pUp are part of a UNIQUE constraint, +** then SQLITE_CONSTRAINT is returned. +** +** If successful, SQLITE_OK is returned and output variable (*ppUpdate) +** is left pointing to a prepared UPDATE statement. It is the responsibility +** of the caller to eventually free this statement using sqlite3_finalize(). +** Or, if an error occurs, an SQLite error code is returned and (*ppUpdate) +** set to NULL. pApply->zErr may be set to an error message in this case. +** Except - it is guaranteed that pApply->zErr is not set if SQLITE_CONSTRAINT +** is returned. +*/ +static int sessionUpdateToUpdate( + sqlite3 *db, /* Database to write to */ + const char *zTab, /* Table name */ + SessionApplyCtx *pApply, /* Apply context */ + sqlite3_changeset_iter *pUp, /* Iterator pointing to UPDATE change */ + sqlite3_stmt **ppUpdate /* OUT: UPDATE statement */ +){ + sqlite3_stmt *pRet = 0; /* UPDATE to set the final values */ + sqlite3_stmt *pRand = 0; /* UPDATE to set random values */ + int rc = SQLITE_OK; + u8 *aUnique = 0; /* aUnique[i] true if col i is UNIQUE */ + SessionBuffer randset = {0, 0, 0}; + SessionBuffer upset = {0, 0, 0}; + SessionBuffer where = {0, 0, 0}; + int ii; + + aUnique = (u8*)sqlite3_malloc64(pApply->nCol); + if( aUnique==0 ){ + rc = SQLITE_NOMEM; + }else{ + rc = sessionUniqueColumns(db, zTab, pApply, aUnique); + } + + /* Assuming a table structure like this: + ** + ** CREATE TABLE x(a, b UNIQUE, c, d UNIQUE, e, PRIMARY KEY(a, c)); + ** + ** and an UPDATE change that sets column b to an integer, column d to + ** a text value and column e to any value, the two statements prepared + ** are: + ** + ** UPDATE main.x SET b = random(), d = CAST(random() AS TEXT) + ** WHERE a IS ?1 AND c IS ?3 + ** UPDATE main.x SET b = ?2, d = ?4, e = ?5 WHERE a IS ?1 AND c IS ?3 + */ + for(ii=0; rc==SQLITE_OK && ii<pApply->nCol; ii++){ + sqlite3_value *pNew = 0; + if( pApply->abPK[ii] ){ + if( where.nBuf>0 ) sessionAppendStr(&where, " AND ", &rc); + sessionAppendIdent(&where, pApply->azCol[ii], &rc); + sessionAppendPrintf(&where, &rc, " IS ?%d", ii+1); + }else if( (pNew = sessionChangesetNew(pUp, ii))!=0 ){ + if( aUnique[ii] ){ + const char *zRand = 0; + switch( sqlite3_value_type(pNew) ){ + case SQLITE_NULL: zRand = "NULL"; break; + case SQLITE_TEXT: zRand = "CAST(random() AS TEXT)"; break; + case SQLITE_BLOB: zRand = "unhex(hex(random()))"; break; + default: zRand = "random()"; break; + } + if( randset.nBuf>0 ) sessionAppendStr(&randset, ", ", &rc); + sessionAppendIdent(&randset, pApply->azCol[ii], &rc); + sessionAppendStr(&randset, " = ", &rc); + sessionAppendStr(&randset, zRand, &rc); + } + if( upset.nBuf>0 ) sessionAppendStr(&upset, ", ", &rc); + sessionAppendIdent(&upset, pApply->azCol[ii], &rc); + sessionAppendPrintf(&upset, &rc, " = ?%d", ii+1); + } + } + + if( rc==SQLITE_OK && randset.nBuf==0 ){ + /* None of the columns modified by this change are part of a UNIQUE + ** constraint. So setting them to random values cannot help resolve + ** a constraint conflict. Report this as a constraint failure. */ + rc = SQLITE_CONSTRAINT; + } + + sessionPrepareMprintf(&rc, db, &pRand, &pApply->zErr, + "UPDATE main.\"%w\" SET %s WHERE %s", + zTab, (char*)randset.aBuf, (char*)where.aBuf + ); + sessionPrepareMprintf(&rc, db, &pRet, &pApply->zErr, + "UPDATE main.\"%w\" SET %s WHERE %s", + zTab, (char*)upset.aBuf, (char*)where.aBuf + ); + + /* Bind the PK values to both statements, and the new.* values to pRet. */ + if( rc==SQLITE_OK ){ + rc = sessionBindRow( + pUp, sqlite3changeset_old, pApply->nCol, pApply->abPK, pRand + ); + } + if( rc==SQLITE_OK ){ + rc = sessionBindRow( + pUp, sqlite3changeset_old, pApply->nCol, pApply->abPK, pRet + ); + } + for(ii=0; rc==SQLITE_OK && ii<pApply->nCol; ii++){ + sqlite3_value *pNew = sessionChangesetNew(pUp, ii); + if( pApply->abPK[ii]==0 && pNew ){ + rc = sessionBindValue(pRet, ii+1, pNew); + } + } + + /* Evaluate the statement to set each modified column of the row to a random + ** value. If this fails with a constraint error, SQLITE_CONSTRAINT is + ** returned to the caller, but pApply->zErr is not set. */ + if( rc==SQLITE_OK ){ + sqlite3_step(pRand); + rc = sqlite3_reset(pRand); + } + sqlite3_finalize(pRand); + + if( rc!=SQLITE_OK ){ + sqlite3_finalize(pRet); + pRet = 0; + } + *ppUpdate = pRet; + + sqlite3_free(aUnique); + sqlite3_free(randset.aBuf); + sqlite3_free(upset.aBuf); + sqlite3_free(where.aBuf); + + return rc; +} + +/* +** Retry the changes accumulated in the pApply->constraints buffer. The +** pApply->constraints buffer contains all changes to table zTab that +** could not be applied due to SQLITE_CONSTRAINT errors. This function +** attempts to apply them as follows: +** +** 1) It runs through the buffer and attempts to retry each change, +** removing any that are successfully applied from the buffer. This +** is repeated until no further progress can be made. +** +** 2) For each UPDATE change in the buffer, try the following in a +** savepoint transaction: +** +** a) UPDATE the affected row, setting each column modified by the +** UPDATE change to a random value, +** b) Attempt step (1) with remaining changes, +** c) Attempt to UPDATE the affected row again, this time setting +** each modified column to the value required by the UPDATE change. +** +** If both (a) and (c) succeed, the savepoint is committed and all +** successfully applied changes are removed from the buffer. Step (2) +** is then repeated. Otherwise, if either (a) or (c) fails with +** SQLITE_CONSTRAINT, the savepoint is rolled back and the next UPDATE +** in the buffer is tried. +** +** 3) Once step (2) has been attempted for each UPDATE in the change, +** a final attempt is made to apply each remaining change. This time, +** if an SQLITE_CONSTRAINT error is encountered, the conflict handler +** is invoked and the user has to decide whether to omit the change +** or rollback the entire _apply() operation. */ static int sessionRetryConstraints( sqlite3 *db, @@ -231330,41 +240598,115 @@ static int sessionRetryConstraints( void *pCtx /* First argument passed to xConflict */ ){ int rc = SQLITE_OK; + int iUpdate = 0; + /* Step (1) */ while( pApply->constraints.nBuf ){ - sqlite3_changeset_iter *pIter2 = 0; SessionBuffer cons = pApply->constraints; memset(&pApply->constraints, 0, sizeof(SessionBuffer)); - rc = sessionChangesetStart( - &pIter2, 0, 0, cons.nBuf, cons.aBuf, pApply->bInvertConstraints, 1 + rc = sessionApplyRetryBuffer( + &cons, -1, db, bPatchset, zTab, pApply, xConflict, pCtx + ); + + sqlite3_free(cons.aBuf); + if( rc!=SQLITE_OK ) break; + + /* If no progress has been made this round, break out of the loop. */ + if( pApply->constraints.nBuf>=cons.nBuf ) break; + } + + /* Step (2) */ + while( rc==SQLITE_OK && pApply->constraints.nBuf && !pApply->bNoUpdateLoop ){ + SessionBuffer cons = {0, 0, 0}; + sqlite3_changeset_iter *pUp = 0; + sqlite3_stmt *pUpdate = 0; + int iSkip = 0; + int bConstraint = 0; /* True if an SQLITE_CONSTRAINT occurs */ + + rc = sessionRetryIterInit( + &pApply->constraints, bPatchset, zTab, pApply, &pUp ); if( rc==SQLITE_OK ){ - size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*); - int rc2; - pIter2->bPatchset = bPatchset; - pIter2->zTab = (char*)zTab; - pIter2->nCol = pApply->nCol; - pIter2->abPK = pApply->abPK; - sessionBufferGrow(&pIter2->tblhdr, nByte, &rc); - pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf; - if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte); + int iThis = -1; + while( SQLITE_ROW==sqlite3changeset_next(pUp) ){ + if( pUp->op==SQLITE_UPDATE ) iThis++; + if( iThis==iUpdate ) break; + iSkip++; + } + if( iThis==iUpdate ){ + rc = sqlite3_exec(db, "SAVEPOINT update_op", 0, 0, 0); + if( rc==SQLITE_OK ){ + rc = sessionUpdateToUpdate(db, zTab, pApply, pUp, &pUpdate); + if( (rc&0xff)==SQLITE_CONSTRAINT ){ + bConstraint = 1; + rc = SQLITE_OK; + } + } + } + sqlite3changeset_finalize(pUp); + if( iThis!=iUpdate ) break; + } - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){ - rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx); + if( rc==SQLITE_OK ){ + cons = pApply->constraints; + if( bConstraint ){ + memset(&pApply->constraints, 0, sizeof(SessionBuffer)); } - rc2 = sqlite3changeset_finalize(pIter2); - if( rc==SQLITE_OK ) rc = rc2; + while( rc==SQLITE_OK && pApply->constraints.nBuf>0 ){ + SessionBuffer app = pApply->constraints; + memset(&pApply->constraints, 0, sizeof(SessionBuffer)); + rc = sessionApplyRetryBuffer( + &app, iSkip, db, bPatchset, zTab, pApply, xConflict, pCtx + ); + if( app.aBuf!=cons.aBuf ){ + sqlite3_free(app.aBuf); + } + if( pApply->constraints.nBuf>=app.nBuf ){ + break; + } + iSkip = -1; + } } - assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 ); - sqlite3_free(cons.aBuf); - if( rc!=SQLITE_OK ) break; - if( pApply->constraints.nBuf>=cons.nBuf ){ - /* No progress was made on the last round. */ - pApply->bDeferConstraints = 0; + iUpdate++; + if( rc==SQLITE_OK ){ + if( bConstraint==0 ){ + sqlite3_step(pUpdate); + rc = sqlite3_finalize(pUpdate); + pUpdate = 0; + if( (rc&0xff)==SQLITE_CONSTRAINT ){ + bConstraint = 1; + rc = SQLITE_OK; + } + } + if( bConstraint ){ + rc = sqlite3_exec(db, "ROLLBACK TO update_op", 0, 0, 0); + sqlite3_free(pApply->constraints.aBuf); + pApply->constraints = cons; + memset(&cons, 0, sizeof(cons)); + }else if( rc==SQLITE_OK ){ + iUpdate = 0; + } + if( rc==SQLITE_OK ){ + rc = sqlite3_exec(db, "RELEASE update_op", 0, 0, 0); + } } + sqlite3_finalize(pUpdate); + + sqlite3_free(cons.aBuf); + } + + /* Step (3) */ + if( rc==SQLITE_OK && pApply->constraints.nBuf ){ + SessionBuffer cons = pApply->constraints; + memset(&pApply->constraints, 0, sizeof(SessionBuffer)); + pApply->bDeferConstraints = 0; + rc = sessionApplyRetryBuffer( + &cons, -1, db, bPatchset, zTab, pApply, xConflict, pCtx + ); + sqlite3_free(cons.aBuf); } return rc; @@ -231384,6 +240726,10 @@ static int sessionChangesetApply( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ ), + int(*xFilterIter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + sqlite3_changeset_iter *p + ), int(*xConflict)( void *pCtx, /* Copy of fifth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ @@ -231396,10 +240742,10 @@ static int sessionChangesetApply( int schemaMismatch = 0; int rc = SQLITE_OK; /* Return code */ const char *zTab = 0; /* Name of current table */ - int nTab = 0; /* Result of sqlite3Strlen30(zTab) */ SessionApplyCtx sApply; /* changeset_apply() context object */ int bPatchset; u64 savedFlag = db->flags & SQLITE_FkNoAction; + int bNew = 0; /* True for first entry of new table */ assert( xConflict!=0 ); @@ -231414,21 +240760,23 @@ static int sessionChangesetApply( sApply.bRebase = (ppRebase && pnRebase); sApply.bInvertConstraints = !!(flags & SQLITE_CHANGESETAPPLY_INVERT); sApply.bIgnoreNoop = !!(flags & SQLITE_CHANGESETAPPLY_IGNORENOOP); + sApply.bNoUpdateLoop = !!(flags & SQLITE_CHANGESETAPPLY_NOUPDATELOOP); if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){ rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0); } if( rc==SQLITE_OK ){ rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0); } - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){ + while( rc==SQLITE_OK && SQLITE_ROW==sessionChangesetNext(pIter, 0, 0,&bNew) ){ int nCol; int op; const char *zNew; sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0); - if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){ + if( bNew ){ u8 *abPK; + bNew = 0; rc = sessionRetryConstraints( db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx @@ -231463,7 +240811,6 @@ static int sessionChangesetApply( rc = SQLITE_NOMEM; break; } - nTab = (int)strlen(zTab); sApply.azCol = (const char **)zTab; }else{ int nMinCol = 0; @@ -231471,7 +240818,8 @@ static int sessionChangesetApply( sqlite3changeset_pk(pIter, &abPK, 0); rc = sessionTableInfo(0, db, "main", zNew, - &sApply.nCol, &zTab, &sApply.azCol, 0, &sApply.abPK, &sApply.bRowid + &sApply.nCol, 0, &zTab, &sApply.azCol, 0, 0, + &sApply.abPK, &sApply.bRowid ); if( rc!=SQLITE_OK ) break; for(i=0; i<sApply.nCol; i++){ @@ -231515,7 +240863,6 @@ static int sessionChangesetApply( sApply.bStat1 = 0; } } - nTab = sqlite3Strlen30(zTab); } } @@ -231523,6 +240870,9 @@ static int sessionChangesetApply( ** next change. A log message has already been issued. */ if( schemaMismatch ) continue; + /* If this is a call to apply_v3(), invoke xFilterIter here. */ + if( xFilterIter && 0==xFilterIter(pCtx, pIter) ) continue; + rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx); } @@ -231551,12 +240901,17 @@ static int sessionChangesetApply( } } } - sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0); + + { + int rc2 = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0); + if( rc==SQLITE_OK ) rc = rc2; + } if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){ if( rc==SQLITE_OK ){ rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0); - }else{ + } + if( rc!=SQLITE_OK ){ sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0); sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0); } @@ -231564,6 +240919,7 @@ static int sessionChangesetApply( assert( sApply.bRebase || sApply.rebase.nBuf==0 ); if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){ + assert( ppRebase!=0 && pnRebase!=0 ); *ppRebase = (void*)sApply.rebase.aBuf; *pnRebase = sApply.rebase.nBuf; sApply.rebase.aBuf = 0; @@ -231581,22 +240937,74 @@ static int sessionChangesetApply( db->flags &= ~((u64)SQLITE_FkNoAction); db->aDb[0].pSchema->schema_cookie -= 32; } + + assert( rc!=SQLITE_OK || sApply.zErr==0 ); + sqlite3_set_errmsg(db, rc, sApply.zErr); + sqlite3_free(sApply.zErr); + sqlite3_mutex_leave(sqlite3_db_mutex(db)); return rc; } /* -** Apply the changeset passed via pChangeset/nChangeset to the main -** database attached to handle "db". +** This function is called by all six sqlite3changeset_apply() variants: +** +** + sqlite3changeset_apply() +** + sqlite3changeset_apply_v2() +** + sqlite3changeset_apply_v3() +** + sqlite3changeset_apply_strm() +** + sqlite3changeset_apply_strm_v2() +** + sqlite3changeset_apply_strm_v3() +** +** Arguments passed to this function are as follows: +** +** db: +** Database handle to apply changeset to main database of. +** +** nChangeset/pChangeset: +** These are both passed zero for the streaming variants. For the normal +** apply() functions, these are passed the size of and the buffer containing +** the changeset, respectively. +** +** xInput/pIn: +** These are both passed zero for the normal variants. For the streaming +** apply() functions, these are passed the input callback and context +** pointer, respectively. +** +** xFilter: +** The filter function as passed to apply() or apply_v2() (to filter by +** table name), if any. This is always NULL for apply_v3() calls. +** +** xFilterIter: +** The filter function as passed to apply_v3(), if any. +** +** xConflict: +** The conflict handler callback (must not be NULL). +** +** pCtx: +** The context pointer passed to the xFilter and xConflict handler callbacks. +** +** ppRebase, pnRebase: +** Zero for apply(). The rebase changeset output pointers, if any, for +** apply_v2() and apply_v3(). +** +** flags: +** Zero for apply(). The flags parameter for apply_v2() and apply_v3(). */ -SQLITE_API int sqlite3changeset_apply_v2( +static int sessionChangesetApplyV23( sqlite3 *db, /* Apply change to "main" db of this handle */ int nChangeset, /* Size of changeset in bytes */ void *pChangeset, /* Changeset blob */ + int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ + void *pIn, /* First arg for xInput */ int(*xFilter)( void *pCtx, /* Copy of sixth arg to _apply() */ const char *zTab /* Table name */ ), + int(*xFilterIter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + sqlite3_changeset_iter *p /* Handle describing current change */ + ), int(*xConflict)( void *pCtx, /* Copy of sixth arg to _apply() */ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ @@ -231607,18 +241015,74 @@ SQLITE_API int sqlite3changeset_apply_v2( int flags ){ sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */ - int bInv = !!(flags & SQLITE_CHANGESETAPPLY_INVERT); - int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset, bInv, 1); - + int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT); + int rc = sessionChangesetStart( + &pIter, xInput, pIn, nChangeset, pChangeset, bInverse, 1 + ); if( rc==SQLITE_OK ){ - rc = sessionChangesetApply( - db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags + rc = sessionChangesetApply(db, pIter, + xFilter, xFilterIter, xConflict, pCtx, ppRebase, pnRebase, flags ); } - return rc; } +/* +** Apply the changeset passed via pChangeset/nChangeset to the main +** database attached to handle "db". +*/ +SQLITE_API int sqlite3changeset_apply_v2( + sqlite3 *db, /* Apply change to "main" db of this handle */ + int nChangeset, /* Size of changeset in bytes */ + void *pChangeset, /* Changeset blob */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + const char *zTab /* Table name */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, + int flags +){ + return sessionChangesetApplyV23(db, + nChangeset, pChangeset, 0, 0, + xFilter, 0, xConflict, pCtx, + ppRebase, pnRebase, flags + ); +} + +/* +** Apply the changeset passed via pChangeset/nChangeset to the main +** database attached to handle "db". +*/ +SQLITE_API int sqlite3changeset_apply_v3( + sqlite3 *db, /* Apply change to "main" db of this handle */ + int nChangeset, /* Size of changeset in bytes */ + void *pChangeset, /* Changeset blob */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + sqlite3_changeset_iter *p /* Handle describing current change */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, + int flags +){ + return sessionChangesetApplyV23(db, + nChangeset, pChangeset, 0, 0, + 0, xFilter, xConflict, pCtx, + ppRebase, pnRebase, flags + ); +} + /* ** Apply the changeset passed via pChangeset/nChangeset to the main database ** attached to handle "db". Invoke the supplied conflict handler callback @@ -231639,8 +241103,10 @@ SQLITE_API int sqlite3changeset_apply( ), void *pCtx /* First argument passed to xConflict */ ){ - return sqlite3changeset_apply_v2( - db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0 + return sessionChangesetApplyV23(db, + nChangeset, pChangeset, 0, 0, + xFilter, 0, xConflict, pCtx, + 0, 0, 0 ); } @@ -231649,6 +241115,29 @@ SQLITE_API int sqlite3changeset_apply( ** attached to handle "db". Invoke the supplied conflict handler callback ** to resolve any conflicts encountered while applying the change. */ +SQLITE_API int sqlite3changeset_apply_v3_strm( + sqlite3 *db, /* Apply change to "main" db of this handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ + void *pIn, /* First arg for xInput */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + sqlite3_changeset_iter *p + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, + int flags +){ + return sessionChangesetApplyV23(db, + 0, 0, xInput, pIn, + 0, xFilter, xConflict, pCtx, + ppRebase, pnRebase, flags + ); +} SQLITE_API int sqlite3changeset_apply_v2_strm( sqlite3 *db, /* Apply change to "main" db of this handle */ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ @@ -231666,15 +241155,11 @@ SQLITE_API int sqlite3changeset_apply_v2_strm( void **ppRebase, int *pnRebase, int flags ){ - sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */ - int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT); - int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse, 1); - if( rc==SQLITE_OK ){ - rc = sessionChangesetApply( - db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags - ); - } - return rc; + return sessionChangesetApplyV23(db, + 0, 0, xInput, pIn, + xFilter, 0, xConflict, pCtx, + ppRebase, pnRebase, flags + ); } SQLITE_API int sqlite3changeset_apply_strm( sqlite3 *db, /* Apply change to "main" db of this handle */ @@ -231691,11 +241176,28 @@ SQLITE_API int sqlite3changeset_apply_strm( ), void *pCtx /* First argument passed to xConflict */ ){ - return sqlite3changeset_apply_v2_strm( - db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0 + return sessionChangesetApplyV23(db, + 0, 0, xInput, pIn, + xFilter, 0, xConflict, pCtx, + 0, 0, 0 ); } +/* +** The parts of the sqlite3_changegroup structure used by the +** sqlite3changegroup_change_xxx() APIs. +*/ +typedef struct ChangeData ChangeData; +struct ChangeData { + SessionTable *pTab; + int bIndirect; + int eOp; + + int nBufAlloc; + SessionBuffer *aBuf; + SessionBuffer record; +}; + /* ** sqlite3_changegroup handle. */ @@ -231707,12 +241209,17 @@ struct sqlite3_changegroup { sqlite3 *db; /* Configured by changegroup_schema() */ char *zDb; /* Configured by changegroup_schema() */ + ChangeData cd; /* Used by changegroup_change_xxx() APIs. */ }; /* ** This function is called to merge two changes to the same row together as ** part of an sqlite3changeset_concat() operation. A new change object is ** allocated and a pointer to it stored in *ppNew. +** +** Because they have been vetted by sqlite3changegroup_add() or similar, +** both the aRec[] change and the pExist change are safe to use without +** checking for buffer overflows. */ static int sessionChangeMerge( SessionTable *pTab, /* Table structure */ @@ -231853,7 +241360,7 @@ static int sessionChangeMerge( memcpy(aCsr, aRec, nRec); aCsr += nRec; }else{ - if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){ + if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist,0,aRec,0) ){ sqlite3_free(pNew); pNew = 0; } @@ -231946,15 +241453,14 @@ static int sessionChangesetExtendRecord( switch( eType ){ case SQLITE_FLOAT: case SQLITE_INTEGER: { - i64 iVal; - if( eType==SQLITE_INTEGER ){ - iVal = sqlite3_column_int64(pTab->pDfltStmt, ii); - }else{ - double rVal = sqlite3_column_int64(pTab->pDfltStmt, ii); - memcpy(&iVal, &rVal, sizeof(i64)); - } if( SQLITE_OK==sessionBufferGrow(pOut, 8, &rc) ){ - sessionPutI64(&pOut->aBuf[pOut->nBuf], iVal); + if( eType==SQLITE_INTEGER ){ + sqlite3_int64 iVal = sqlite3_column_int64(pTab->pDfltStmt, ii); + sessionPutI64(&pOut->aBuf[pOut->nBuf], iVal); + }else{ + double rVal = sqlite3_column_double(pTab->pDfltStmt, ii); + sessionPutDouble(&pOut->aBuf[pOut->nBuf], rVal); + } pOut->nBuf += 8; } break; @@ -232025,13 +241531,19 @@ static int sessionChangesetFindTable( int nCol = 0; *ppTab = 0; - sqlite3changeset_pk(pIter, &abPK, &nCol); /* Search the list for an existing table */ for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){ if( 0==sqlite3_strnicmp(pTab->zName, zTab, nTab+1) ) break; } + + if( pIter ){ + sqlite3changeset_pk(pIter, &abPK, &nCol); + }else if( !pTab && !pGrp->db ){ + return SQLITE_ERROR; + } + /* If one was not found above, create a new table now */ if( !pTab ){ SessionTable **ppNew; @@ -232043,17 +241555,19 @@ static int sessionChangesetFindTable( memset(pTab, 0, sizeof(SessionTable)); pTab->nCol = nCol; pTab->abPK = (u8*)&pTab[1]; - memcpy(pTab->abPK, abPK, nCol); + if( nCol>0 ){ + memcpy(pTab->abPK, abPK, nCol); + } pTab->zName = (char*)&pTab->abPK[nCol]; memcpy(pTab->zName, zTab, nTab+1); if( pGrp->db ){ pTab->nCol = 0; rc = sessionInitTable(0, pTab, pGrp->db, pGrp->zDb); - if( rc ){ - assert( pTab->azCol==0 ); + if( rc || pTab->nCol==0 ){ + sqlite3_free(pTab->azCol); sqlite3_free(pTab); - return rc; + return rc ? rc : SQLITE_ERROR; } } @@ -232066,7 +241580,7 @@ static int sessionChangesetFindTable( } /* Check that the table is compatible. */ - if( !sessionChangesetCheckCompat(pTab, nCol, abPK) ){ + if( pIter && !sessionChangesetCheckCompat(pTab, nCol, abPK) ){ rc = SQLITE_SCHEMA; } @@ -232075,44 +241589,27 @@ static int sessionChangesetFindTable( } /* -** Add the change currently indicated by iterator pIter to the hash table -** belonging to changegroup pGrp. +** Add a single change to the changegroup pGrp. */ static int sessionOneChangeToHash( - sqlite3_changegroup *pGrp, - sqlite3_changeset_iter *pIter, - int bRebase + sqlite3_changegroup *pGrp, /* Changegroup to update */ + SessionTable *pTab, /* Table change pertains to */ + int op, /* One of SQLITE_INSERT, UPDATE, DELETE */ + int bIndirect, /* True to flag change as "indirect" */ + int nCol, /* Number of columns in record(s) */ + u8 *aRec, /* Serialized change record(s) */ + int nRec, /* Size of aRec[] in bytes */ + int bRebase /* True if this is a rebase blob */ ){ int rc = SQLITE_OK; - int nCol = 0; - int op = 0; int iHash = 0; - int bIndirect = 0; SessionChange *pChange = 0; SessionChange *pExist = 0; SessionChange **pp = 0; - SessionTable *pTab = 0; - u8 *aRec = &pIter->in.aData[pIter->in.iCurrent + 2]; - int nRec = (pIter->in.iNext - pIter->in.iCurrent) - 2; assert( nRec>0 ); - /* Ensure that only changesets, or only patchsets, but not a mixture - ** of both, are being combined. It is an error to try to combine a - ** changeset and a patchset. */ - if( pGrp->pList==0 ){ - pGrp->bPatch = pIter->bPatchset; - }else if( pIter->bPatchset!=pGrp->bPatch ){ - rc = SQLITE_ERROR; - } - - if( rc==SQLITE_OK ){ - const char *zTab = 0; - sqlite3changeset_op(pIter, &zTab, &nCol, &op, &bIndirect); - rc = sessionChangesetFindTable(pGrp, zTab, pIter, &pTab); - } - - if( rc==SQLITE_OK && nCol<pTab->nCol ){ + if( nCol<pTab->nCol ){ SessionBuffer *pBuf = &pGrp->rec; rc = sessionChangesetExtendRecord(pGrp, pTab, nCol, op, aRec, nRec, pBuf); aRec = pBuf->aBuf; @@ -232120,7 +241617,7 @@ static int sessionOneChangeToHash( assert( pGrp->db ); } - if( rc==SQLITE_OK && sessionGrowHash(0, pIter->bPatchset, pTab) ){ + if( rc==SQLITE_OK && sessionGrowHash(0, pGrp->bPatch, pTab) ){ rc = SQLITE_NOMEM; } @@ -232128,12 +241625,12 @@ static int sessionOneChangeToHash( /* Search for existing entry. If found, remove it from the hash table. ** Code below may link it back in. */ iHash = sessionChangeHash( - pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange + pTab, (pGrp->bPatch && op==SQLITE_DELETE), aRec, pTab->nChange ); for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){ int bPkOnly1 = 0; int bPkOnly2 = 0; - if( pIter->bPatchset ){ + if( pGrp->bPatch ){ bPkOnly1 = (*pp)->op==SQLITE_DELETE; bPkOnly2 = op==SQLITE_DELETE; } @@ -232148,7 +241645,7 @@ static int sessionOneChangeToHash( if( rc==SQLITE_OK ){ rc = sessionChangeMerge(pTab, bRebase, - pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange + pGrp->bPatch, pExist, op, bIndirect, aRec, nRec, &pChange ); } if( rc==SQLITE_OK && pChange ){ @@ -232157,6 +241654,47 @@ static int sessionOneChangeToHash( pTab->nEntry++; } + return rc; +} + +/* +** Add the change currently indicated by iterator pIter to the hash table +** belonging to changegroup pGrp. +*/ +static int sessionOneChangeIterToHash( + sqlite3_changegroup *pGrp, + sqlite3_changeset_iter *pIter, + int bRebase +){ + u8 *aRec = &pIter->in.aData[pIter->in.iCurrent + 2]; + int nRec = (pIter->in.iNext - pIter->in.iCurrent) - 2; + const char *zTab = 0; + int nCol = 0; + int op = 0; + int bIndirect = 0; + int rc = SQLITE_OK; + SessionTable *pTab = 0; + + /* Ensure that only changesets, or only patchsets, but not a mixture + ** of both, are being combined. It is an error to try to combine a + ** changeset and a patchset. */ + if( pGrp->pList==0 ){ + pGrp->bPatch = pIter->bPatchset; + }else if( pIter->bPatchset!=pGrp->bPatch ){ + rc = SQLITE_ERROR; + } + + if( rc==SQLITE_OK ){ + sqlite3changeset_op(pIter, &zTab, &nCol, &op, &bIndirect); + rc = sessionChangesetFindTable(pGrp, zTab, pIter, &pTab); + } + + if( rc==SQLITE_OK ){ + rc = sessionOneChangeToHash( + pGrp, pTab, op, bIndirect, nCol, aRec, nRec, bRebase + ); + } + if( rc==SQLITE_OK ) rc = pIter->rc; return rc; } @@ -232176,7 +241714,12 @@ static int sessionChangesetToHash( pIter->in.bNoDiscard = 1; while( SQLITE_ROW==(sessionChangesetNext(pIter, &aRec, &nRec, 0)) ){ - rc = sessionOneChangeToHash(pGrp, pIter, bRebase); + if( bRebase && pIter->bPatchset ){ + /* A patchset may not be used as a rebase */ + rc = SQLITE_ERROR; + }else{ + rc = sessionOneChangeIterToHash(pGrp, pIter, bRebase); + } if( rc!=SQLITE_OK ) break; } @@ -232266,6 +241809,33 @@ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){ return rc; } +/* +** Configure a changegroup object. +*/ +SQLITE_API int sqlite3changegroup_config( + sqlite3_changegroup *pGrp, + int op, + void *pArg +){ + int rc = SQLITE_OK; + + switch( op ){ + case SQLITE_CHANGEGROUP_CONFIG_PATCHSET: { + int arg = *(int*)pArg; + if( pGrp->pList==0 && arg>=0 ){ + pGrp->bPatch = (arg>0); + } + *(int*)pArg = pGrp->bPatch; + break; + } + default: + rc = SQLITE_MISUSE; + break; + } + + return rc; +} + /* ** Provide a database schema to the changegroup object. */ @@ -232314,14 +241884,19 @@ SQLITE_API int sqlite3changegroup_add_change( sqlite3_changegroup *pGrp, sqlite3_changeset_iter *pIter ){ + int rc = SQLITE_OK; + if( pIter->in.iCurrent==pIter->in.iNext || pIter->rc!=SQLITE_OK || pIter->bInvert ){ /* Iterator does not point to any valid entry or is an INVERT iterator. */ - return SQLITE_ERROR; + rc = SQLITE_ERROR; + }else{ + pIter->in.bNoDiscard = 1; + rc = sessionOneChangeIterToHash(pGrp, pIter, 0); } - return sessionOneChangeToHash(pGrp, pIter, 0); + return rc; } /* @@ -232371,6 +241946,12 @@ SQLITE_API int sqlite3changegroup_output_strm( */ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){ if( pGrp ){ + int ii; + for(ii=0; ii<pGrp->cd.nBufAlloc; ii++){ + sqlite3_free(pGrp->cd.aBuf[ii].aBuf); + } + sqlite3_free(pGrp->cd.record.aBuf); + sqlite3_free(pGrp->cd.aBuf); sqlite3_free(pGrp->zDb); sessionDeleteTable(0, pGrp->pList); sqlite3_free(pGrp->rec.aBuf); @@ -232456,14 +242037,17 @@ static void sessionAppendRecordMerge( u8 *a2, int n2, /* Record 2 */ int *pRc /* IN/OUT: error code */ ){ - sessionBufferGrow(pBuf, n1+n2, pRc); + u8 *a1Eof = &a1[n1]; + u8 *a2Eof = &a2[n2]; + + sessionBufferGrow(pBuf, (i64)n1+n2, pRc); if( *pRc==SQLITE_OK ){ int i; u8 *pOut = &pBuf->aBuf[pBuf->nBuf]; for(i=0; i<nCol; i++){ - int nn1 = sessionSerialLen(a1); - int nn2 = sessionSerialLen(a2); - if( *a1==0 || *a1==0xFF ){ + int nn1 = (a1<a1Eof ? sessionSerialLen(a1) : 0); + int nn2 = (a2<a2Eof ? sessionSerialLen(a2) : 0); + if( nn1==0 || (nn2>0 && (*a1==0 || *a1==0xFF)) ){ memcpy(pOut, a2, nn2); pOut += nn2; }else{ @@ -232505,20 +242089,21 @@ static void sessionAppendPartialUpdate( u8 *aChange, int nChange, /* Record to rebase against */ int *pRc /* IN/OUT: Return Code */ ){ - sessionBufferGrow(pBuf, 2+nRec+nChange, pRc); + sessionBufferGrow(pBuf, (i64)2+nRec+nChange, pRc); if( *pRc==SQLITE_OK ){ int bData = 0; u8 *pOut = &pBuf->aBuf[pBuf->nBuf]; int i; u8 *a1 = aRec; u8 *a2 = aChange; + u8 *a2Eof = &a2[nChange]; *pOut++ = SQLITE_UPDATE; *pOut++ = pIter->bIndirect; for(i=0; i<pIter->nCol; i++){ int n1 = sessionSerialLen(a1); - int n2 = sessionSerialLen(a2); - if( pIter->abPK[i] || a2[0]==0 ){ + int n2 = (a2>=a2Eof) ? 0 : sessionSerialLen(a2); + if( n2<=0 || pIter->abPK[i] || a2[0]==0 ){ if( !pIter->abPK[i] && a1[0] ) bData = 1; memcpy(pOut, a1, n1); pOut += n1; @@ -232719,8 +242304,8 @@ SQLITE_API int sqlite3rebaser_configure( sqlite3_rebaser *p, int nRebase, const void *pRebase ){ - sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */ int rc; /* Return code */ + sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */ rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase); if( rc==SQLITE_OK ){ rc = sessionChangesetToHash(pIter, &p->grp, 1); @@ -232801,12 +242386,356 @@ SQLITE_API int sqlite3session_config(int op, void *pArg){ return rc; } +/* +** Begin adding a change to a changegroup object. +*/ +SQLITE_API int sqlite3changegroup_change_begin( + sqlite3_changegroup *pGrp, + int eOp, + const char *zTab, + int bIndirect, + char **pzErr +){ + SessionTable *pTab = 0; + int rc = SQLITE_OK; + + if( pGrp->cd.pTab ){ + rc = SQLITE_MISUSE; + }else if( eOp!=SQLITE_INSERT && eOp!=SQLITE_UPDATE && eOp!=SQLITE_DELETE ){ + rc = SQLITE_ERROR; + }else{ + rc = sessionChangesetFindTable(pGrp, zTab, 0, &pTab); + if( pTab==0 && pzErr ){ + *pzErr = sqlite3_mprintf("no such table: %s", zTab); + } + } + if( rc==SQLITE_OK ){ + int nReq = pTab->nCol * (eOp==SQLITE_UPDATE ? 2 : 1); + pGrp->cd.pTab = pTab; + pGrp->cd.eOp = eOp; + pGrp->cd.bIndirect = bIndirect; + + if( pGrp->cd.nBufAlloc<nReq ){ + SessionBuffer *aBuf = (SessionBuffer*)sqlite3_realloc( + pGrp->cd.aBuf, nReq * sizeof(SessionBuffer) + ); + if( aBuf==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(&aBuf[pGrp->cd.nBufAlloc], 0, + sizeof(SessionBuffer) * (nReq - pGrp->cd.nBufAlloc) + ); + pGrp->cd.aBuf = aBuf; + pGrp->cd.nBufAlloc = nReq; + } + } + +#ifdef SQLITE_DEBUG + { + /* Assert that all column values are currently undefined */ + int ii; + for(ii=0; ii<pGrp->cd.nBufAlloc; ii++){ + assert( pGrp->cd.aBuf[ii].nBuf==0 ); + } + } +#endif + } + + return rc; +} + +/* +** This function does processing common to the _change_int64(), _change_text() +** and other similar APIs. +*/ +static int checkChangeParams( + sqlite3_changegroup *pGrp, + int bNew, + int iCol, + sqlite3_int64 nReq, + SessionBuffer **ppBuf +){ + int rc = SQLITE_OK; + if( pGrp->cd.pTab==0 ){ + rc = SQLITE_MISUSE; + }else if( iCol<0 || iCol>=pGrp->cd.pTab->nCol ){ + rc = SQLITE_RANGE; + }else if( + (bNew && pGrp->cd.eOp==SQLITE_DELETE) + || (!bNew && pGrp->cd.eOp==SQLITE_INSERT) + ){ + rc = SQLITE_ERROR; + }else{ + SessionBuffer *pBuf = &pGrp->cd.aBuf[iCol]; + if( pGrp->cd.eOp==SQLITE_UPDATE && bNew ){ + pBuf += pGrp->cd.pTab->nCol; + } + pBuf->nBuf = 0; + sessionBufferGrow(pBuf, nReq, &rc); + pBuf->nBuf = nReq; + *ppBuf = pBuf; + } + return rc; +} + +/* +** Configure the change currently under construction with an integer value. +*/ +SQLITE_API int sqlite3changegroup_change_int64( + sqlite3_changegroup *pGrp, + int bNew, + int iCol, + sqlite3_int64 iVal +){ + int rc = SQLITE_OK; + SessionBuffer *pBuf = 0; + + if( SQLITE_OK!=(rc = checkChangeParams(pGrp, bNew, iCol, 9, &pBuf)) ){ + return rc; + } + + pBuf->aBuf[0] = SQLITE_INTEGER; + sessionPutI64(&pBuf->aBuf[1], iVal); + return SQLITE_OK; +} + +/* +** Configure the change currently under construction with a null value. +*/ +SQLITE_API int sqlite3changegroup_change_null( + sqlite3_changegroup *pGrp, + int bNew, + int iCol +){ + int rc = SQLITE_OK; + SessionBuffer *pBuf = 0; + + if( SQLITE_OK!=(rc = checkChangeParams(pGrp, bNew, iCol, 1, &pBuf)) ){ + return rc; + } + + pBuf->aBuf[0] = SQLITE_NULL; + return SQLITE_OK; +} + +/* +** Configure the change currently under construction with a real value. +*/ +SQLITE_API int sqlite3changegroup_change_double( + sqlite3_changegroup *pGrp, + int bNew, + int iCol, + double fVal +){ + int rc = SQLITE_OK; + SessionBuffer *pBuf = 0; + + if( SQLITE_OK!=(rc = checkChangeParams(pGrp, bNew, iCol, 9, &pBuf)) ){ + return rc; + } + + pBuf->aBuf[0] = SQLITE_FLOAT; + sessionPutDouble(&pBuf->aBuf[1], fVal); + return SQLITE_OK; +} + +/* +** Configure the change currently under construction with a text value. +*/ +SQLITE_API int sqlite3changegroup_change_text( + sqlite3_changegroup *pGrp, + int bNew, + int iCol, + const char *pVal, + int nVal +){ + sqlite3_int64 nText = nVal>=0 ? nVal : strlen(pVal); + sqlite3_int64 nByte = 1 + sessionVarintLen(nText) + nText; + int rc = SQLITE_OK; + SessionBuffer *pBuf = 0; + + if( SQLITE_OK!=(rc = checkChangeParams(pGrp, bNew, iCol, nByte, &pBuf)) ){ + return rc; + } + + pBuf->aBuf[0] = SQLITE_TEXT; + pBuf->nBuf = (1 + sessionVarintPut(&pBuf->aBuf[1], nText)); + memcpy(&pBuf->aBuf[pBuf->nBuf], pVal, nText); + pBuf->nBuf += nText; + + return SQLITE_OK; +} + +/* +** Configure the change currently under construction with a blob value. +*/ +SQLITE_API int sqlite3changegroup_change_blob( + sqlite3_changegroup *pGrp, + int bNew, + int iCol, + const void *pVal, + int nVal +){ + sqlite3_int64 nByte = 1 + sessionVarintLen(nVal) + (i64)nVal; + int rc = SQLITE_OK; + SessionBuffer *pBuf = 0; + + if( SQLITE_OK!=(rc = checkChangeParams(pGrp, bNew, iCol, nByte, &pBuf)) ){ + return rc; + } + + pBuf->aBuf[0] = SQLITE_BLOB; + pBuf->nBuf = (1 + sessionVarintPut(&pBuf->aBuf[1], nVal)); + memcpy(&pBuf->aBuf[pBuf->nBuf], pVal, nVal); + pBuf->nBuf += nVal; + + return SQLITE_OK; +} + +/* +** Finish any change currently being constructed by the changegroup object. +*/ +SQLITE_API int sqlite3changegroup_change_finish( + sqlite3_changegroup *pGrp, + int bDiscard, + char **pzErr +){ + int rc = SQLITE_OK; + char *zErr = 0; + if( pGrp->cd.pTab ){ + SessionBuffer *aBuf = pGrp->cd.aBuf; + int ii; + + if( bDiscard==0 ){ + int nBuf = pGrp->cd.pTab->nCol; + u8 eUndef = SQLITE_NULL; + if( pGrp->cd.eOp==SQLITE_UPDATE ){ + for(ii=0; ii<nBuf; ii++){ + if( pGrp->cd.pTab->abPK[ii] ){ + if( aBuf[ii].nBuf<=1 ){ + zErr = sqlite3_mprintf( + "invalid change: %s value in PK of old.* record", + aBuf[ii].nBuf==1 ? "null" : "undefined" + ); + rc = SQLITE_ERROR; + break; + }else if( aBuf[ii + nBuf].nBuf>0 ){ + zErr = sqlite3_mprintf( + "invalid change: defined value in PK of new.* record" + ); + rc = SQLITE_ERROR; + break; + } + }else + if( pGrp->bPatch==0 && (aBuf[ii].nBuf>0)!=(aBuf[ii+nBuf].nBuf>0) ){ + zErr = sqlite3_mprintf( + "invalid change: column %d " + "- old.* value is %sdefined but new.* is %sdefined", + ii, aBuf[ii].nBuf ? "" : "un", aBuf[ii+nBuf].nBuf ? "" : "un" + ); + rc = SQLITE_ERROR; + break; + } + } + eUndef = 0x00; + if( pGrp->bPatch==0 ) nBuf = nBuf * 2; + }else{ + for(ii=0; ii<nBuf; ii++){ + int isPK = pGrp->cd.pTab->abPK[ii]; + if( (pGrp->cd.eOp==SQLITE_INSERT || pGrp->bPatch==0 || isPK) + && aBuf[ii].nBuf==0 + ){ + zErr = sqlite3_mprintf( + "invalid change: column %d is undefined", ii + ); + rc = SQLITE_ERROR; + break; + } + if( aBuf[ii].nBuf==1 && isPK ){ + zErr = sqlite3_mprintf( + "invalid change: null value in PK" + ); + rc = SQLITE_ERROR; + break; + } + } + } + + pGrp->cd.record.nBuf = 0; + for(ii=0; ii<nBuf; ii++){ + SessionBuffer *p = &pGrp->cd.aBuf[ii]; + if( pGrp->bPatch ){ + if( pGrp->cd.pTab->abPK[ii]==0 ){ + if( pGrp->cd.eOp==SQLITE_UPDATE ){ + p += pGrp->cd.pTab->nCol; + }else if( pGrp->cd.eOp==SQLITE_DELETE ){ + continue; + } + } + } + if( 0==sessionBufferGrow(&pGrp->cd.record, p->nBuf?p->nBuf:1, &rc) ){ + if( p->nBuf ){ + memcpy(&pGrp->cd.record.aBuf[pGrp->cd.record.nBuf],p->aBuf,p->nBuf); + pGrp->cd.record.nBuf += p->nBuf; + }else{ + pGrp->cd.record.aBuf[pGrp->cd.record.nBuf++] = eUndef; + } + } + } + if( rc==SQLITE_OK ){ + rc = sessionOneChangeToHash( + pGrp, pGrp->cd.pTab, + pGrp->cd.eOp, pGrp->cd.bIndirect, pGrp->cd.pTab->nCol, + pGrp->cd.record.aBuf, pGrp->cd.record.nBuf, 0 + ); + } + } + + /* Reset all aBuf[] entries to "undefined". */ + { + int nZero = pGrp->cd.pTab->nCol; + if( pGrp->cd.eOp==SQLITE_UPDATE ) nZero += nZero; + for(ii=0; ii<nZero; ii++){ + pGrp->cd.aBuf[ii].nBuf = 0; + } + } + pGrp->cd.pTab = 0; + } + + if( pzErr ){ + *pzErr = zErr; + }else{ + sqlite3_free(zErr); + } + return rc; +} + #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */ /************** End of sqlite3session.c **************************************/ /************** Begin file fts5.c ********************************************/ - +/* +** This, the "fts5.c" source file, is a composite file that is itself +** assembled from the following files: +** +** fts5.h +** fts5Int.h +** fts5parse.h <--- Generated from fts5parse.y by Lemon +** fts5parse.c <--- Generated from fts5parse.y by Lemon +** fts5_aux.c +** fts5_buffer.c +** fts5_config.c +** fts5_expr.c +** fts5_hash.c +** fts5_index.c +** fts5_main.c +** fts5_storage.c +** fts5_tokenize.c +** fts5_unicode2.c +** fts5_varint.c +** fts5_vocab.c +*/ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) @@ -232816,6 +242745,12 @@ SQLITE_API int sqlite3session_config(int op, void *pArg){ # undef NDEBUG #endif +#ifdef HAVE_STDINT_H +/* #include <stdint.h> */ +#endif +#ifdef HAVE_INTTYPES_H +/* #include <inttypes.h> */ +#endif /* ** 2014 May 31 ** @@ -233116,14 +243051,29 @@ struct Fts5PhraseIter { ** value returned by xInstCount(), SQLITE_RANGE is returned. Otherwise, ** output variable (*ppToken) is set to point to a buffer containing the ** matching document token, and (*pnToken) to the size of that buffer in -** bytes. This API is not available if the specified token matches a -** prefix query term. In that case both output variables are always set -** to 0. +** bytes. ** ** The output text is not a copy of the document text that was tokenized. ** It is the output of the tokenizer module. For tokendata=1 tables, this ** includes any embedded 0x00 and trailing data. ** +** This API may be slow in some cases if the token identified by parameters +** iIdx and iToken matched a prefix token in the query. In most cases, the +** first call to this API for each prefix token in the query is forced +** to scan the portion of the full-text index that matches the prefix +** token to collect the extra data required by this API. If the prefix +** token matches a large number of token instances in the document set, +** this may be a performance problem. +** +** If the user knows in advance that a query may use this API for a +** prefix token, FTS5 may be configured to collect all required data as part +** of the initial querying of the full-text index, avoiding the second scan +** entirely. This also causes prefix queries that do not use this API to +** run more slowly and use more memory. FTS5 may be configured in this way +** either on a per-table basis using the [FTS5 insttoken | 'insttoken'] +** option, or on a per-query basis using the +** [fts5_insttoken | fts5_insttoken()] user function. +** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. ** @@ -233578,6 +243528,7 @@ SQLITE_EXTENSION_INIT1 /* #include <string.h> */ /* #include <assert.h> */ +/* #include <stddef.h> */ #ifndef SQLITE_AMALGAMATION @@ -233617,23 +243568,34 @@ typedef sqlite3_uint64 u64; # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) -/* The uptr type is an unsigned integer large enough to hold a pointer +/* +** This macro is used in a single assert() within fts5 to check that an +** allocation is aligned to an 8-byte boundary. But it is a complicated +** macro to get right for multiple platforms without generating warnings. +** So instead of reproducing the entire definition from sqliteInt.h, we +** just do without this assert() for the rare non-amalgamation builds. */ -#if defined(HAVE_STDINT_H) - typedef uintptr_t uptr; -#elif SQLITE_PTRSIZE==4 - typedef u32 uptr; -#else - typedef u64 uptr; -#endif +#define EIGHT_BYTE_ALIGNMENT(x) 1 -#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC -# define EIGHT_BYTE_ALIGNMENT(X) ((((uptr)(X) - (uptr)0)&3)==0) +/* +** Macros needed to provide flexible arrays in a portable way +*/ +#ifndef offsetof +# define offsetof(ST,M) ((size_t)((char*)&((ST*)0)->M - (char*)0)) +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) +# define FLEXARRAY #else -# define EIGHT_BYTE_ALIGNMENT(X) ((((uptr)(X) - (uptr)0)&7)==0) +# define FLEXARRAY 1 #endif -#endif +#endif /* SQLITE_AMALGAMATION */ + +/* +** Constants for the largest and smallest possible 32-bit signed integers. +*/ +# define LARGEST_INT32 ((int)(0x7fffffff)) +# define SMALLEST_INT32 ((int)((-1) - LARGEST_INT32)) /* Truncate very long tokens to this many bytes. Hard limit is ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset @@ -233705,10 +243667,11 @@ typedef struct Fts5Colset Fts5Colset; */ struct Fts5Colset { int nCol; - int aiCol[1]; + int aiCol[FLEXARRAY]; }; - +/* Size (int bytes) of a complete Fts5Colset object with N columns. */ +#define SZ_FTS5COLSET(N) (sizeof(i64)*((N+2)/2)) /************************************************************************** ** Interface to code in fts5_config.c. fts5_config.c contains contains code @@ -233805,7 +243768,8 @@ struct Fts5Config { char *zRank; /* Name of rank function */ char *zRankArgs; /* Arguments to rank function */ int bSecureDelete; /* 'secure-delete' */ - int nDeleteMerge; /* 'deletemerge' */ + int nDeleteMerge; /* 'deletemerge' */ + int bPrefixInsttoken; /* 'prefix-insttoken' */ /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */ char **pzErrmsg; @@ -234062,7 +244026,14 @@ static int sqlite3Fts5StructureTest(Fts5Index*, void*); /* ** Used by xInstToken(): */ -static int sqlite3Fts5IterToken(Fts5IndexIter*, i64, int, int, const char**, int*); +static int sqlite3Fts5IterToken( + Fts5IndexIter *pIndexIter, + const char *pToken, int nToken, + i64 iRowid, + int iCol, + int iOff, + const char **ppOut, int *pnOut +); /* ** Insert or remove data to or from the index. Each time a document is @@ -234358,7 +244329,7 @@ static int sqlite3Fts5ExprPattern( ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr); ** } */ -static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc); +static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, i64, int bDesc); static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax); static int sqlite3Fts5ExprEof(Fts5Expr*); static i64 sqlite3Fts5ExprRowid(Fts5Expr*); @@ -234529,10 +244500,10 @@ static void sqlite3Fts5UnicodeAscii(u8*, u8*); ** ** The "lemon" program processes an LALR(1) input grammar file, then uses ** this template to construct a parser. The "lemon" program inserts text -** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the +** at each "%%" line. Also, any "P-a-r-s-e" identifier prefix (without the ** interstitial "-" characters) contained in this template is changed into ** the value of the %name directive from the grammar. Otherwise, the content -** of this template is copied straight through into the generate parser +** of this template is copied straight through into the generated parser ** source file. ** ** The following is the concatenation of all %include directives from the @@ -234669,14 +244640,22 @@ typedef union { #define sqlite3Fts5ParserARG_PARAM ,pParse #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse=fts5yypParser->pParse; #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse=pParse; +#undef fts5YYREALLOC #define fts5YYREALLOC realloc +#undef fts5YYFREE #define fts5YYFREE free +#undef fts5YYDYNSTACK #define fts5YYDYNSTACK 0 +#undef fts5YYSIZELIMIT +#define sqlite3Fts5ParserCTX(P) 0 #define sqlite3Fts5ParserCTX_SDECL #define sqlite3Fts5ParserCTX_PDECL #define sqlite3Fts5ParserCTX_PARAM #define sqlite3Fts5ParserCTX_FETCH #define sqlite3Fts5ParserCTX_STORE +#undef fts5YYERRORSYMBOL +#undef fts5YYERRSYMDT +#undef fts5YYFALLBACK #define fts5YYNSTATE 35 #define fts5YYNRULE 28 #define fts5YYNRULE_WITH_ACTION 28 @@ -235001,15 +244980,24 @@ static int fts5yyGrowStack(fts5yyParser *p){ int newSize; int idx; fts5yyStackEntry *pNew; +#ifdef fts5YYSIZELIMIT + int nLimit = fts5YYSIZELIMIT(sqlite3Fts5ParserCTX(p)); +#endif newSize = oldSize*2 + 100; +#ifdef fts5YYSIZELIMIT + if( newSize>nLimit ){ + newSize = nLimit; + if( newSize<=oldSize ) return 1; + } +#endif idx = (int)(p->fts5yytos - p->fts5yystack); if( p->fts5yystack==p->fts5yystk0 ){ - pNew = fts5YYREALLOC(0, newSize*sizeof(pNew[0])); + pNew = fts5YYREALLOC(0, newSize*sizeof(pNew[0]), sqlite3Fts5ParserCTX(p)); if( pNew==0 ) return 1; memcpy(pNew, p->fts5yystack, oldSize*sizeof(pNew[0])); }else{ - pNew = fts5YYREALLOC(p->fts5yystack, newSize*sizeof(pNew[0])); + pNew = fts5YYREALLOC(p->fts5yystack, newSize*sizeof(pNew[0]), sqlite3Fts5ParserCTX(p)); if( pNew==0 ) return 1; } p->fts5yystack = pNew; @@ -235189,7 +245177,9 @@ static void sqlite3Fts5ParserFinalize(void *p){ } #if fts5YYGROWABLESTACK - if( pParser->fts5yystack!=pParser->fts5yystk0 ) fts5YYFREE(pParser->fts5yystack); + if( pParser->fts5yystack!=pParser->fts5yystk0 ){ + fts5YYFREE(pParser->fts5yystack, sqlite3Fts5ParserCTX(pParser)); + } #endif } @@ -236242,6 +246232,16 @@ static int fts5HighlightCb( return rc; } +/* +** Return the integer value of pVal, clamped to the range [-1, 0x7FFFFFFF]. +** This is used for the column-number arguments of auxiliary functions, +** so that 64-bit values that are too large or too small to fit in a +** 32-bit signed integer are not truncated to what might be a valid +** column number. +*/ +static int fts5ValueClampedInt(sqlite3_value *pVal){ + return (int)MIN(MAX(sqlite3_value_int64(pVal), -1), 0x7FFFFFFF); +} /* ** Implementation of highlight() function. @@ -236263,7 +246263,7 @@ static void fts5HighlightFunction( return; } - iCol = sqlite3_value_int(apVal[0]); + iCol = fts5ValueClampedInt(apVal[0]); memset(&ctx, 0, sizeof(HighlightContext)); ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]); ctx.zClose = (const char*)sqlite3_value_text(apVal[2]); @@ -236442,7 +246442,7 @@ static void fts5SnippetFunction( int rc = SQLITE_OK; /* Return code */ int iCol; /* 1st argument to snippet() */ const char *zEllips; /* 4th argument to snippet() */ - int nToken; /* 5th argument to snippet() */ + i64 nToken; /* 5th argument to snippet() */ int nInst = 0; /* Number of instance matches this row */ int i; /* Used to iterate through instances */ int nPhrase; /* Number of phrases in query */ @@ -236462,16 +246462,16 @@ static void fts5SnippetFunction( nCol = pApi->xColumnCount(pFts); memset(&ctx, 0, sizeof(HighlightContext)); - iCol = sqlite3_value_int(apVal[0]); + iCol = fts5ValueClampedInt(apVal[0]); ctx.zOpen = fts5ValueToText(apVal[1]); ctx.zClose = fts5ValueToText(apVal[2]); ctx.iRangeEnd = -1; zEllips = fts5ValueToText(apVal[3]); - nToken = sqlite3_value_int(apVal[4]); + nToken = (int)(MIN( MAX(sqlite3_value_int64(apVal[4]), 0), 64)); iBestCol = (iCol>=0 ? iCol : 0); nPhrase = pApi->xPhraseCount(pFts); - aSeen = sqlite3_malloc(nPhrase); + aSeen = sqlite3_malloc64(nPhrase); if( aSeen==0 ){ rc = SQLITE_NOMEM; } @@ -236683,7 +246683,7 @@ static int fts5Bm25GetData( ** under consideration. ** ** The problem with this is that if (N < 2*nHit), the IDF is - ** negative. Which is undesirable. So the mimimum allowable IDF is + ** negative. Which is undesirable. So the minimum allowable IDF is ** (1e-6) - roughly the same as a term that appears in just over ** half of set of 5,000,000 documents. */ double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) ); @@ -236794,7 +246794,7 @@ static void fts5GetLocaleFunction( return; } - iCol = sqlite3_value_int(apVal[0]); + iCol = fts5ValueClampedInt(apVal[0]); if( iCol<0 || iCol>=pApi->xColumnCount(pFts) ){ sqlite3_result_error_code(pCtx, SQLITE_RANGE); return; @@ -237126,7 +247126,7 @@ static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){ if( nIn<0 ){ nIn = (int)strlen(pIn); } - zRet = (char*)sqlite3_malloc(nIn+1); + zRet = (char*)sqlite3_malloc64((i64)nIn+1); if( zRet ){ memcpy(zRet, pIn, nIn); zRet[nIn] = '\0'; @@ -237146,7 +247146,7 @@ static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){ ** * The 52 upper and lower case ASCII characters, and ** * The 10 integer ASCII characters. ** * The underscore character "_" (0x5F). -** * The unicode "subsitute" character (0x1A). +** * The unicode "substitute" character (0x1A). */ static int sqlite3Fts5IsBareword(char t){ u8 aBareword[128] = { @@ -237826,7 +247826,7 @@ static int sqlite3Fts5ConfigParse( sqlite3_int64 nByte; int bUnindexed = 0; /* True if there are one or more UNINDEXED */ - *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config)); + *ppOut = pRet = (Fts5Config*)sqlite3_malloc64(sizeof(Fts5Config)); if( pRet==0 ) return SQLITE_NOMEM; memset(pRet, 0, sizeof(Fts5Config)); pRet->pGlobal = pGlobal; @@ -238276,6 +248276,19 @@ static int sqlite3Fts5ConfigSetValue( }else{ pConfig->bSecureDelete = (bVal ? 1 : 0); } + } + + else if( 0==sqlite3_stricmp(zKey, "insttoken") ){ + int bVal = -1; + if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){ + bVal = sqlite3_value_int(pVal); + } + if( bVal<0 ){ + *pbBadkey = 1; + }else{ + pConfig->bPrefixInsttoken = (bVal ? 1 : 0); + } + }else{ *pbBadkey = 1; } @@ -238361,8 +248374,6 @@ static void sqlite3Fts5ConfigErrmsg(Fts5Config *pConfig, const char *zFmt, ...){ va_end(ap); } - - /* ** 2014 May 31 ** @@ -238451,9 +248462,13 @@ struct Fts5ExprNode { /* Child nodes. For a NOT node, this array always contains 2 entries. For ** AND or OR nodes, it contains 2 or more entries. */ int nChild; /* Number of child nodes */ - Fts5ExprNode *apChild[1]; /* Array of child nodes */ + Fts5ExprNode *apChild[FLEXARRAY]; /* Array of child nodes */ }; +/* Size (in bytes) of an Fts5ExprNode object that holds up to N children */ +#define SZ_FTS5EXPRNODE(N) \ + (offsetof(Fts5ExprNode,apChild) + (N)*sizeof(Fts5ExprNode*)) + #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING) /* @@ -238484,9 +248499,13 @@ struct Fts5ExprPhrase { Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */ Fts5Buffer poslist; /* Current position list */ int nTerm; /* Number of entries in aTerm[] */ - Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */ + Fts5ExprTerm aTerm[FLEXARRAY]; /* Terms that make up this phrase */ }; +/* Size (in bytes) of an Fts5ExprPhrase object that holds up to N terms */ +#define SZ_FTS5EXPRPHRASE(N) \ + (offsetof(Fts5ExprPhrase,aTerm) + (N)*sizeof(Fts5ExprTerm)) + /* ** One or more phrases that must appear within a certain token distance of ** each other within each matching document. @@ -238495,9 +248514,12 @@ struct Fts5ExprNearset { int nNear; /* NEAR parameter */ Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */ int nPhrase; /* Number of entries in aPhrase[] array */ - Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */ + Fts5ExprPhrase *apPhrase[FLEXARRAY]; /* Array of phrase pointers */ }; +/* Size (in bytes) of an Fts5ExprNearset object covering up to N phrases */ +#define SZ_FTS5EXPRNEARSET(N) \ + (offsetof(Fts5ExprNearset,apPhrase)+(N)*sizeof(Fts5ExprPhrase*)) /* ** Parse context. @@ -238657,7 +248679,7 @@ static int sqlite3Fts5ExprNew( /* If the LHS of the MATCH expression was a user column, apply the ** implicit column-filter. */ if( sParse.rc==SQLITE_OK && iCol<pConfig->nCol ){ - int n = sizeof(Fts5Colset); + int n = SZ_FTS5COLSET(1); Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n); if( pColset ){ pColset->nCol = 1; @@ -238668,7 +248690,7 @@ static int sqlite3Fts5ExprNew( assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 ); if( sParse.rc==SQLITE_OK ){ - *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr)); + *ppNew = pNew = sqlite3_malloc64(sizeof(Fts5Expr)); if( pNew==0 ){ sParse.rc = SQLITE_NOMEM; sqlite3Fts5ParseNodeFree(sParse.pExpr); @@ -238820,7 +248842,7 @@ static int sqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2){ p2->pRoot = 0; if( sParse.rc==SQLITE_OK ){ - Fts5ExprPhrase **ap = (Fts5ExprPhrase**)sqlite3_realloc( + Fts5ExprPhrase **ap = (Fts5ExprPhrase**)sqlite3_realloc64( p1->apExprPhrase, nPhrase * sizeof(Fts5ExprPhrase*) ); if( ap==0 ){ @@ -239161,7 +249183,7 @@ static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){ i64 iPos = a[i].reader.iPos; Fts5PoslistWriter *pWriter = &a[i].writer; if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){ - sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos); + sqlite3Fts5PoslistSafeAppend(a[i].pOut, &pWriter->iPrev, iPos); } } @@ -239903,7 +249925,13 @@ static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){ ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It ** is not considered an error if the query does not match any documents. */ -static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){ +static int sqlite3Fts5ExprFirst( + Fts5Expr *p, + Fts5Index *pIdx, + i64 iFirst, + i64 iLast, + int bDesc +){ Fts5ExprNode *pRoot = p->pRoot; int rc; /* Return code */ @@ -239925,6 +249953,9 @@ static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bD assert( pRoot->bEof==0 ); rc = fts5ExprNodeNext(p, pRoot, 0, 0); } + if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){ + pRoot->bEof = 1; + } return rc; } @@ -240015,7 +250046,7 @@ static Fts5ExprNearset *sqlite3Fts5ParseNearset( if( pParse->rc==SQLITE_OK ){ if( pNear==0 ){ sqlite3_int64 nByte; - nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*); + nByte = SZ_FTS5EXPRNEARSET(SZALLOC+1); pRet = sqlite3_malloc64(nByte); if( pRet==0 ){ pParse->rc = SQLITE_NOMEM; @@ -240026,7 +250057,7 @@ static Fts5ExprNearset *sqlite3Fts5ParseNearset( int nNew = pNear->nPhrase + SZALLOC; sqlite3_int64 nByte; - nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*); + nByte = SZ_FTS5EXPRNEARSET(nNew+1); pRet = (Fts5ExprNearset*)sqlite3_realloc64(pNear, nByte); if( pRet==0 ){ pParse->rc = SQLITE_NOMEM; @@ -240103,10 +250134,10 @@ static int fts5ParseTokenize( memset(pSyn, 0, (size_t)nByte); pSyn->pTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer); pSyn->nFullTerm = pSyn->nQueryTerm = nToken; + memcpy(pSyn->pTerm, pToken, nToken); if( pCtx->pConfig->bTokendata ){ pSyn->nQueryTerm = (int)strlen(pSyn->pTerm); } - memcpy(pSyn->pTerm, pToken, nToken); pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym; pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn; } @@ -240117,12 +250148,12 @@ static int fts5ParseTokenize( int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0); pNew = (Fts5ExprPhrase*)sqlite3_realloc64(pPhrase, - sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew + SZ_FTS5EXPRPHRASE(nNew+1) ); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ - if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase)); + if( pPhrase==0 ) memset(pNew, 0, SZ_FTS5EXPRPHRASE(1)); pCtx->pPhrase = pPhrase = pNew; pNew->nTerm = nNew - SZALLOC; } @@ -240230,7 +250261,7 @@ static Fts5ExprPhrase *sqlite3Fts5ParseTerm( if( sCtx.pPhrase==0 ){ /* This happens when parsing a token or quoted phrase that contains ** no token characters at all. (e.g ... MATCH '""'). */ - sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase)); + sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, SZ_FTS5EXPRPHRASE(1)); }else if( sCtx.pPhrase->nTerm ){ sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix; } @@ -240265,19 +250296,18 @@ static int sqlite3Fts5ExprClonePhrase( sizeof(Fts5ExprPhrase*)); } if( rc==SQLITE_OK ){ - pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc, - sizeof(Fts5ExprNode)); + pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc, SZ_FTS5EXPRNODE(1)); } if( rc==SQLITE_OK ){ pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc, - sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*)); + SZ_FTS5EXPRNEARSET(2)); } if( rc==SQLITE_OK && ALWAYS(pOrig!=0) ){ Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset; if( pColsetOrig ){ sqlite3_int64 nByte; Fts5Colset *pColset; - nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int); + nByte = SZ_FTS5COLSET(pColsetOrig->nCol); pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte); if( pColset ){ memcpy(pColset, pColsetOrig, (size_t)nByte); @@ -240305,7 +250335,7 @@ static int sqlite3Fts5ExprClonePhrase( }else{ /* This happens when parsing a token or quoted phrase that contains ** no token characters at all. (e.g ... MATCH '""'). */ - sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase)); + sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, SZ_FTS5EXPRPHRASE(1)); } } @@ -240370,7 +250400,8 @@ static void sqlite3Fts5ParseSetDistance( ); return; } - nNear = nNear * 10 + (p->p[i] - '0'); + if( nNear<214748363 ) nNear = nNear * 10 + (p->p[i] - '0'); + /* ^^^^^^^^^^^^^^^--- Prevent integer overflow */ } }else{ nNear = FTS5_DEFAULT_NEARDIST; @@ -240399,7 +250430,7 @@ static Fts5Colset *fts5ParseColset( assert( pParse->rc==SQLITE_OK ); assert( iCol>=0 && iCol<pParse->pConfig->nCol ); - pNew = sqlite3_realloc64(p, sizeof(Fts5Colset) + sizeof(int)*nCol); + pNew = sqlite3_realloc64(p, SZ_FTS5COLSET(nCol+1)); if( pNew==0 ){ pParse->rc = SQLITE_NOMEM; }else{ @@ -240434,7 +250465,7 @@ static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p int nCol = pParse->pConfig->nCol; pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc, - sizeof(Fts5Colset) + sizeof(int)*nCol + SZ_FTS5COLSET(nCol+1) ); if( pRet ){ int i; @@ -240495,7 +250526,7 @@ static Fts5Colset *sqlite3Fts5ParseColset( static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){ Fts5Colset *pRet; if( pOrig ){ - sqlite3_int64 nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int); + sqlite3_int64 nByte = SZ_FTS5COLSET(pOrig->nCol); pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte); if( pRet ){ memcpy(pRet, pOrig, (size_t)nByte); @@ -240663,7 +250694,7 @@ static Fts5ExprNode *fts5ParsePhraseToAnd( assert( pNear->nPhrase==1 ); assert( pParse->bPhraseToAnd ); - nByte = sizeof(Fts5ExprNode) + nTerm*sizeof(Fts5ExprNode*); + nByte = SZ_FTS5EXPRNODE(nTerm+1); pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte); if( pRet ){ pRet->eType = FTS5_AND; @@ -240673,7 +250704,7 @@ static Fts5ExprNode *fts5ParsePhraseToAnd( pParse->nPhrase--; for(ii=0; ii<nTerm; ii++){ Fts5ExprPhrase *pPhrase = (Fts5ExprPhrase*)sqlite3Fts5MallocZero( - &pParse->rc, sizeof(Fts5ExprPhrase) + &pParse->rc, SZ_FTS5EXPRPHRASE(1) ); if( pPhrase ){ if( parseGrowPhraseArray(pParse) ){ @@ -240742,7 +250773,7 @@ static Fts5ExprNode *sqlite3Fts5ParseNode( if( pRight->eType==eType ) nChild += pRight->nChild-1; } - nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1); + nByte = SZ_FTS5EXPRNODE(nChild); pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte); if( pRet ){ @@ -241411,7 +251442,7 @@ static int fts5ExprPopulatePoslistsCb( int rc = sqlite3Fts5PoslistWriterAppend( &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff ); - if( rc==SQLITE_OK && pExpr->pConfig->bTokendata && !pT->bPrefix ){ + if( rc==SQLITE_OK && (pExpr->pConfig->bTokendata || pT->bPrefix) ){ int iCol = p->iOff>>32; int iTokOff = p->iOff & 0x7FFFFFFF; rc = sqlite3Fts5IndexIterWriteTokendata( @@ -241604,21 +251635,20 @@ static int sqlite3Fts5ExprInstToken( return SQLITE_RANGE; } pTerm = &pPhrase->aTerm[iToken]; - if( pTerm->bPrefix==0 ){ - if( pExpr->pConfig->bTokendata ){ - rc = sqlite3Fts5IterToken( - pTerm->pIter, iRowid, iCol, iOff+iToken, ppOut, pnOut - ); - }else{ - *ppOut = pTerm->pTerm; - *pnOut = pTerm->nFullTerm; - } + if( pExpr->pConfig->bTokendata || pTerm->bPrefix ){ + rc = sqlite3Fts5IterToken( + pTerm->pIter, pTerm->pTerm, pTerm->nQueryTerm, + iRowid, iCol, iOff+iToken, ppOut, pnOut + ); + }else{ + *ppOut = pTerm->pTerm; + *pnOut = pTerm->nFullTerm; } return rc; } /* -** Clear the token mappings for all Fts5IndexIter objects mannaged by +** Clear the token mappings for all Fts5IndexIter objects managed by ** the expression passed as the only argument. */ static void sqlite3Fts5ExprClearTokens(Fts5Expr *pExpr){ @@ -241653,7 +251683,7 @@ typedef struct Fts5HashEntry Fts5HashEntry; /* ** This file contains the implementation of an in-memory hash table used -** to accumuluate "term -> doclist" content before it is flused to a level-0 +** to accumulate "term -> doclist" content before it is flushed to a level-0 ** segment. */ @@ -241710,7 +251740,7 @@ struct Fts5HashEntry { }; /* -** Eqivalent to: +** Equivalent to: ** ** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; } */ @@ -241724,7 +251754,7 @@ static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte int rc = SQLITE_OK; Fts5Hash *pNew; - *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash)); + *ppNew = pNew = (Fts5Hash*)sqlite3_malloc64(sizeof(Fts5Hash)); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ @@ -241956,7 +251986,7 @@ static int sqlite3Fts5HashWrite( ** + 5 bytes for the new position offset (32-bit max). */ if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){ - sqlite3_int64 nNew = p->nAlloc * 2; + sqlite3_int64 nNew = (i64)p->nAlloc * 2; Fts5HashEntry *pNew; Fts5HashEntry **pp; pNew = (Fts5HashEntry*)sqlite3_realloc64(p, nNew); @@ -242509,7 +252539,12 @@ static void sqlite3Fts5HashScanEntry( #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */ #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */ #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */ -#define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */ +#define FTS5_DATA_PAGE_B 31 /* 31-bit page numbers */ + +/* Maximum page number within a segment. Declare any structure read from +** the database with a page number greater than this corrupt. It is not +** actually possible to create a database this large. */ +#define FTS5_MAX_PGNO 0x7FFFFF00 #define fts5_dri(segid, dlidx, height, pgno) ( \ ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \ @@ -242646,9 +252681,13 @@ struct Fts5Structure { u64 nOriginCntr; /* Origin value for next top-level segment */ int nSegment; /* Total segments in this structure */ int nLevel; /* Number of levels in this index */ - Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */ + Fts5StructureLevel aLevel[FLEXARRAY]; /* Array of nLevel level objects */ }; +/* Size (in bytes) of an Fts5Structure object holding up to N levels */ +#define SZ_FTS5STRUCTURE(N) \ + (offsetof(Fts5Structure,aLevel) + (N)*sizeof(Fts5StructureLevel)) + /* ** An object of type Fts5SegWriter is used to write to segments. */ @@ -242774,15 +252813,49 @@ struct Fts5SegIter { u8 bDel; /* True if the delete flag is set */ }; +static int fts5IndexCorruptRowid(Fts5Index *pIdx, i64 iRowid){ + pIdx->rc = FTS5_CORRUPT; + sqlite3Fts5ConfigErrmsg(pIdx->pConfig, + "fts5: corruption found reading blob %lld from table \"%s\"", + iRowid, pIdx->pConfig->zName + ); + return SQLITE_CORRUPT_VTAB; +} +#define FTS5_CORRUPT_ROWID(pIdx, iRowid) fts5IndexCorruptRowid(pIdx, iRowid) + +static int fts5IndexCorruptIter(Fts5Index *pIdx, Fts5SegIter *pIter){ + pIdx->rc = FTS5_CORRUPT; + sqlite3Fts5ConfigErrmsg(pIdx->pConfig, + "fts5: corruption on page %d, segment %d, table \"%s\"", + pIter->iLeafPgno, pIter->pSeg->iSegid, pIdx->pConfig->zName + ); + return SQLITE_CORRUPT_VTAB; +} +#define FTS5_CORRUPT_ITER(pIdx, pIter) fts5IndexCorruptIter(pIdx, pIter) + +static int fts5IndexCorruptIdx(Fts5Index *pIdx){ + pIdx->rc = FTS5_CORRUPT; + sqlite3Fts5ConfigErrmsg(pIdx->pConfig, + "fts5: corruption in table \"%s\"", pIdx->pConfig->zName + ); + return SQLITE_CORRUPT_VTAB; +} +#define FTS5_CORRUPT_IDX(pIdx) fts5IndexCorruptIdx(pIdx) + + /* ** Array of tombstone pages. Reference counted. */ struct Fts5TombstoneArray { - int nRef; /* Number of pointers to this object */ + int nRef; /* Number of pointers to this object */ int nTombstone; - Fts5Data *apTombstone[1]; /* Array of tombstone pages */ + Fts5Data *apTombstone[FLEXARRAY]; /* Array of tombstone pages */ }; +/* Size (in bytes) of an Fts5TombstoneArray holding up to N tombstones */ +#define SZ_FTS5TOMBSTONEARRAY(N) \ + (offsetof(Fts5TombstoneArray,apTombstone)+(N)*sizeof(Fts5Data*)) + /* ** Argument is a pointer to an Fts5Data structure that contains a ** leaf page. @@ -242851,9 +252924,12 @@ struct Fts5Iter { i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */ Fts5CResult *aFirst; /* Current merge state (see above) */ - Fts5SegIter aSeg[1]; /* Array of segment iterators */ + Fts5SegIter aSeg[FLEXARRAY]; /* Array of segment iterators */ }; +/* Size (in bytes) of an Fts5Iter object holding up to N segment iterators */ +#define SZ_FTS5ITER(N) (offsetof(Fts5Iter,aSeg)+(N)*sizeof(Fts5SegIter)) + /* ** An instance of the following type is used to iterate through the contents ** of a doclist-index record. @@ -242880,9 +252956,13 @@ struct Fts5DlidxLvl { struct Fts5DlidxIter { int nLvl; int iSegid; - Fts5DlidxLvl aLvl[1]; + Fts5DlidxLvl aLvl[FLEXARRAY]; }; +/* Size (in bytes) of an Fts5DlidxIter object with up to N levels */ +#define SZ_FTS5DLIDXITER(N) \ + (offsetof(Fts5DlidxIter,aLvl)+(N)*sizeof(Fts5DlidxLvl)) + static void fts5PutU16(u8 *aOut, u16 iVal){ aOut[0] = (iVal>>8); aOut[1] = (iVal&0xFF); @@ -243002,11 +253082,13 @@ static int fts5LeafFirstTermOff(Fts5Data *pLeaf){ /* ** Close the read-only blob handle, if it is open. */ -static void sqlite3Fts5IndexCloseReader(Fts5Index *p){ +static void fts5IndexCloseReader(Fts5Index *p){ if( p->pReader ){ + int rc; sqlite3_blob *pReader = p->pReader; p->pReader = 0; - sqlite3_blob_close(pReader); + rc = sqlite3_blob_close(pReader); + if( p->rc==SQLITE_OK ) p->rc = rc; } } @@ -243031,7 +253113,7 @@ static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){ assert( p->pReader==0 ); p->pReader = pBlob; if( rc!=SQLITE_OK ){ - sqlite3Fts5IndexCloseReader(p); + fts5IndexCloseReader(p); } if( rc==SQLITE_ABORT ) rc = SQLITE_OK; } @@ -243050,16 +253132,17 @@ static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){ ** All the reasons those functions might return SQLITE_ERROR - missing ** table, missing row, non-blob/text in block column - indicate ** backing store corruption. */ - if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT; + if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT_ROWID(p, iRowid); if( rc==SQLITE_OK ){ u8 *aOut = 0; /* Read blob data into this buffer */ - int nByte = sqlite3_blob_bytes(p->pReader); - int szData = (sizeof(Fts5Data) + 7) & ~7; - sqlite3_int64 nAlloc = szData + nByte + FTS5_DATA_PADDING; + i64 nByte = sqlite3_blob_bytes(p->pReader); + i64 szData = (sizeof(Fts5Data) + 7) & ~7; + i64 nAlloc = szData + nByte + FTS5_DATA_PADDING; pRet = (Fts5Data*)sqlite3_malloc64(nAlloc); if( pRet ){ pRet->nn = nByte; + pRet->szLeaf = 0; aOut = pRet->p = (u8*)pRet + szData; }else{ rc = SQLITE_NOMEM; @@ -243072,10 +253155,8 @@ static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){ sqlite3_free(pRet); pRet = 0; }else{ - /* TODO1: Fix this */ pRet->p[nByte] = 0x00; pRet->p[nByte+1] = 0x00; - pRet->szLeaf = fts5GetU16(&pRet->p[2]); } } p->rc = rc; @@ -243096,11 +253177,19 @@ static void fts5DataRelease(Fts5Data *pData){ sqlite3_free(pData); } +/* +** Read a leaf-page record. This is similar to fts5DataRead(), except that +** it fills in the Fts5Data.szLeaf value before returning. +*/ static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){ Fts5Data *pRet = fts5DataRead(p, iRowid); if( pRet ){ - if( pRet->nn<4 || pRet->szLeaf>pRet->nn ){ - p->rc = FTS5_CORRUPT; + assert( pRet->szLeaf==0 ); + if( pRet->nn>=4 ){ + pRet->szLeaf = fts5GetU16(&pRet->p[2]); + } + if( pRet->szLeaf<4 || pRet->szLeaf>pRet->nn ){ + FTS5_CORRUPT_ROWID(p, iRowid); fts5DataRelease(pRet); pRet = 0; } @@ -243115,9 +253204,13 @@ static int fts5IndexPrepareStmt( ){ if( p->rc==SQLITE_OK ){ if( zSql ){ - p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1, + int rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1, SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB, ppStmt, 0); + /* If this prepare() call fails with SQLITE_ERROR, then one of the + ** %_idx or %_data tables has been removed or modified. Call this + ** corruption. */ + p->rc = (rc==SQLITE_ERROR ? SQLITE_CORRUPT : rc); }else{ p->rc = SQLITE_NOMEM; } @@ -243244,7 +253337,7 @@ static int sqlite3Fts5StructureTest(Fts5Index *p, void *pStruct){ static void fts5StructureMakeWritable(int *pRc, Fts5Structure **pp){ Fts5Structure *p = *pp; if( *pRc==SQLITE_OK && p->nRef>1 ){ - i64 nByte = sizeof(Fts5Structure)+(p->nLevel-1)*sizeof(Fts5StructureLevel); + i64 nByte = SZ_FTS5STRUCTURE(p->nLevel); Fts5Structure *pNew; pNew = (Fts5Structure*)sqlite3Fts5MallocZero(pRc, nByte); if( pNew ){ @@ -243318,10 +253411,7 @@ static int fts5StructureDecode( ){ return FTS5_CORRUPT; } - nByte = ( - sizeof(Fts5Structure) + /* Main structure */ - sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */ - ); + nByte = SZ_FTS5STRUCTURE(nLevel); pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte); if( pRet ){ @@ -243342,7 +253432,7 @@ static int fts5StructureDecode( i += fts5GetVarint32(&pData[i], nTotal); if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT; pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc, - nTotal * sizeof(Fts5StructureSegment) + (i64)nTotal * sizeof(Fts5StructureSegment) ); nSegment -= nTotal; } @@ -243367,7 +253457,7 @@ static int fts5StructureDecode( i += fts5GetVarint(&pData[i], &pSeg->nEntry); nOriginCntr = MAX(nOriginCntr, pSeg->iOrigin2); } - if( pSeg->pgnoLast<pSeg->pgnoFirst ){ + if( pSeg->pgnoLast<pSeg->pgnoFirst || pSeg->pgnoLast>FTS5_MAX_PGNO ){ rc = FTS5_CORRUPT; break; } @@ -243401,10 +253491,7 @@ static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){ if( *pRc==SQLITE_OK ){ Fts5Structure *pStruct = *ppStruct; int nLevel = pStruct->nLevel; - sqlite3_int64 nByte = ( - sizeof(Fts5Structure) + /* Main structure */ - sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */ - ); + sqlite3_int64 nByte = SZ_FTS5STRUCTURE(nLevel+2); pStruct = sqlite3_realloc64(pStruct, nByte); if( pStruct ){ @@ -243461,8 +253548,14 @@ static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){ /* TODO: Do we need this if the leaf-index is appended? Probably... */ memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING); p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet); - if( p->rc==SQLITE_OK && (pConfig->pgsz==0 || pConfig->iCookie!=iCookie) ){ - p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie); + if( p->rc==SQLITE_OK ){ + if( (pConfig->pgsz==0 || pConfig->iCookie!=iCookie) ){ + p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie); + } + }else if( p->rc==SQLITE_CORRUPT_VTAB ){ + sqlite3Fts5ConfigErrmsg(p->pConfig, + "fts5: corrupt structure record for table \"%s\"", p->pConfig->zName + ); } fts5DataRelease(pData); if( p->rc!=SQLITE_OK ){ @@ -243868,6 +253961,7 @@ static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){ pLvl->bEof = 1; }else{ u8 *a = pLvl->pData->p; + int nn = pLvl->pData->nn; pLvl->iOff = 0; fts5DlidxLvlNext(pLvl); @@ -243876,7 +253970,7 @@ static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){ int ii = pLvl->iOff; u64 delta = 0; - while( a[ii]==0 ){ + while( ii<nn && a[ii]==0 ){ nZero++; ii++; } @@ -243943,7 +254037,7 @@ static Fts5DlidxIter *fts5DlidxIterInit( int bDone = 0; for(i=0; p->rc==SQLITE_OK && bDone==0; i++){ - sqlite3_int64 nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl); + sqlite3_int64 nByte = SZ_FTS5DLIDXITER(i+1); Fts5DlidxIter *pNew; pNew = (Fts5DlidxIter*)sqlite3_realloc64(pIter, nByte); @@ -243959,6 +254053,9 @@ static Fts5DlidxIter *fts5DlidxIterInit( bDone = 1; } pIter->nLvl = i+1; + if( pIter->nLvl > (1<<FTS5_DATA_HEIGHT_B) ){ + p->rc = FTS5_CORRUPT; + } } } @@ -244085,7 +254182,7 @@ static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){ while( iOff>=pIter->pLeaf->szLeaf ){ fts5SegIterNextPage(p, pIter); if( pIter->pLeaf==0 ){ - if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT; + if( p->rc==SQLITE_OK ) FTS5_CORRUPT_ITER(p, pIter); return; } iOff = 4; @@ -244117,7 +254214,7 @@ static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){ iOff += fts5GetVarint32(&a[iOff], nNew); if( iOff+nNew>pIter->pLeaf->szLeaf || nKeep>pIter->term.n || nNew==0 ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ITER(p, pIter); return; } pIter->term.n = nKeep; @@ -244159,9 +254256,9 @@ static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){ ** leave an error in the Fts5Index object. */ static void fts5SegIterAllocTombstone(Fts5Index *p, Fts5SegIter *pIter){ - const int nTomb = pIter->pSeg->nPgTombstone; + const i64 nTomb = (i64)pIter->pSeg->nPgTombstone; if( nTomb>0 ){ - int nByte = nTomb * sizeof(Fts5Data*) + sizeof(Fts5TombstoneArray); + i64 nByte = SZ_FTS5TOMBSTONEARRAY(nTomb+1); Fts5TombstoneArray *pNew; pNew = (Fts5TombstoneArray*)sqlite3Fts5MallocZero(&p->rc, nByte); if( pNew ){ @@ -244247,6 +254344,7 @@ static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){ while( 1 ){ u64 iDelta = 0; + if( i>=n ) break; if( eDetail==FTS5_DETAIL_NONE ){ /* todo */ if( i<n && a[i]==0 ){ @@ -244265,7 +254363,7 @@ static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){ /* If necessary, grow the pIter->aRowidOffset[] array. */ if( iRowidOffset>=pIter->nRowidOffset ){ - int nNew = pIter->nRowidOffset + 8; + i64 nNew = pIter->nRowidOffset + 8; int *aNew = (int*)sqlite3_realloc64(pIter->aRowidOffset,nNew*sizeof(int)); if( aNew==0 ){ p->rc = SQLITE_NOMEM; @@ -244294,7 +254392,7 @@ static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){ while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){ Fts5Data *pNew; pIter->iLeafPgno--; - pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID( + pNew = fts5LeafRead(p, FTS5_SEGMENT_ROWID( pIter->pSeg->iSegid, pIter->iLeafPgno )); if( pNew ){ @@ -244312,7 +254410,7 @@ static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){ iRowidOff = fts5LeafFirstRowidOff(pNew); if( iRowidOff ){ if( iRowidOff>=pNew->szLeaf ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ITER(p, pIter); }else{ pIter->pLeaf = pNew; pIter->iLeafOffset = iRowidOff; @@ -244546,7 +254644,7 @@ static void fts5SegIterNext( } assert_nc( iOff<pLeaf->szLeaf ); if( iOff>pLeaf->szLeaf ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ITER(p, pIter); return; } } @@ -244654,18 +254752,20 @@ static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){ fts5DataRelease(pIter->pLeaf); pIter->pLeaf = pLast; pIter->iLeafPgno = pgnoLast; - iOff = fts5LeafFirstRowidOff(pLast); - if( iOff>pLast->szLeaf ){ - p->rc = FTS5_CORRUPT; - return; - } - iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid); - pIter->iLeafOffset = iOff; + if( p->rc==SQLITE_OK ){ + iOff = fts5LeafFirstRowidOff(pLast); + if( iOff>pLast->szLeaf ){ + FTS5_CORRUPT_ITER(p, pIter); + return; + } + iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid); + pIter->iLeafOffset = iOff; - if( fts5LeafIsTermless(pLast) ){ - pIter->iEndofDoclist = pLast->nn+1; - }else{ - pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast); + if( fts5LeafIsTermless(pLast) ){ + pIter->iEndofDoclist = pLast->nn+1; + }else{ + pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast); + } } } @@ -244735,7 +254835,7 @@ static void fts5LeafSeek( iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff); iOff = iTermOff; if( iOff>n ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ITER(p, pIter); return; } @@ -244746,6 +254846,10 @@ static void fts5LeafSeek( if( nKeep<nMatch ){ goto search_failed; } + if( (iOff+nNew)>n ){ + FTS5_CORRUPT_ITER(p, pIter); + return; + } assert( nKeep>=nMatch ); if( nKeep==nMatch ){ @@ -244778,7 +254882,7 @@ static void fts5LeafSeek( iOff = iTermOff; if( iOff>=n ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ITER(p, pIter); return; } @@ -244800,7 +254904,7 @@ static void fts5LeafSeek( iPgidx = (u32)pIter->pLeaf->szLeaf; iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff); if( iOff<4 || (i64)iOff>=pIter->pLeaf->szLeaf ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ITER(p, pIter); return; }else{ nKeep = 0; @@ -244815,7 +254919,7 @@ static void fts5LeafSeek( search_success: if( (i64)iOff+nNew>n || nNew<1 ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ITER(p, pIter); return; } pIter->iLeafOffset = iOff + nNew; @@ -244997,6 +255101,10 @@ static void fts5SegIterNextInit( pIter->iPgidxOff = pIter->pLeaf->szLeaf; pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], iTermOff); + if( iTermOff > pIter->pLeaf->szLeaf ){ + p->rc = FTS5_CORRUPT; + return; + } pIter->iLeafOffset = iTermOff; fts5SegIterLoadTerm(p, pIter, 0); fts5SegIterLoadNPos(p, pIter); @@ -245280,7 +255388,7 @@ static void fts5SegIterGotoPage( assert( iLeafPgno>pIter->iLeafPgno ); if( iLeafPgno>pIter->pSeg->pgnoLast ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_IDX(p); }else{ fts5DataRelease(pIter->pNextLeaf); pIter->pNextLeaf = 0; @@ -245295,7 +255403,7 @@ static void fts5SegIterGotoPage( u8 *a = pIter->pLeaf->p; int n = pIter->pLeaf->szLeaf; if( iOff<4 || iOff>=n ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_IDX(p); }else{ iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid); pIter->iLeafOffset = iOff; @@ -245622,8 +255730,7 @@ static Fts5Iter *fts5MultiIterAlloc( for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2); pNew = fts5IdxMalloc(p, - sizeof(Fts5Iter) + /* pNew */ - sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */ + SZ_FTS5ITER(nSlot) + /* pNew + pNew->aSeg[] */ sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */ ); if( pNew ){ @@ -245723,8 +255830,7 @@ static void fts5PoslistFilterCallback( do { while( i<nChunk && pChunk[i]!=0x01 ){ - while( pChunk[i] & 0x80 ) i++; - i++; + fts5IndexSkipVarint(pChunk, i); } if( pCtx->eState ){ fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart); @@ -245775,7 +255881,7 @@ static void fts5ChunkIterate( if( nRem<=0 ){ break; }else if( pSeg->pSeg==0 ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_IDX(p); return; }else{ pgno++; @@ -245873,7 +255979,7 @@ static void fts5IndexExtractColset( /* Advance pointer p until it points to pEnd or an 0x01 byte that is ** not part of a varint */ while( p<pEnd && *p!=0x01 ){ - while( *p++ & 0x80 ); + while( p<pEnd && (*p++ & 0x80) ); } if( pColset->aiCol[i]==iCurrent ){ @@ -245941,6 +256047,7 @@ static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){ static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){ UNUSED_PARAM(pSeg); pIter->base.nData = 0; + pIter->base.bEof = 1; } /* @@ -245970,8 +256077,11 @@ static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){ assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS ); assert( pIter->pColset ); + assert( pIter->poslist.nSpace>=pIter->pIndex->pConfig->nCol ); - if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){ + if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf + || pSeg->nPos>pIter->pIndex->pConfig->nCol + ){ fts5IterSetOutputs_Col(pIter, pSeg); }else{ u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset]; @@ -246878,7 +256988,7 @@ static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){ ** a single page has been assigned to more than one segment. In ** this case a prior iteration of this loop may have corrupted the ** segment currently being trimmed. */ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ROWID(p, iLeafRowid); }else{ fts5BufferZero(&buf); fts5BufferGrow(&p->rc, &buf, pData->nn); @@ -247229,6 +257339,14 @@ static int fts5IndexReturn(Fts5Index *p){ return rc; } +/* +** Close the read-only blob handle, if it is open. +*/ +static void sqlite3Fts5IndexCloseReader(Fts5Index *p){ + fts5IndexCloseReader(p); + fts5IndexReturn(p); +} + typedef struct Fts5FlushCtx Fts5FlushCtx; struct Fts5FlushCtx { Fts5Index *pIdx; @@ -247314,7 +257432,7 @@ static void fts5SecureDeleteOverflow( int iNext = 0; u8 *aPg = 0; - pLeaf = fts5DataRead(p, iRowid); + pLeaf = fts5LeafRead(p, iRowid); if( pLeaf==0 ) break; aPg = pLeaf->p; @@ -247322,7 +257440,7 @@ static void fts5SecureDeleteOverflow( if( iNext!=0 ){ *pbLastInDoclist = 0; } - if( iNext==0 && pLeaf->szLeaf!=pLeaf->nn ){ + if( iNext==0 && pLeaf->szLeaf<pLeaf->nn ){ fts5GetVarint32(&aPg[pLeaf->szLeaf], iNext); } @@ -247337,7 +257455,7 @@ static void fts5SecureDeleteOverflow( }else if( bDetailNone ){ break; }else if( iNext>=pLeaf->szLeaf || pLeaf->nn<pLeaf->szLeaf || iNext<4 ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ROWID(p, iRowid); break; }else{ int nShift = iNext - 4; @@ -247357,7 +257475,7 @@ static void fts5SecureDeleteOverflow( i1 += fts5GetVarint32(&aPg[i1], iFirst); if( iFirst<iNext ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ROWID(p, iRowid); break; } aIdx = sqlite3Fts5MallocZero(&p->rc, (pLeaf->nn-pLeaf->szLeaf)+2); @@ -247403,7 +257521,7 @@ static void fts5DoSecureDelete( int iSegid = pSeg->pSeg->iSegid; u8 *aPg = pSeg->pLeaf->p; int nPg = pSeg->pLeaf->nn; - int iPgIdx = pSeg->pLeaf->szLeaf; + int iPgIdx = pSeg->pLeaf->szLeaf; /* Offset of page footer */ u64 iDelta = 0; int iNextOff = 0; @@ -247416,7 +257534,7 @@ static void fts5DoSecureDelete( int iDelKeyOff = 0; /* Offset of deleted key, if any */ nIdx = nPg-iPgIdx; - aIdx = sqlite3Fts5MallocZero(&p->rc, nIdx+16); + aIdx = sqlite3Fts5MallocZero(&p->rc, ((i64)nIdx)+16); if( p->rc ) return; memcpy(aIdx, &aPg[iPgIdx], nIdx); @@ -247457,6 +257575,11 @@ static void fts5DoSecureDelete( }else{ iStart = fts5GetU16(&aPg[0]); } + if( iStart>nPg ){ + FTS5_CORRUPT_IDX(p); + sqlite3_free(aIdx); + return; + } iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta); assert_nc( iSOP<=pSeg->iLeafOffset ); @@ -247482,7 +257605,7 @@ static void fts5DoSecureDelete( iSOP += fts5GetVarint32(&aPg[iSOP], nPos); } assert_nc( iSOP==pSeg->iLeafOffset ); - iNextOff = pSeg->iLeafOffset + pSeg->nPos; + iNextOff = iSOP + pSeg->nPos; } } @@ -247562,32 +257685,32 @@ static void fts5DoSecureDelete( ** is another term following it on this page. So the subsequent term ** needs to be moved to replace the term associated with the entry ** being removed. */ - int nPrefix = 0; - int nSuffix = 0; - int nPrefix2 = 0; - int nSuffix2 = 0; + u64 nPrefix = 0; + u64 nSuffix = 0; + u64 nPrefix2 = 0; + u64 nSuffix2 = 0; iDelKeyOff = iNextOff; - iNextOff += fts5GetVarint32(&aPg[iNextOff], nPrefix2); - iNextOff += fts5GetVarint32(&aPg[iNextOff], nSuffix2); + iNextOff += fts5GetVarint(&aPg[iNextOff], &nPrefix2); + iNextOff += fts5GetVarint(&aPg[iNextOff], &nSuffix2); if( iKey!=1 ){ - iKeyOff += fts5GetVarint32(&aPg[iKeyOff], nPrefix); + iKeyOff += fts5GetVarint(&aPg[iKeyOff], &nPrefix); } - iKeyOff += fts5GetVarint32(&aPg[iKeyOff], nSuffix); + iKeyOff += fts5GetVarint(&aPg[iKeyOff], &nSuffix); nPrefix = MIN(nPrefix, nPrefix2); nSuffix = (nPrefix2 + nSuffix2) - nPrefix; - if( (iKeyOff+nSuffix)>iPgIdx || (iNextOff+nSuffix2)>iPgIdx ){ - p->rc = FTS5_CORRUPT; + if( (iKeyOff+nSuffix)>(u64)iPgIdx || (iNextOff+nSuffix2)>(u64)iPgIdx ){ + FTS5_CORRUPT_IDX(p); }else{ if( iKey!=1 ){ iOff += sqlite3Fts5PutVarint(&aPg[iOff], nPrefix); } iOff += sqlite3Fts5PutVarint(&aPg[iOff], nSuffix); - if( nPrefix2>pSeg->term.n ){ - p->rc = FTS5_CORRUPT; + if( nPrefix2>(u64)pSeg->term.n ){ + FTS5_CORRUPT_IDX(p); }else if( nPrefix2>nPrefix ){ memcpy(&aPg[iOff], &pSeg->term.p[nPrefix], nPrefix2-nPrefix); iOff += (nPrefix2-nPrefix); @@ -247604,7 +257727,7 @@ static void fts5DoSecureDelete( /* The entry being removed may be the only position list in ** its doclist. */ for(iPgno=pSeg->iLeafPgno-1; iPgno>pSeg->iTermLeafPgno; iPgno-- ){ - Fts5Data *pPg = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, iPgno)); + Fts5Data *pPg = fts5LeafRead(p, FTS5_SEGMENT_ROWID(iSegid, iPgno)); int bEmpty = (pPg && pPg->nn==4); fts5DataRelease(pPg); if( bEmpty==0 ) break; @@ -247612,12 +257735,12 @@ static void fts5DoSecureDelete( if( iPgno==pSeg->iTermLeafPgno ){ i64 iId = FTS5_SEGMENT_ROWID(iSegid, pSeg->iTermLeafPgno); - Fts5Data *pTerm = fts5DataRead(p, iId); + Fts5Data *pTerm = fts5LeafRead(p, iId); if( pTerm && pTerm->szLeaf==pSeg->iTermLeafOffset ){ u8 *aTermIdx = &pTerm->p[pTerm->szLeaf]; int nTermIdx = pTerm->nn - pTerm->szLeaf; int iTermIdx = 0; - int iTermOff = 0; + i64 iTermOff = 0; while( 1 ){ u32 iVal = 0; @@ -247628,12 +257751,15 @@ static void fts5DoSecureDelete( } nTermIdx = iTermIdx; - memmove(&pTerm->p[iTermOff], &pTerm->p[pTerm->szLeaf], nTermIdx); - fts5PutU16(&pTerm->p[2], iTermOff); - - fts5DataWrite(p, iId, pTerm->p, iTermOff+nTermIdx); - if( nTermIdx==0 ){ - fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iTermLeafPgno); + if( iTermOff>pTerm->szLeaf ){ + FTS5_CORRUPT_IDX(p); + }else{ + memmove(&pTerm->p[iTermOff], &pTerm->p[pTerm->szLeaf], nTermIdx); + fts5PutU16(&pTerm->p[2], iTermOff); + fts5DataWrite(p, iId, pTerm->p, iTermOff+nTermIdx); + if( nTermIdx==0 ){ + fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iTermLeafPgno); + } } } fts5DataRelease(pTerm); @@ -247652,32 +257778,38 @@ static void fts5DoSecureDelete( if( p->rc==SQLITE_OK ){ const int nMove = nPg - iNextOff; /* Number of bytes to move */ int nShift = iNextOff - iOff; /* Distance to move them */ - + int nNewPg = 0; int iPrevKeyOut = 0; - int iKeyIn = 0; + i64 iKeyIn = 0; - memmove(&aPg[iOff], &aPg[iNextOff], nMove); + if( nMove>0 ){ + memmove(&aPg[iOff], &aPg[iNextOff], nMove); + } iPgIdx -= nShift; - nPg = iPgIdx; + nNewPg = iPgIdx; fts5PutU16(&aPg[2], iPgIdx); for(iIdx=0; iIdx<nIdx; /* no-op */){ u32 iVal = 0; iIdx += fts5GetVarint32(&aIdx[iIdx], iVal); iKeyIn += iVal; + if( iKeyIn>nPg ){ + FTS5_CORRUPT_IDX(p); + break; + } if( iKeyIn!=iDelKeyOff ){ int iKeyOut = (iKeyIn - (iKeyIn>iOff ? nShift : 0)); - nPg += sqlite3Fts5PutVarint(&aPg[nPg], iKeyOut - iPrevKeyOut); + nNewPg += sqlite3Fts5PutVarint(&aPg[nNewPg], iKeyOut - iPrevKeyOut); iPrevKeyOut = iKeyOut; } } - if( iPgIdx==nPg && nIdx>0 && pSeg->iLeafPgno!=1 ){ + if( p->rc==SQLITE_OK && iPgIdx==nNewPg && nIdx>0 && pSeg->iLeafPgno!=1 ){ fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iLeafPgno); } - assert_nc( nPg>4 || fts5GetU16(aPg)==0 ); - fts5DataWrite(p, FTS5_SEGMENT_ROWID(iSegid,pSeg->iLeafPgno), aPg, nPg); + assert_nc( nNewPg>4 || fts5GetU16(aPg)==0 ); + fts5DataWrite(p, FTS5_SEGMENT_ROWID(iSegid,pSeg->iLeafPgno), aPg, nNewPg); } sqlite3_free(aIdx); } @@ -247686,8 +257818,11 @@ static void fts5DoSecureDelete( ** This is called as part of flushing a delete to disk in 'secure-delete' ** mode. It edits the segments within the database described by argument ** pStruct to remove the entries for term zTerm, rowid iRowid. +** +** Return SQLITE_OK if successful, or an SQLite error code if an error +** has occurred. Any error code is also stored in the Fts5Index handle. */ -static void fts5FlushSecureDelete( +static int fts5FlushSecureDelete( Fts5Index *p, Fts5Structure *pStruct, const char *zTerm, @@ -247697,6 +257832,24 @@ static void fts5FlushSecureDelete( const int f = FTS5INDEX_QUERY_SKIPHASH; Fts5Iter *pIter = 0; /* Used to find term instance */ + /* If the version number has not been set to SECUREDELETE, do so now. */ + if( p->pConfig->iVersion!=FTS5_CURRENT_VERSION_SECUREDELETE ){ + Fts5Config *pConfig = p->pConfig; + sqlite3_stmt *pStmt = 0; + fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf( + "REPLACE INTO %Q.'%q_config' VALUES ('version', %d)", + pConfig->zDb, pConfig->zName, FTS5_CURRENT_VERSION_SECUREDELETE + )); + if( p->rc==SQLITE_OK ){ + int rc; + sqlite3_step(pStmt); + rc = sqlite3_finalize(pStmt); + if( p->rc==SQLITE_OK ) p->rc = rc; + pConfig->iCookie++; + pConfig->iVersion = FTS5_CURRENT_VERSION_SECUREDELETE; + } + } + fts5MultiIterNew(p, pStruct, f, 0, (const u8*)zTerm, nTerm, -1, 0, &pIter); if( fts5MultiIterEof(p, pIter)==0 ){ i64 iThis = fts5MultiIterRowid(pIter); @@ -247714,6 +257867,7 @@ static void fts5FlushSecureDelete( } fts5MultiIterFree(pIter); + return p->rc; } @@ -247797,18 +257951,19 @@ static void fts5FlushOneHash(Fts5Index *p){ ** using fts5FlushSecureDelete(). */ if( bSecureDelete ){ if( eDetail==FTS5_DETAIL_NONE ){ - if( iOff<nDoclist && pDoclist[iOff]==0x00 ){ - fts5FlushSecureDelete(p, pStruct, zTerm, nTerm, iRowid); + if( iOff<nDoclist && pDoclist[iOff]==0x00 + && !fts5FlushSecureDelete(p, pStruct, zTerm, nTerm, iRowid) + ){ iOff++; if( iOff<nDoclist && pDoclist[iOff]==0x00 ){ iOff++; - nDoclist = 0; }else{ continue; } } - }else if( (pDoclist[iOff] & 0x01) ){ - fts5FlushSecureDelete(p, pStruct, zTerm, nTerm, iRowid); + }else if( (pDoclist[iOff] & 0x01) + && !fts5FlushSecureDelete(p, pStruct, zTerm, nTerm, iRowid) + ){ if( p->rc!=SQLITE_OK || pDoclist[iOff]==0x01 ){ iOff++; continue; @@ -247957,7 +258112,7 @@ static Fts5Structure *fts5IndexOptimizeStruct( Fts5Structure *pStruct ){ Fts5Structure *pNew = 0; - sqlite3_int64 nByte = sizeof(Fts5Structure); + sqlite3_int64 nByte = SZ_FTS5STRUCTURE(1); int nSeg = pStruct->nSegment; int i; @@ -247986,7 +258141,8 @@ static Fts5Structure *fts5IndexOptimizeStruct( assert( pStruct->aLevel[i].nMerge<=nThis ); } - nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel); + nByte += (((i64)pStruct->nLevel)+1) * sizeof(Fts5StructureLevel); + assert( nByte==(i64)SZ_FTS5STRUCTURE(pStruct->nLevel+2) ); pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte); if( pNew ){ @@ -248069,7 +258225,7 @@ static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){ fts5StructureRelease(pStruct); pStruct = pNew; nMin = 1; - nMerge = nMerge*-1; + nMerge = (nMerge==SMALLEST_INT32 ? LARGEST_INT32 : (nMerge*-1)); } if( pStruct && pStruct->nLevel ){ if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){ @@ -248116,9 +258272,9 @@ static void fts5DoclistIterNext(Fts5DoclistIter *pIter){ if( p>=pIter->aEof ){ pIter->aPoslist = 0; }else{ - i64 iDelta; + u64 iDelta; - p += fts5GetVarint(p, (u64*)&iDelta); + p += fts5GetVarint(p, &iDelta); pIter->iRowid += iDelta; /* Read position list size */ @@ -248215,7 +258371,7 @@ static void fts5MergeRowidLists( (void)nBuf; memset(&out, 0, sizeof(out)); assert( nBuf==1 ); - sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n); + sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9); if( p->rc ) return; fts5NextRowid(p1, &i1, &iRowid1); @@ -248223,12 +258379,12 @@ static void fts5MergeRowidLists( while( i1>=0 || i2>=0 ){ if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){ assert( iOut==0 || iRowid1>iOut ); - fts5BufferSafeAppendVarint(&out, iRowid1 - iOut); + fts5BufferSafeAppendVarint(&out, (u64)iRowid1 - (u64)iOut); iOut = iRowid1; fts5NextRowid(p1, &i1, &iRowid1); }else{ assert( iOut==0 || iRowid2>iOut ); - fts5BufferSafeAppendVarint(&out, iRowid2 - iOut); + fts5BufferSafeAppendVarint(&out, (u64)iRowid2 - (u64)iOut); iOut = iRowid2; if( i1>=0 && iRowid1==iRowid2 ){ fts5NextRowid(p1, &i1, &iRowid1); @@ -248355,7 +258511,7 @@ static void fts5MergePrefixLists( } if( pHead==0 || pHead->pNext==0 ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_IDX(p); break; } @@ -248392,7 +258548,7 @@ static void fts5MergePrefixLists( assert_nc( tmp.n+nTail<=nTmp ); assert( tmp.n+nTail<=nTmp+nMerge*10 ); if( tmp.n+nTail>nTmp-FTS5_DATA_ZERO_PADDING ){ - if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT; + if( p->rc==SQLITE_OK ) FTS5_CORRUPT_IDX(p); break; } fts5BufferSafeAppendVarint(&out, (tmp.n+nTail) * 2); @@ -248427,6 +258583,387 @@ static void fts5MergePrefixLists( *p1 = out; } + +/* +** Iterate through a range of entries in the FTS index, invoking the xVisit +** callback for each of them. +** +** Parameter pToken points to an nToken buffer containing an FTS index term +** (i.e. a document term with the preceding 1 byte index identifier - +** FTS5_MAIN_PREFIX or similar). If bPrefix is true, then the call visits +** all entries for terms that have pToken/nToken as a prefix. If bPrefix +** is false, then only entries with pToken/nToken as the entire key are +** visited. +** +** If the current table is a tokendata=1 table, then if bPrefix is true then +** each index term is treated separately. However, if bPrefix is false, then +** all index terms corresponding to pToken/nToken are collapsed into a single +** term before the callback is invoked. +** +** The callback invoked for each entry visited is specified by paramter xVisit. +** Each time it is invoked, it is passed a pointer to the Fts5Index object, +** a copy of the 7th paramter to this function (pCtx) and a pointer to the +** iterator that indicates the current entry. If the current entry is the +** first with a new term (i.e. different from that of the previous entry, +** including the very first term), then the final two parameters are passed +** a pointer to the term and its size in bytes, respectively. If the current +** entry is not the first associated with its term, these two parameters +** are passed 0. +** +** If parameter pColset is not NULL, then it is used to filter entries before +** the callback is invoked. +*/ +static int fts5VisitEntries( + Fts5Index *p, /* Fts5 index object */ + Fts5Colset *pColset, /* Columns filter to apply, or NULL */ + u8 *pToken, /* Buffer containing token */ + int nToken, /* Size of buffer pToken in bytes */ + int bPrefix, /* True for a prefix scan */ + void (*xVisit)(Fts5Index*, void *pCtx, Fts5Iter *pIter, const u8*, int), + void *pCtx /* Passed as second argument to xVisit() */ +){ + const int flags = (bPrefix ? FTS5INDEX_QUERY_SCAN : 0) + | FTS5INDEX_QUERY_SKIPEMPTY + | FTS5INDEX_QUERY_NOOUTPUT; + Fts5Iter *p1 = 0; /* Iterator used to gather data from index */ + int bNewTerm = 1; + Fts5Structure *pStruct = fts5StructureRead(p); + + fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1); + fts5IterSetOutputCb(&p->rc, p1); + for( /* no-op */ ; + fts5MultiIterEof(p, p1)==0; + fts5MultiIterNext2(p, p1, &bNewTerm) + ){ + Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ]; + int nNew = 0; + const u8 *pNew = 0; + + p1->xSetOutputs(p1, pSeg); + if( p->rc ) break; + + if( bNewTerm ){ + nNew = pSeg->term.n; + pNew = pSeg->term.p; + if( nNew<nToken || memcmp(pToken, pNew, nToken) ) break; + } + + xVisit(p, pCtx, p1, pNew, nNew); + } + fts5MultiIterFree(p1); + + fts5StructureRelease(pStruct); + return p->rc; +} + + +/* +** Usually, a tokendata=1 iterator (struct Fts5TokenDataIter) accumulates an +** array of these for each row it visits (so all iRowid fields are the same). +** Or, for an iterator used by an "ORDER BY rank" query, it accumulates an +** array of these for the entire query (in which case iRowid fields may take +** a variety of values). +** +** Each instance in the array indicates the iterator (and therefore term) +** associated with position iPos of rowid iRowid. This is used by the +** xInstToken() API. +** +** iRowid: +** Rowid for the current entry. +** +** iPos: +** Position of current entry within row. In the usual ((iCol<<32)+iOff) +** format (e.g. see macros FTS5_POS2COLUMN() and FTS5_POS2OFFSET()). +** +** iIter: +** If the Fts5TokenDataIter iterator that the entry is part of is +** actually an iterator (i.e. with nIter>0, not just a container for +** Fts5TokenDataMap structures), then this variable is an index into +** the apIter[] array. The corresponding term is that which the iterator +** at apIter[iIter] currently points to. +** +** Or, if the Fts5TokenDataIter iterator is just a container object +** (nIter==0), then iIter is an index into the term.p[] buffer where +** the term is stored. +** +** nByte: +** In the case where iIter is an index into term.p[], this variable +** is the size of the term in bytes. If iIter is an index into apIter[], +** this variable is unused. +*/ +struct Fts5TokenDataMap { + i64 iRowid; /* Row this token is located in */ + i64 iPos; /* Position of token */ + int iIter; /* Iterator token was read from */ + int nByte; /* Length of token in bytes (or 0) */ +}; + +/* +** An object used to supplement Fts5Iter for tokendata=1 iterators. +** +** This object serves two purposes. The first is as a container for an array +** of Fts5TokenDataMap structures, which are used to find the token required +** when the xInstToken() API is used. This is done by the nMapAlloc, nMap and +** aMap[] variables. +*/ +struct Fts5TokenDataIter { + i64 nMapAlloc; /* Allocated size of aMap[] in entries */ + i64 nMap; /* Number of valid entries in aMap[] */ + Fts5TokenDataMap *aMap; /* Array of (rowid+pos -> token) mappings */ + + /* The following are used for prefix-queries only. */ + Fts5Buffer terms; + + /* The following are used for other full-token tokendata queries only. */ + i64 nIter; + i64 nIterAlloc; + Fts5PoslistReader *aPoslistReader; + int *aPoslistToIter; + Fts5Iter *apIter[FLEXARRAY]; +}; + +/* Size in bytes of an Fts5TokenDataIter object holding up to N iterators */ +#define SZ_FTS5TOKENDATAITER(N) \ + (offsetof(Fts5TokenDataIter,apIter) + (N)*sizeof(Fts5Iter)) + +/* +** The two input arrays - a1[] and a2[] - are in sorted order. This function +** merges the two arrays together and writes the result to output array +** aOut[]. aOut[] is guaranteed to be large enough to hold the result. +** +** Duplicate entries are copied into the output. So the size of the output +** array is always (n1+n2) entries. +*/ +static void fts5TokendataMerge( + Fts5TokenDataMap *a1, int n1, /* Input array 1 */ + Fts5TokenDataMap *a2, int n2, /* Input array 2 */ + Fts5TokenDataMap *aOut /* Output array */ +){ + int i1 = 0; + int i2 = 0; + + assert( n1>=0 && n2>=0 ); + while( i1<n1 || i2<n2 ){ + Fts5TokenDataMap *pOut = &aOut[i1+i2]; + if( i2>=n2 || (i1<n1 && ( + a1[i1].iRowid<a2[i2].iRowid + || (a1[i1].iRowid==a2[i2].iRowid && a1[i1].iPos<=a2[i2].iPos) + ))){ + memcpy(pOut, &a1[i1], sizeof(Fts5TokenDataMap)); + i1++; + }else{ + memcpy(pOut, &a2[i2], sizeof(Fts5TokenDataMap)); + i2++; + } + } +} + + +/* +** Append a mapping to the token-map belonging to object pT. +*/ +static void fts5TokendataIterAppendMap( + Fts5Index *p, + Fts5TokenDataIter *pT, + int iIter, + int nByte, + i64 iRowid, + i64 iPos +){ + if( p->rc==SQLITE_OK ){ + if( pT->nMap==pT->nMapAlloc ){ + i64 nNew = pT->nMapAlloc ? pT->nMapAlloc*2 : 64; + i64 nAlloc = nNew * sizeof(Fts5TokenDataMap); + Fts5TokenDataMap *aNew; + + aNew = (Fts5TokenDataMap*)sqlite3_realloc64(pT->aMap, nAlloc); + if( aNew==0 ){ + p->rc = SQLITE_NOMEM; + return; + } + + pT->aMap = aNew; + pT->nMapAlloc = nNew; + } + + pT->aMap[pT->nMap].iRowid = iRowid; + pT->aMap[pT->nMap].iPos = iPos; + pT->aMap[pT->nMap].iIter = iIter; + pT->aMap[pT->nMap].nByte = nByte; + pT->nMap++; + } +} + +/* +** Sort the contents of the pT->aMap[] array. +** +** The sorting algorithm requires a malloc(). If this fails, an error code +** is left in Fts5Index.rc before returning. +*/ +static void fts5TokendataIterSortMap(Fts5Index *p, Fts5TokenDataIter *pT){ + Fts5TokenDataMap *aTmp = 0; + i64 nByte = pT->nMap * sizeof(Fts5TokenDataMap); + + aTmp = (Fts5TokenDataMap*)sqlite3Fts5MallocZero(&p->rc, nByte); + if( aTmp ){ + Fts5TokenDataMap *a1 = pT->aMap; + Fts5TokenDataMap *a2 = aTmp; + i64 nHalf; + + for(nHalf=1; nHalf<pT->nMap; nHalf=nHalf*2){ + int i1; + for(i1=0; i1<pT->nMap; i1+=(nHalf*2)){ + int n1 = MIN(nHalf, pT->nMap-i1); + int n2 = MIN(nHalf, pT->nMap-i1-n1); + fts5TokendataMerge(&a1[i1], n1, &a1[i1+n1], n2, &a2[i1]); + } + SWAPVAL(Fts5TokenDataMap*, a1, a2); + } + + if( a1!=pT->aMap ){ + memcpy(pT->aMap, a1, pT->nMap*sizeof(Fts5TokenDataMap)); + } + sqlite3_free(aTmp); + +#ifdef SQLITE_DEBUG + { + int ii; + for(ii=1; ii<pT->nMap; ii++){ + Fts5TokenDataMap *p1 = &pT->aMap[ii-1]; + Fts5TokenDataMap *p2 = &pT->aMap[ii]; + assert( p1->iRowid<p2->iRowid + || (p1->iRowid==p2->iRowid && p1->iPos<=p2->iPos) + ); + } + } +#endif + } +} + +/* +** Delete an Fts5TokenDataIter structure and its contents. +*/ +static void fts5TokendataIterDelete(Fts5TokenDataIter *pSet){ + if( pSet ){ + int ii; + for(ii=0; ii<pSet->nIter; ii++){ + fts5MultiIterFree(pSet->apIter[ii]); + } + fts5BufferFree(&pSet->terms); + sqlite3_free(pSet->aPoslistReader); + sqlite3_free(pSet->aMap); + sqlite3_free(pSet); + } +} + + +/* +** fts5VisitEntries() context object used by fts5SetupPrefixIterTokendata() +** to pass data to prefixIterSetupTokendataCb(). +*/ +typedef struct TokendataSetupCtx TokendataSetupCtx; +struct TokendataSetupCtx { + Fts5TokenDataIter *pT; /* Object being populated with mappings */ + int iTermOff; /* Offset of current term in terms.p[] */ + int nTermByte; /* Size of current term in bytes */ +}; + +/* +** fts5VisitEntries() callback used by fts5SetupPrefixIterTokendata(). This +** callback adds an entry to the Fts5TokenDataIter.aMap[] array for each +** position in the current position-list. It doesn't matter that some of +** these may be out of order - they will be sorted later. +*/ +static void prefixIterSetupTokendataCb( + Fts5Index *p, + void *pCtx, + Fts5Iter *p1, + const u8 *pNew, + int nNew +){ + TokendataSetupCtx *pSetup = (TokendataSetupCtx*)pCtx; + int iPosOff = 0; + i64 iPos = 0; + + if( pNew ){ + pSetup->nTermByte = nNew-1; + pSetup->iTermOff = pSetup->pT->terms.n; + fts5BufferAppendBlob(&p->rc, &pSetup->pT->terms, nNew-1, pNew+1); + } + + while( 0==sqlite3Fts5PoslistNext64( + p1->base.pData, p1->base.nData, &iPosOff, &iPos + ) ){ + fts5TokendataIterAppendMap(p, + pSetup->pT, pSetup->iTermOff, pSetup->nTermByte, p1->base.iRowid, iPos + ); + } +} + + +/* +** Context object passed by fts5SetupPrefixIter() to fts5VisitEntries(). +*/ +typedef struct PrefixSetupCtx PrefixSetupCtx; +struct PrefixSetupCtx { + void (*xMerge)(Fts5Index*, Fts5Buffer*, int, Fts5Buffer*); + void (*xAppend)(Fts5Index*, u64, Fts5Iter*, Fts5Buffer*); + i64 iLastRowid; + int nMerge; + Fts5Buffer *aBuf; + int nBuf; + Fts5Buffer doclist; + TokendataSetupCtx *pTokendata; +}; + +/* +** fts5VisitEntries() callback used by fts5SetupPrefixIter() +*/ +static void prefixIterSetupCb( + Fts5Index *p, + void *pCtx, + Fts5Iter *p1, + const u8 *pNew, + int nNew +){ + PrefixSetupCtx *pSetup = (PrefixSetupCtx*)pCtx; + const int nMerge = pSetup->nMerge; + + if( p1->base.nData>0 ){ + if( p1->base.iRowid<=pSetup->iLastRowid && pSetup->doclist.n>0 ){ + int i; + for(i=0; p->rc==SQLITE_OK && pSetup->doclist.n; i++){ + int i1 = i*nMerge; + int iStore; + assert( i1+nMerge<=pSetup->nBuf ); + for(iStore=i1; iStore<i1+nMerge; iStore++){ + if( pSetup->aBuf[iStore].n==0 ){ + fts5BufferSwap(&pSetup->doclist, &pSetup->aBuf[iStore]); + fts5BufferZero(&pSetup->doclist); + break; + } + } + if( iStore==i1+nMerge ){ + pSetup->xMerge(p, &pSetup->doclist, nMerge, &pSetup->aBuf[i1]); + for(iStore=i1; iStore<i1+nMerge; iStore++){ + fts5BufferZero(&pSetup->aBuf[iStore]); + } + } + } + pSetup->iLastRowid = 0; + } + + pSetup->xAppend( + p, (u64)p1->base.iRowid-(u64)pSetup->iLastRowid, p1, &pSetup->doclist + ); + pSetup->iLastRowid = p1->base.iRowid; + } + + if( pSetup->pTokendata ){ + prefixIterSetupTokendataCb(p, (void*)pSetup->pTokendata, p1, pNew, nNew); + } +} + static void fts5SetupPrefixIter( Fts5Index *p, /* Index to read from */ int bDesc, /* True for "ORDER BY rowid DESC" */ @@ -248437,38 +258974,41 @@ static void fts5SetupPrefixIter( Fts5Iter **ppIter /* OUT: New iterator */ ){ Fts5Structure *pStruct; - Fts5Buffer *aBuf; - int nBuf = 32; - int nMerge = 1; + PrefixSetupCtx s; + TokendataSetupCtx s2; + + memset(&s, 0, sizeof(s)); + memset(&s2, 0, sizeof(s2)); + + s.nMerge = 1; + s.iLastRowid = 0; + s.nBuf = 32; + if( iIdx==0 + && p->pConfig->eDetail==FTS5_DETAIL_FULL + && p->pConfig->bPrefixInsttoken + ){ + s.pTokendata = &s2; + s2.pT = (Fts5TokenDataIter*)fts5IdxMalloc(p, SZ_FTS5TOKENDATAITER(1)); + } - void (*xMerge)(Fts5Index*, Fts5Buffer*, int, Fts5Buffer*); - void (*xAppend)(Fts5Index*, u64, Fts5Iter*, Fts5Buffer*); if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){ - xMerge = fts5MergeRowidLists; - xAppend = fts5AppendRowid; + s.xMerge = fts5MergeRowidLists; + s.xAppend = fts5AppendRowid; }else{ - nMerge = FTS5_MERGE_NLIST-1; - nBuf = nMerge*8; /* Sufficient to merge (16^8)==(2^32) lists */ - xMerge = fts5MergePrefixLists; - xAppend = fts5AppendPoslist; + s.nMerge = FTS5_MERGE_NLIST-1; + s.nBuf = s.nMerge*8; /* Sufficient to merge (16^8)==(2^32) lists */ + s.xMerge = fts5MergePrefixLists; + s.xAppend = fts5AppendPoslist; } - aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf); + s.aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*s.nBuf); pStruct = fts5StructureRead(p); - assert( p->rc!=SQLITE_OK || (aBuf && pStruct) ); + assert( p->rc!=SQLITE_OK || (s.aBuf && pStruct) ); if( p->rc==SQLITE_OK ){ - const int flags = FTS5INDEX_QUERY_SCAN - | FTS5INDEX_QUERY_SKIPEMPTY - | FTS5INDEX_QUERY_NOOUTPUT; + void *pCtx = (void*)&s; int i; - i64 iLastRowid = 0; - Fts5Iter *p1 = 0; /* Iterator used to gather data from index */ Fts5Data *pData; - Fts5Buffer doclist; - int bNewTerm = 1; - - memset(&doclist, 0, sizeof(doclist)); /* If iIdx is non-zero, then it is the number of a prefix-index for ** prefixes 1 character longer than the prefix being queried for. That @@ -248476,94 +259016,46 @@ static void fts5SetupPrefixIter( ** corresponding to the prefix itself. That one is extracted from the ** main term index here. */ if( iIdx!=0 ){ - int dummy = 0; - const int f2 = FTS5INDEX_QUERY_SKIPEMPTY|FTS5INDEX_QUERY_NOOUTPUT; pToken[0] = FTS5_MAIN_PREFIX; - fts5MultiIterNew(p, pStruct, f2, pColset, pToken, nToken, -1, 0, &p1); - fts5IterSetOutputCb(&p->rc, p1); - for(; - fts5MultiIterEof(p, p1)==0; - fts5MultiIterNext2(p, p1, &dummy) - ){ - Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ]; - p1->xSetOutputs(p1, pSeg); - if( p1->base.nData ){ - xAppend(p, (u64)p1->base.iRowid-(u64)iLastRowid, p1, &doclist); - iLastRowid = p1->base.iRowid; - } - } - fts5MultiIterFree(p1); + fts5VisitEntries(p, pColset, pToken, nToken, 0, prefixIterSetupCb, pCtx); } pToken[0] = FTS5_MAIN_PREFIX + iIdx; - fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1); - fts5IterSetOutputCb(&p->rc, p1); - - for( /* no-op */ ; - fts5MultiIterEof(p, p1)==0; - fts5MultiIterNext2(p, p1, &bNewTerm) - ){ - Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ]; - int nTerm = pSeg->term.n; - const u8 *pTerm = pSeg->term.p; - p1->xSetOutputs(p1, pSeg); - - assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 ); - if( bNewTerm ){ - if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break; - } - - if( p1->base.nData==0 ) continue; - if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){ - for(i=0; p->rc==SQLITE_OK && doclist.n; i++){ - int i1 = i*nMerge; - int iStore; - assert( i1+nMerge<=nBuf ); - for(iStore=i1; iStore<i1+nMerge; iStore++){ - if( aBuf[iStore].n==0 ){ - fts5BufferSwap(&doclist, &aBuf[iStore]); - fts5BufferZero(&doclist); - break; - } - } - if( iStore==i1+nMerge ){ - xMerge(p, &doclist, nMerge, &aBuf[i1]); - for(iStore=i1; iStore<i1+nMerge; iStore++){ - fts5BufferZero(&aBuf[iStore]); - } - } - } - iLastRowid = 0; - } - - xAppend(p, (u64)p1->base.iRowid-(u64)iLastRowid, p1, &doclist); - iLastRowid = p1->base.iRowid; - } + fts5VisitEntries(p, pColset, pToken, nToken, 1, prefixIterSetupCb, pCtx); - assert( (nBuf%nMerge)==0 ); - for(i=0; i<nBuf; i+=nMerge){ + assert( (s.nBuf%s.nMerge)==0 ); + for(i=0; i<s.nBuf; i+=s.nMerge){ int iFree; if( p->rc==SQLITE_OK ){ - xMerge(p, &doclist, nMerge, &aBuf[i]); + s.xMerge(p, &s.doclist, s.nMerge, &s.aBuf[i]); } - for(iFree=i; iFree<i+nMerge; iFree++){ - fts5BufferFree(&aBuf[iFree]); + for(iFree=i; iFree<i+s.nMerge; iFree++){ + fts5BufferFree(&s.aBuf[iFree]); } } - fts5MultiIterFree(p1); - pData = fts5IdxMalloc(p, sizeof(*pData)+doclist.n+FTS5_DATA_ZERO_PADDING); + pData = fts5IdxMalloc(p, sizeof(*pData) + + ((i64)s.doclist.n)+FTS5_DATA_ZERO_PADDING); + assert( pData!=0 || p->rc!=SQLITE_OK ); if( pData ){ pData->p = (u8*)&pData[1]; - pData->nn = pData->szLeaf = doclist.n; - if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n); + pData->nn = pData->szLeaf = s.doclist.n; + if( s.doclist.n ) memcpy(pData->p, s.doclist.p, s.doclist.n); fts5MultiIterNew2(p, pData, bDesc, ppIter); } - fts5BufferFree(&doclist); + + assert( (*ppIter)!=0 || p->rc!=SQLITE_OK ); + if( p->rc==SQLITE_OK && s.pTokendata ){ + fts5TokendataIterSortMap(p, s2.pT); + (*ppIter)->pTokenDataIter = s2.pT; + s2.pT = 0; + } } + fts5TokendataIterDelete(s2.pT); + fts5BufferFree(&s.doclist); fts5StructureRelease(pStruct); - sqlite3_free(aBuf); + sqlite3_free(s.aBuf); } @@ -248601,7 +259093,7 @@ static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){ static int sqlite3Fts5IndexSync(Fts5Index *p){ assert( p->rc==SQLITE_OK ); fts5IndexFlush(p); - sqlite3Fts5IndexCloseReader(p); + fts5IndexCloseReader(p); return fts5IndexReturn(p); } @@ -248612,11 +259104,10 @@ static int sqlite3Fts5IndexSync(Fts5Index *p){ ** records must be invalidated. */ static int sqlite3Fts5IndexRollback(Fts5Index *p){ - sqlite3Fts5IndexCloseReader(p); + fts5IndexCloseReader(p); fts5IndexDiscardData(p); fts5StructureInvalidate(p); - /* assert( p->rc==SQLITE_OK ); */ - return SQLITE_OK; + return fts5IndexReturn(p); } /* @@ -248625,15 +259116,20 @@ static int sqlite3Fts5IndexRollback(Fts5Index *p){ ** and the initial version of the "averages" record (a zero-byte blob). */ static int sqlite3Fts5IndexReinit(Fts5Index *p){ - Fts5Structure s; + Fts5Structure *pTmp; + union { + Fts5Structure sFts; + u8 tmpSpace[SZ_FTS5STRUCTURE(1)]; + } uFts; fts5StructureInvalidate(p); fts5IndexDiscardData(p); - memset(&s, 0, sizeof(Fts5Structure)); + pTmp = &uFts.sFts; + memset(uFts.tmpSpace, 0, sizeof(uFts.tmpSpace)); if( p->pConfig->bContentlessDelete ){ - s.nOriginCntr = 1; + pTmp->nOriginCntr = 1; } fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0); - fts5StructureWrite(p, &s); + fts5StructureWrite(p, pTmp); return fts5IndexReturn(p); } @@ -248817,37 +259313,15 @@ static void fts5SegIterSetEOF(Fts5SegIter *pSeg){ pSeg->pLeaf = 0; } -/* -** Usually, a tokendata=1 iterator (struct Fts5TokenDataIter) accumulates an -** array of these for each row it visits. Or, for an iterator used by an -** "ORDER BY rank" query, it accumulates an array of these for the entire -** query. -** -** Each instance in the array indicates the iterator (and therefore term) -** associated with position iPos of rowid iRowid. This is used by the -** xInstToken() API. -*/ -struct Fts5TokenDataMap { - i64 iRowid; /* Row this token is located in */ - i64 iPos; /* Position of token */ - int iIter; /* Iterator token was read from */ -}; - -/* -** An object used to supplement Fts5Iter for tokendata=1 iterators. -*/ -struct Fts5TokenDataIter { - int nIter; - int nIterAlloc; - - int nMap; - int nMapAlloc; - Fts5TokenDataMap *aMap; - - Fts5PoslistReader *aPoslistReader; - int *aPoslistToIter; - Fts5Iter *apIter[1]; -}; +static void fts5IterClose(Fts5IndexIter *pIndexIter){ + if( pIndexIter ){ + Fts5Iter *pIter = (Fts5Iter*)pIndexIter; + Fts5Index *pIndex = pIter->pIndex; + fts5TokendataIterDelete(pIter->pTokenDataIter); + fts5MultiIterFree(pIter); + fts5IndexCloseReader(pIndex); + } +} /* ** This function appends iterator pAppend to Fts5TokenDataIter pIn and @@ -248862,9 +259336,10 @@ static Fts5TokenDataIter *fts5AppendTokendataIter( if( p->rc==SQLITE_OK ){ if( pIn==0 || pIn->nIter==pIn->nIterAlloc ){ - int nAlloc = pIn ? pIn->nIterAlloc*2 : 16; - int nByte = nAlloc * sizeof(Fts5Iter*) + sizeof(Fts5TokenDataIter); - Fts5TokenDataIter *pNew = (Fts5TokenDataIter*)sqlite3_realloc(pIn, nByte); + i64 nAlloc = pIn ? pIn->nIterAlloc*2 : 16; + i64 nByte = SZ_FTS5TOKENDATAITER(nAlloc+1); + Fts5TokenDataIter *pNew; + pNew = (Fts5TokenDataIter*)sqlite3_realloc64(pIn, nByte); if( pNew==0 ){ p->rc = SQLITE_NOMEM; @@ -248876,7 +259351,7 @@ static Fts5TokenDataIter *fts5AppendTokendataIter( } } if( p->rc ){ - sqlite3Fts5IterClose((Fts5IndexIter*)pAppend); + fts5IterClose((Fts5IndexIter*)pAppend); }else{ pRet->apIter[pRet->nIter++] = pAppend; } @@ -248885,54 +259360,6 @@ static Fts5TokenDataIter *fts5AppendTokendataIter( return pRet; } -/* -** Delete an Fts5TokenDataIter structure and its contents. -*/ -static void fts5TokendataIterDelete(Fts5TokenDataIter *pSet){ - if( pSet ){ - int ii; - for(ii=0; ii<pSet->nIter; ii++){ - fts5MultiIterFree(pSet->apIter[ii]); - } - sqlite3_free(pSet->aPoslistReader); - sqlite3_free(pSet->aMap); - sqlite3_free(pSet); - } -} - -/* -** Append a mapping to the token-map belonging to object pT. -*/ -static void fts5TokendataIterAppendMap( - Fts5Index *p, - Fts5TokenDataIter *pT, - int iIter, - i64 iRowid, - i64 iPos -){ - if( p->rc==SQLITE_OK ){ - if( pT->nMap==pT->nMapAlloc ){ - int nNew = pT->nMapAlloc ? pT->nMapAlloc*2 : 64; - int nByte = nNew * sizeof(Fts5TokenDataMap); - Fts5TokenDataMap *aNew; - - aNew = (Fts5TokenDataMap*)sqlite3_realloc(pT->aMap, nByte); - if( aNew==0 ){ - p->rc = SQLITE_NOMEM; - return; - } - - pT->aMap = aNew; - pT->nMapAlloc = nNew; - } - - pT->aMap[pT->nMap].iRowid = iRowid; - pT->aMap[pT->nMap].iPos = iPos; - pT->aMap[pT->nMap].iIter = iIter; - pT->nMap++; - } -} - /* ** The iterator passed as the only argument must be a tokendata=1 iterator ** (pIter->pTokenDataIter!=0). This function sets the iterator output @@ -248973,7 +259400,7 @@ static void fts5IterSetOutputsTokendata(Fts5Iter *pIter){ pIter->base.iRowid = iRowid; if( nHit==1 && eDetail==FTS5_DETAIL_FULL ){ - fts5TokendataIterAppendMap(pIter->pIndex, pT, iMin, iRowid, -1); + fts5TokendataIterAppendMap(pIter->pIndex, pT, iMin, 0, iRowid, -1); }else if( nHit>1 && eDetail!=FTS5_DETAIL_NONE ){ int nReader = 0; @@ -249009,8 +259436,8 @@ static void fts5IterSetOutputsTokendata(Fts5Iter *pIter){ /* Ensure the token-mapping is large enough */ if( eDetail==FTS5_DETAIL_FULL && pT->nMapAlloc<(pT->nMap + nByte) ){ - int nNew = (pT->nMapAlloc + nByte) * 2; - Fts5TokenDataMap *aNew = (Fts5TokenDataMap*)sqlite3_realloc( + i64 nNew = (pT->nMapAlloc + nByte) * 2; + Fts5TokenDataMap *aNew = (Fts5TokenDataMap*)sqlite3_realloc64( pT->aMap, nNew*sizeof(Fts5TokenDataMap) ); if( aNew==0 ){ @@ -249137,7 +259564,7 @@ static Fts5Iter *fts5SetupTokendataIter( fts5BufferSet(&p->rc, &bSeek, nToken, pToken); } if( p->rc ){ - sqlite3Fts5IterClose((Fts5IndexIter*)pNew); + fts5IterClose((Fts5IndexIter*)pNew); break; } @@ -249202,7 +259629,7 @@ static Fts5Iter *fts5SetupTokendataIter( ** not point to any terms that match the query. So delete it and break ** out of the loop - all required iterators have been collected. */ if( pSmall==0 ){ - sqlite3Fts5IterClose((Fts5IndexIter*)pNew); + fts5IterClose((Fts5IndexIter*)pNew); break; } @@ -249226,6 +259653,7 @@ static Fts5Iter *fts5SetupTokendataIter( pRet = fts5MultiIterAlloc(p, 0); } if( pRet ){ + pRet->nSeg = 0; pRet->pTokenDataIter = pSet; if( pSet ){ fts5IterSetOutputsTokendata(pRet); @@ -249241,7 +259669,6 @@ static Fts5Iter *fts5SetupTokendataIter( return pRet; } - /* ** Open a new iterator to iterate though all rowid that match the ** specified token or token prefix. @@ -249264,8 +259691,14 @@ static int sqlite3Fts5IndexQuery( int iIdx = 0; /* Index to search */ int iPrefixIdx = 0; /* +1 prefix index */ int bTokendata = pConfig->bTokendata; + assert( buf.p!=0 ); if( nToken>0 ) memcpy(&buf.p[1], pToken, nToken); + /* The NOTOKENDATA flag is set when each token in a tokendata=1 table + ** should be treated individually, instead of merging all those with + ** a common prefix into a single entry. This is used, for example, by + ** queries performed as part of an integrity-check, or by the fts5vocab + ** module. */ if( flags & (FTS5INDEX_QUERY_NOTOKENDATA|FTS5INDEX_QUERY_SCAN) ){ bTokendata = 0; } @@ -249296,7 +259729,7 @@ static int sqlite3Fts5IndexQuery( } if( bTokendata && iIdx==0 ){ - buf.p[0] = '0'; + buf.p[0] = FTS5_MAIN_PREFIX; pRet = fts5SetupTokendataIter(p, buf.p, nToken+1, pColset); }else if( iIdx<=pConfig->nPrefix ){ /* Straight index lookup */ @@ -249309,7 +259742,7 @@ static int sqlite3Fts5IndexQuery( fts5StructureRelease(pStruct); } }else{ - /* Scan multiple terms in the main index */ + /* Scan multiple terms in the main index for a prefix query. */ int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0; fts5SetupPrefixIter(p, bDesc, iPrefixIdx, buf.p, nToken+1, pColset,&pRet); if( pRet==0 ){ @@ -249325,9 +259758,9 @@ static int sqlite3Fts5IndexQuery( } if( p->rc ){ - sqlite3Fts5IterClose((Fts5IndexIter*)pRet); + fts5IterClose((Fts5IndexIter*)pRet); pRet = 0; - sqlite3Fts5IndexCloseReader(p); + fts5IndexCloseReader(p); } *ppIter = (Fts5IndexIter*)pRet; @@ -249345,7 +259778,8 @@ static int sqlite3Fts5IndexQuery( static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){ Fts5Iter *pIter = (Fts5Iter*)pIndexIter; assert( pIter->pIndex->rc==SQLITE_OK ); - if( pIter->pTokenDataIter ){ + if( pIter->nSeg==0 ){ + assert( pIter->pTokenDataIter ); fts5TokendataIterNext(pIter, 0, 0); }else{ fts5MultiIterNext(pIter->pIndex, pIter, 0, 0); @@ -249382,7 +259816,8 @@ static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){ */ static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){ Fts5Iter *pIter = (Fts5Iter*)pIndexIter; - if( pIter->pTokenDataIter ){ + if( pIter->nSeg==0 ){ + assert( pIter->pTokenDataIter ); fts5TokendataIterNext(pIter, 1, iMatch); }else{ fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch); @@ -249401,14 +259836,62 @@ static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){ return (z ? &z[1] : 0); } +/* +** pIter is a prefix query. This function populates pIter->pTokenDataIter +** with an Fts5TokenDataIter object containing mappings for all rows +** matched by the query. +*/ +static int fts5SetupPrefixIterTokendata( + Fts5Iter *pIter, + const char *pToken, /* Token prefix to search for */ + int nToken /* Size of pToken in bytes */ +){ + Fts5Index *p = pIter->pIndex; + Fts5Buffer token = {0, 0, 0}; + TokendataSetupCtx ctx; + + memset(&ctx, 0, sizeof(ctx)); + + fts5BufferGrow(&p->rc, &token, nToken+1); + assert( token.p!=0 || p->rc!=SQLITE_OK ); + ctx.pT = (Fts5TokenDataIter*)sqlite3Fts5MallocZero(&p->rc, + SZ_FTS5TOKENDATAITER(1)); + + if( p->rc==SQLITE_OK ){ + + /* Fill in the token prefix to search for */ + token.p[0] = FTS5_MAIN_PREFIX; + memcpy(&token.p[1], pToken, nToken); + token.n = nToken+1; + + fts5VisitEntries( + p, 0, token.p, token.n, 1, prefixIterSetupTokendataCb, (void*)&ctx + ); + + fts5TokendataIterSortMap(p, ctx.pT); + } + + if( p->rc==SQLITE_OK ){ + pIter->pTokenDataIter = ctx.pT; + }else{ + fts5TokendataIterDelete(ctx.pT); + } + fts5BufferFree(&token); + + return fts5IndexReturn(p); +} + /* ** This is used by xInstToken() to access the token at offset iOff, column ** iCol of row iRowid. The token is returned via output variables *ppOut ** and *pnOut. The iterator passed as the first argument must be a tokendata=1 ** iterator (pIter->pTokenDataIter!=0). +** +** pToken/nToken: */ static int sqlite3Fts5IterToken( Fts5IndexIter *pIndexIter, + const char *pToken, int nToken, i64 iRowid, int iCol, int iOff, @@ -249416,13 +259899,22 @@ static int sqlite3Fts5IterToken( ){ Fts5Iter *pIter = (Fts5Iter*)pIndexIter; Fts5TokenDataIter *pT = pIter->pTokenDataIter; - Fts5TokenDataMap *aMap = pT->aMap; i64 iPos = (((i64)iCol)<<32) + iOff; - + Fts5TokenDataMap *aMap = 0; int i1 = 0; - int i2 = pT->nMap; + int i2 = 0; int iTest = 0; + assert( pT || (pToken && pIter->nSeg>0) ); + if( pT==0 ){ + int rc = fts5SetupPrefixIterTokendata(pIter, pToken, nToken); + if( rc!=SQLITE_OK ) return rc; + pT = pIter->pTokenDataIter; + } + + i2 = pT->nMap; + aMap = pT->aMap; + while( i2>i1 ){ iTest = (i1 + i2) / 2; @@ -249445,9 +259937,15 @@ static int sqlite3Fts5IterToken( } if( i2>i1 ){ - Fts5Iter *pMap = pT->apIter[aMap[iTest].iIter]; - *ppOut = (const char*)pMap->aSeg[0].term.p+1; - *pnOut = pMap->aSeg[0].term.n-1; + if( pIter->nSeg==0 ){ + Fts5Iter *pMap = pT->apIter[aMap[iTest].iIter]; + *ppOut = (const char*)pMap->aSeg[0].term.p+1; + *pnOut = pMap->aSeg[0].term.n-1; + }else{ + Fts5TokenDataMap *p = &aMap[iTest]; + *ppOut = (const char*)&pT->terms.p[p->iIter]; + *pnOut = aMap[iTest].nByte; + } } return SQLITE_OK; @@ -249459,7 +259957,9 @@ static int sqlite3Fts5IterToken( */ static void sqlite3Fts5IndexIterClearTokendata(Fts5IndexIter *pIndexIter){ Fts5Iter *pIter = (Fts5Iter*)pIndexIter; - if( pIter && pIter->pTokenDataIter ){ + if( pIter && pIter->pTokenDataIter + && (pIter->nSeg==0 || pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_FULL) + ){ pIter->pTokenDataIter->nMap = 0; } } @@ -249479,17 +259979,30 @@ static int sqlite3Fts5IndexIterWriteTokendata( Fts5Iter *pIter = (Fts5Iter*)pIndexIter; Fts5TokenDataIter *pT = pIter->pTokenDataIter; Fts5Index *p = pIter->pIndex; - int ii; + i64 iPos = (((i64)iCol)<<32) + iOff; assert( p->pConfig->eDetail!=FTS5_DETAIL_FULL ); - assert( pIter->pTokenDataIter ); - - for(ii=0; ii<pT->nIter; ii++){ - Fts5Buffer *pTerm = &pT->apIter[ii]->aSeg[0].term; - if( nToken==pTerm->n-1 && memcmp(pToken, pTerm->p+1, nToken)==0 ) break; - } - if( ii<pT->nIter ){ - fts5TokendataIterAppendMap(p, pT, ii, iRowid, (((i64)iCol)<<32) + iOff); + assert( pIter->pTokenDataIter || pIter->nSeg>0 ); + if( pIter->nSeg>0 ){ + /* This is a prefix term iterator. */ + if( pT==0 ){ + pT = (Fts5TokenDataIter*)sqlite3Fts5MallocZero(&p->rc, + SZ_FTS5TOKENDATAITER(1)); + pIter->pTokenDataIter = pT; + } + if( pT ){ + fts5TokendataIterAppendMap(p, pT, pT->terms.n, nToken, iRowid, iPos); + fts5BufferAppendBlob(&p->rc, &pT->terms, nToken, (const u8*)pToken); + } + }else{ + int ii; + for(ii=0; ii<pT->nIter; ii++){ + Fts5Buffer *pTerm = &pT->apIter[ii]->aSeg[0].term; + if( nToken==pTerm->n-1 && memcmp(pToken, pTerm->p+1, nToken)==0 ) break; + } + if( ii<pT->nIter ){ + fts5TokendataIterAppendMap(p, pT, ii, 0, iRowid, iPos); + } } return fts5IndexReturn(p); } @@ -249499,11 +260012,9 @@ static int sqlite3Fts5IndexIterWriteTokendata( */ static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){ if( pIndexIter ){ - Fts5Iter *pIter = (Fts5Iter*)pIndexIter; - Fts5Index *pIndex = pIter->pIndex; - fts5TokendataIterDelete(pIter->pTokenDataIter); - fts5MultiIterFree(pIter); - sqlite3Fts5IndexCloseReader(pIndex); + Fts5Index *pIndex = ((Fts5Iter*)pIndexIter)->pIndex; + fts5IterClose(pIndexIter); + fts5IndexReturn(pIndex); } } @@ -249757,8 +260268,8 @@ static void fts5IndexTombstoneRebuild( ){ const int MINSLOT = 32; int nSlotPerPage = MAX(MINSLOT, (p->pConfig->pgsz - 8) / szKey); - int nSlot = 0; /* Number of slots in each output page */ - int nOut = 0; + i64 nSlot = 0; /* Number of slots in each output page */ + i64 nOut = 0; /* Figure out how many output pages (nOut) and how many slots per ** page (nSlot). There are three possibilities: @@ -249783,23 +260294,26 @@ static void fts5IndexTombstoneRebuild( nSlot = MINSLOT; }else if( pSeg->nPgTombstone==1 ){ /* Case 2. */ - int nElem = (int)fts5GetU32(&pData1->p[4]); + u32 nElem = fts5GetU32(&pData1->p[4]); assert( pData1 && iPg1==0 ); - nOut = 1; - nSlot = MAX(nElem*4, MINSLOT); - if( nSlot>nSlotPerPage ) nOut = 0; + if( nElem>((u32)nSlotPerPage/4) ){ + nOut = 0; + }else{ + nOut = 1; + nSlot = MAX((i64)nElem*4, MINSLOT); + } } if( nOut==0 ){ /* Case 3. */ - nOut = (pSeg->nPgTombstone * 2 + 1); + nOut = ((i64)pSeg->nPgTombstone * 2 + 1); nSlot = nSlotPerPage; } /* Allocate the required array and output pages */ while( 1 ){ int res = 0; - int ii = 0; - int szPage = 0; + i64 ii = 0; + i64 szPage = 0; Fts5Data **apOut = 0; /* Allocate space for the new hash table */ @@ -250033,13 +260547,16 @@ static int fts5QueryCksum( rc = sqlite3Fts5IterNext(pIter); } } - sqlite3Fts5IterClose(pIter); + fts5IterClose(pIter); *pCksum = cksum; return rc; } /* +** This function is purely an internal test. It does not contribute to +** FTS functionality, or even the integrity-check, in any way. +** ** Check if buffer z[], size n bytes, contains as series of valid utf-8 ** encoded codepoints. If so, return 0. Otherwise, if the buffer does not ** contain valid utf-8, return non-zero. @@ -250061,8 +260578,8 @@ static int fts5TestUtf8(const char *z, int n){ }else if( (z[i] & 0xF8)==0xF0 ){ if( i+3>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1; - if( (z[i+2] & 0xC0)!=0x80 ) return 1; - i += 3; + if( (z[i+3] & 0xC0)!=0x80 ) return 1; + i += 4; }else{ return 1; } @@ -250074,19 +260591,27 @@ static int fts5TestUtf8(const char *z, int n){ /* ** This function is also purely an internal test. It does not contribute to ** FTS functionality, or even the integrity-check, in any way. +** +** This function sets output variable (*pbFail) to true if the test fails. Or +** leaves it unchanged if the test succeeds. */ static void fts5TestTerm( Fts5Index *p, Fts5Buffer *pPrev, /* Previous term */ const char *z, int n, /* Possibly new term to test */ u64 expected, - u64 *pCksum + u64 *pCksum, + int *pbFail ){ int rc = p->rc; if( pPrev->n==0 ){ fts5BufferSet(&rc, pPrev, n, (const u8*)z); }else - if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){ + if( *pbFail==0 + && rc==SQLITE_OK + && (pPrev->n!=n || memcmp(pPrev->p, z, n)) + && (p->pHash==0 || p->pHash->nEntry==0) + ){ u64 cksum3 = *pCksum; const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */ int nTerm = pPrev->n-1; /* Size of zTerm in bytes */ @@ -250136,7 +260661,7 @@ static void fts5TestTerm( fts5BufferSet(&rc, pPrev, n, (const u8*)z); if( rc==SQLITE_OK && cksum3!=expected ){ - rc = FTS5_CORRUPT; + *pbFail = 1; } *pCksum = cksum3; } @@ -250145,7 +260670,7 @@ static void fts5TestTerm( #else # define fts5TestDlidxReverse(x,y,z) -# define fts5TestTerm(u,v,w,x,y,z) +# define fts5TestTerm(t,u,v,w,x,y,z) #endif /* @@ -250168,16 +260693,19 @@ static void fts5IndexIntegrityCheckEmpty( /* Now check that the iter.nEmpty leaves following the current leaf ** (a) exist and (b) contain no terms. */ for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){ - Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i)); + Fts5Data *pLeaf = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i)); if( pLeaf ){ - if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT; - if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT; + if( !fts5LeafIsTermless(pLeaf) + || (i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf)) + ){ + FTS5_CORRUPT_ROWID(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i)); + } } fts5DataRelease(pLeaf); } } -static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){ +static void fts5IntegrityCheckPgidx(Fts5Index *p, i64 iRowid, Fts5Data *pLeaf){ i64 iTermOff = 0; int ii; @@ -250195,12 +260723,12 @@ static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){ iOff = iTermOff; if( iOff>=pLeaf->szLeaf ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ROWID(p, iRowid); }else if( iTermOff==nIncr ){ int nByte; iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte); if( (iOff+nByte)>pLeaf->szLeaf ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ROWID(p, iRowid); }else{ fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]); } @@ -250209,7 +260737,7 @@ static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){ iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep); iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte); if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ROWID(p, iRowid); }else{ buf1.n = nKeep; fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]); @@ -250217,7 +260745,7 @@ static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){ if( p->rc==SQLITE_OK ){ res = fts5BufferCompare(&buf1, &buf2); - if( res<=0 ) p->rc = FTS5_CORRUPT; + if( res<=0 ) FTS5_CORRUPT_ROWID(p, iRowid); } } fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p); @@ -250278,7 +260806,7 @@ static void fts5IndexIntegrityCheckSegment( ** entry even if all the terms are removed from it by secure-delete ** operations. */ }else{ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ROWID(p, iRow); } }else{ @@ -250290,15 +260818,19 @@ static void fts5IndexIntegrityCheckSegment( iOff = fts5LeafFirstTermOff(pLeaf); iRowidOff = fts5LeafFirstRowidOff(pLeaf); if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ROWID(p, iRow); }else{ iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm); - res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm)); - if( res==0 ) res = nTerm - nIdxTerm; - if( res<0 ) p->rc = FTS5_CORRUPT; + if( (i64)iOff+(i64)nTerm>(i64)pLeaf->szLeaf ){ + FTS5_CORRUPT_ROWID(p, iRow); + }else{ + res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm)); + if( res==0 ) res = nTerm - nIdxTerm; + if( res<0 ) FTS5_CORRUPT_ROWID(p, iRow); + } } - fts5IntegrityCheckPgidx(p, pLeaf); + fts5IntegrityCheckPgidx(p, iRow, pLeaf); } fts5DataRelease(pLeaf); if( p->rc ) break; @@ -250326,9 +260858,9 @@ static void fts5IndexIntegrityCheckSegment( /* Check any rowid-less pages that occur before the current leaf. */ for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){ iKey = FTS5_SEGMENT_ROWID(iSegid, iPg); - pLeaf = fts5DataRead(p, iKey); + pLeaf = fts5LeafRead(p, iKey); if( pLeaf ){ - if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT; + if( fts5LeafFirstRowidOff(pLeaf)!=0 ) FTS5_CORRUPT_ROWID(p, iKey); fts5DataRelease(pLeaf); } } @@ -250337,18 +260869,18 @@ static void fts5IndexIntegrityCheckSegment( /* Check that the leaf page indicated by the iterator really does ** contain the rowid suggested by the same. */ iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf); - pLeaf = fts5DataRead(p, iKey); + pLeaf = fts5LeafRead(p, iKey); if( pLeaf ){ i64 iRowid; int iRowidOff = fts5LeafFirstRowidOff(pLeaf); ASSERT_SZLEAF_OK(pLeaf); if( iRowidOff>=pLeaf->szLeaf ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ROWID(p, iKey); }else if( bSecureDelete==0 || iRowidOff>0 ){ i64 iDlRowid = fts5DlidxIterRowid(pDlidx); fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid); if( iRowid<iDlRowid || (bSecureDelete==0 && iRowid!=iDlRowid) ){ - p->rc = FTS5_CORRUPT; + FTS5_CORRUPT_ROWID(p, iKey); } } fts5DataRelease(pLeaf); @@ -250400,6 +260932,7 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum /* Used by extra internal tests only run if NDEBUG is not defined */ u64 cksum3 = 0; /* Checksum based on contents of indexes */ Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */ + int bTestFail = 0; #endif const int flags = FTS5INDEX_QUERY_NOOUTPUT; @@ -250442,7 +260975,7 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum char *z = (char*)fts5MultiIterTerm(pIter, &n); /* If this is a new term, query for it. Update cksum3 with the results. */ - fts5TestTerm(p, &term, z, n, cksum2, &cksum3); + fts5TestTerm(p, &term, z, n, cksum2, &cksum3, &bTestFail); if( p->rc ) break; if( eDetail==FTS5_DETAIL_NONE ){ @@ -250460,15 +260993,26 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum } } } - fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3); + fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3, &bTestFail); fts5MultiIterFree(pIter); - if( p->rc==SQLITE_OK && bUseCksum && cksum!=cksum2 ) p->rc = FTS5_CORRUPT; - - fts5StructureRelease(pStruct); + if( p->rc==SQLITE_OK && bUseCksum && cksum!=cksum2 ){ + p->rc = FTS5_CORRUPT; + sqlite3Fts5ConfigErrmsg(p->pConfig, + "fts5: checksum mismatch for table \"%s\"", p->pConfig->zName + ); + } #ifdef SQLITE_DEBUG + /* In SQLITE_DEBUG builds, expensive extra checks were run as part of + ** the integrity-check above. If no other errors were detected, but one + ** of these tests failed, set the result to SQLITE_CORRUPT_VTAB here. */ + if( p->rc==SQLITE_OK && bTestFail ){ + p->rc = FTS5_CORRUPT; + } fts5BufferFree(&term); #endif + + fts5StructureRelease(pStruct); fts5BufferFree(&poslist); return fts5IndexReturn(p); } @@ -250510,7 +261054,7 @@ static void fts5DecodeRowid( #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG) static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){ - int iSegid, iHeight, iPgno, bDlidx, bTomb; /* Rowid compenents */ + int iSegid, iHeight, iPgno, bDlidx, bTomb; /* Rowid components */ fts5DecodeRowid(iKey, &bTomb, &iSegid, &bDlidx, &iHeight, &iPgno); if( iSegid==0 ){ @@ -250756,7 +261300,7 @@ static void fts5DecodeFunction( ** buffer overreads even if the record is corrupt. */ n = sqlite3_value_bytes(apVal[1]); aBlob = sqlite3_value_blob(apVal[1]); - nSpace = n + FTS5_DATA_ZERO_PADDING; + nSpace = ((i64)n) + FTS5_DATA_ZERO_PADDING; a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace); if( a==0 ) goto decode_out; if( n>0 ) memcpy(a, aBlob, n); @@ -251394,6 +261938,7 @@ struct Fts5Global { #define FTS5_LOCALE_HDR_SIZE ((int)sizeof( ((Fts5Global*)0)->aLocaleHdr )) #define FTS5_LOCALE_HDR(pConfig) ((const u8*)(pConfig->pGlobal->aLocaleHdr)) +#define FTS5_INSTTOKEN_SUBTYPE 73 /* ** Each auxiliary function registered with the FTS5 module is represented @@ -251470,9 +262015,11 @@ struct Fts5Sorter { i64 iRowid; /* Current rowid */ const u8 *aPoslist; /* Position lists for current row */ int nIdx; /* Number of entries in aIdx[] */ - int aIdx[1]; /* Offsets into aPoslist for current row */ + int aIdx[FLEXARRAY]; /* Offsets into aPoslist for current row */ }; +/* Size (int bytes) of an Fts5Sorter object with N indexes */ +#define SZ_FTS5SORTER(N) (offsetof(Fts5Sorter,nIdx)+((N+2)/2)*sizeof(i64)) /* ** Virtual-table cursor object. @@ -251809,6 +262356,17 @@ static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){ #endif } +static void fts5SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){ +#if SQLITE_VERSION_NUMBER>=3008002 +#ifndef SQLITE_CORE + if( sqlite3_libversion_number()>=3008002 ) +#endif + { + pIdxInfo->estimatedRows = MAX(1, nRow); + } +#endif +} + static int fts5UsePatternMatch( Fts5Config *pConfig, struct sqlite3_index_constraint *p @@ -251873,19 +262431,30 @@ static int fts5UsePatternMatch( ** a) If a MATCH operator is present, the cost depends on the other ** constraints also present. As follows: ** -** * No other constraints: cost=1000.0 -** * One rowid range constraint: cost=750.0 -** * Both rowid range constraints: cost=500.0 -** * An == rowid constraint: cost=100.0 +** * No other constraints: cost=50000.0 +** * One rowid range constraint: cost=37500.0 +** * Both rowid range constraints: cost=30000.0 +** * An == rowid constraint: cost=25000.0 ** ** b) Otherwise, if there is no MATCH: ** -** * No other constraints: cost=1000000.0 -** * One rowid range constraint: cost=750000.0 -** * Both rowid range constraints: cost=250000.0 -** * An == rowid constraint: cost=10.0 +** * No other constraints: cost=3000000.0 +** * One rowid range constraints: cost=2250000.0 +** * Both rowid range constraint: cost=750000.0 +** * An == rowid constraint: cost=25.0 ** ** Costs are not modified by the ORDER BY clause. +** +** The ratios used in case (a) are based on informal results obtained from +** the tool/fts5cost.tcl script. The "MATCH and ==" combination has the +** cost set quite high because the query may be a prefix query. Unless +** there is a prefix index, prefix queries with rowid constraints are much +** more expensive than non-prefix queries with rowid constraints. +** +** The estimated rows returned is set to the cost/40. For simple queries, +** experimental results show that cost/4 might be about right. But for +** more complex queries that use multiple terms the number of rows might +** be far fewer than this. So we compromise and use cost/40. */ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ Fts5Table *pTab = (Fts5Table*)pVTab; @@ -251918,7 +262487,7 @@ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ return SQLITE_ERROR; } - idxStr = (char*)sqlite3_malloc(pInfo->nConstraint * 8 + 1); + idxStr = (char*)sqlite3_malloc64((i64)pInfo->nConstraint * 8 + 1); if( idxStr==0 ) return SQLITE_NOMEM; pInfo->idxStr = idxStr; pInfo->needToFreeIdxStr = 1; @@ -251933,6 +262502,7 @@ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ if( p->usable==0 || iCol<0 ){ /* As there exists an unusable MATCH constraint this is an ** unusable plan. Return SQLITE_CONSTRAINT. */ + idxStr[iIdxStr] = 0; return SQLITE_CONSTRAINT; }else{ if( iCol==nCol+1 ){ @@ -251943,7 +262513,7 @@ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ nSeenMatch++; idxStr[iIdxStr++] = 'M'; sqlite3_snprintf(6, &idxStr[iIdxStr], "%d", iCol); - idxStr += strlen(&idxStr[iIdxStr]); + iIdxStr += (int)strlen(&idxStr[iIdxStr]); assert( idxStr[iIdxStr]=='\0' ); } pInfo->aConstraintUsage[i].argvIndex = ++iCons; @@ -251962,6 +262532,7 @@ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ idxStr[iIdxStr++] = '='; bSeenEq = 1; pInfo->aConstraintUsage[i].argvIndex = ++iCons; + pInfo->aConstraintUsage[i].omit = 1; } } } @@ -252009,17 +262580,35 @@ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ /* Calculate the estimated cost based on the flags set in idxFlags. */ if( bSeenEq ){ - pInfo->estimatedCost = nSeenMatch ? 1000.0 : 10.0; - if( nSeenMatch==0 ) fts5SetUniqueFlag(pInfo); - }else if( bSeenLt && bSeenGt ){ - pInfo->estimatedCost = nSeenMatch ? 5000.0 : 250000.0; - }else if( bSeenLt || bSeenGt ){ - pInfo->estimatedCost = nSeenMatch ? 7500.0 : 750000.0; - }else{ - pInfo->estimatedCost = nSeenMatch ? 10000.0 : 1000000.0; - } - for(i=1; i<nSeenMatch; i++){ - pInfo->estimatedCost *= 0.4; + pInfo->estimatedCost = nSeenMatch ? 25000.0 : 25.0; + fts5SetEstimatedRows(pInfo, 1); + fts5SetUniqueFlag(pInfo); + }else{ + i64 nEstRows; + if( nSeenMatch ){ + if( bSeenLt && bSeenGt ){ + pInfo->estimatedCost = 50000.0; + }else if( bSeenLt || bSeenGt ){ + pInfo->estimatedCost = 37500.0; + }else{ + pInfo->estimatedCost = 50000.0; + } + nEstRows = (i64)(pInfo->estimatedCost / 40.0); + for(i=1; i<nSeenMatch; i++){ + pInfo->estimatedCost *= 2.5; + nEstRows = nEstRows / 2; + } + }else{ + if( bSeenLt && bSeenGt ){ + pInfo->estimatedCost = 750000.0; + }else if( bSeenLt || bSeenGt ){ + pInfo->estimatedCost = 2250000.0; + }else{ + pInfo->estimatedCost = 3000000.0; + } + nEstRows = (i64)(pInfo->estimatedCost / 4.0); + } + fts5SetEstimatedRows(pInfo, nEstRows); } pInfo->idxNum = idxFlags; @@ -252218,7 +262807,9 @@ static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){ int bDesc = pCsr->bDesc; i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr); - rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->p.pIndex, iRowid, bDesc); + rc = sqlite3Fts5ExprFirst( + pCsr->pExpr, pTab->p.pIndex, iRowid, pCsr->iLastRowid, bDesc + ); if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){ *pbSkip = 1; } @@ -252349,7 +262940,7 @@ static int fts5CursorFirstSorted( const char *zRankArgs = pCsr->zRankArgs; nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr); - nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1); + nByte = SZ_FTS5SORTER(nPhrase); pSorter = (Fts5Sorter*)sqlite3_malloc64(nByte); if( pSorter==0 ) return SQLITE_NOMEM; memset(pSorter, 0, (size_t)nByte); @@ -252390,7 +262981,9 @@ static int fts5CursorFirstSorted( static int fts5CursorFirst(Fts5FullTable *pTab, Fts5Cursor *pCsr, int bDesc){ int rc; Fts5Expr *pExpr = pCsr->pExpr; - rc = sqlite3Fts5ExprFirst(pExpr, pTab->p.pIndex, pCsr->iFirstRowid, bDesc); + rc = sqlite3Fts5ExprFirst( + pExpr, pTab->p.pIndex, pCsr->iFirstRowid, pCsr->iLastRowid, bDesc + ); if( sqlite3Fts5ExprEof(pExpr) ){ CsrFlagSet(pCsr, FTS5CSR_EOF); } @@ -252718,6 +263311,7 @@ static int fts5FilterMethod( sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */ int iCol; /* Column on LHS of MATCH operator */ char **pzErrmsg = pConfig->pzErrmsg; + int bPrefixInsttoken = pConfig->bPrefixInsttoken; int i; int iIdxStr = 0; Fts5Expr *pExpr = 0; @@ -252753,6 +263347,9 @@ static int fts5FilterMethod( rc = fts5ExtractExprText(pConfig, apVal[i], &zText, &bFreeAndReset); if( rc!=SQLITE_OK ) goto filter_out; if( zText==0 ) zText = ""; + if( sqlite3_value_subtype(apVal[i])==FTS5_INSTTOKEN_SUBTYPE ){ + pConfig->bPrefixInsttoken = 1; + } iCol = 0; do{ @@ -252893,6 +263490,7 @@ static int fts5FilterMethod( filter_out: sqlite3Fts5ExprFree(pExpr); pConfig->pzErrmsg = pzErrmsg; + pConfig->bPrefixInsttoken = bPrefixInsttoken; return rc; } @@ -253195,7 +263793,6 @@ static int fts5UpdateMethod( Fts5Config *pConfig = pTab->p.pConfig; int eType0; /* value_type() of apVal[0] */ int rc = SQLITE_OK; /* Return code */ - int bUpdateOrDelete = 0; /* A transaction must be open when this is called. */ assert( pTab->ts.eState==1 || pTab->ts.eState==2 ); @@ -253207,7 +263804,7 @@ static int fts5UpdateMethod( ); assert( pTab->p.pConfig->pzErrmsg==0 ); if( pConfig->pgsz==0 ){ - rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex); + rc = sqlite3Fts5ConfigLoad(pTab->p.pConfig, pTab->p.pConfig->iCookie); if( rc!=SQLITE_OK ) return rc; } @@ -253232,7 +263829,6 @@ static int fts5UpdateMethod( rc = SQLITE_ERROR; }else{ rc = fts5SpecialDelete(pTab, apVal); - bUpdateOrDelete = 1; } }else{ rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]); @@ -253269,7 +263865,6 @@ static int fts5UpdateMethod( }else{ i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0, 0); - bUpdateOrDelete = 1; } } @@ -253297,7 +263892,6 @@ static int fts5UpdateMethod( if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){ i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */ rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0, 0); - bUpdateOrDelete = 1; } fts5StorageInsert(&rc, pTab, apVal, pRowid); } @@ -253351,27 +263945,13 @@ static int fts5UpdateMethod( rc = sqlite3Fts5StorageDelete(pStorage, iOld, 0, 1); fts5StorageInsert(&rc, pTab, apVal, pRowid); } - bUpdateOrDelete = 1; sqlite3Fts5StorageReleaseDeleteRow(pStorage); } - - } - } - - if( rc==SQLITE_OK - && bUpdateOrDelete - && pConfig->bSecureDelete - && pConfig->iVersion==FTS5_CURRENT_VERSION - ){ - rc = sqlite3Fts5StorageConfigValue( - pTab->pStorage, "version", 0, FTS5_CURRENT_VERSION_SECUREDELETE - ); - if( rc==SQLITE_OK ){ - pConfig->iVersion = FTS5_CURRENT_VERSION_SECUREDELETE; } } update_out: + sqlite3Fts5IndexCloseReader(pTab->p.pIndex); pTab->p.pConfig->pzErrmsg = 0; return rc; } @@ -253420,6 +264000,7 @@ static int fts5RollbackMethod(sqlite3_vtab *pVtab){ Fts5FullTable *pTab = (Fts5FullTable*)pVtab; fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0); rc = sqlite3Fts5StorageRollback(pTab->pStorage); + pTab->p.pConfig->pgsz = 0; return rc; } @@ -253968,19 +264549,23 @@ static int fts5ApiPhraseFirstColumn( if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){ Fts5Sorter *pSorter = pCsr->pSorter; - int n; - if( pSorter ){ - int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]); - n = pSorter->aIdx[iPhrase] - i1; - pIter->a = &pSorter->aPoslist[i1]; + if( iPhrase<0 || iPhrase>=sqlite3Fts5ExprPhraseCount(pCsr->pExpr) ){ + rc = SQLITE_RANGE; }else{ - rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n); - } - if( rc==SQLITE_OK ){ - assert( pIter->a || n==0 ); - pIter->b = (pIter->a ? &pIter->a[n] : 0); - *piCol = 0; - fts5ApiPhraseNextColumn(pCtx, pIter, piCol); + int n; + if( pSorter ){ + int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]); + n = pSorter->aIdx[iPhrase] - i1; + pIter->a = &pSorter->aPoslist[i1]; + }else{ + rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n); + } + if( rc==SQLITE_OK ){ + assert( pIter->a || n==0 ); + pIter->b = (pIter->a ? &pIter->a[n] : 0); + *piCol = 0; + fts5ApiPhraseNextColumn(pCtx, pIter, piCol); + } } }else{ int n; @@ -254888,7 +265473,7 @@ static void fts5SourceIdFunc( ){ assert( nArg==0 ); UNUSED_PARAM2(nArg, apUnused); - sqlite3_result_text(pCtx, "fts5: 2024-10-21 16:30:22 03a9703e27c44437c39363d0baf82db4ebc94538a0f28411c85dda156f82636e", -1, SQLITE_TRANSIENT); + sqlite3_result_text(pCtx, "fts5: 2026-10-16 14:45:20 555e07ef33f69a0957d24d8e555b702464a131d6f1607f4c3c1e4551e8e6ca76", -1, SQLITE_TRANSIENT); } /* @@ -254911,9 +265496,9 @@ static void fts5LocaleFunc( sqlite3_value **apArg /* Function arguments */ ){ const char *zLocale = 0; - int nLocale = 0; + i64 nLocale = 0; const char *zText = 0; - int nText = 0; + i64 nText = 0; assert( nArg==2 ); UNUSED_PARAM(nArg); @@ -254930,10 +265515,10 @@ static void fts5LocaleFunc( Fts5Global *p = (Fts5Global*)sqlite3_user_data(pCtx); u8 *pBlob = 0; u8 *pCsr = 0; - int nBlob = 0; + i64 nBlob = 0; nBlob = FTS5_LOCALE_HDR_SIZE + nLocale + 1 + nText; - pBlob = (u8*)sqlite3_malloc(nBlob); + pBlob = (u8*)sqlite3_malloc64(nBlob); if( pBlob==0 ){ sqlite3_result_error_nomem(pCtx); return; @@ -254952,6 +265537,20 @@ static void fts5LocaleFunc( } } +/* +** Implementation of fts5_insttoken() function. +*/ +static void fts5InsttokenFunc( + sqlite3_context *pCtx, /* Function call context */ + int nArg, /* Number of args */ + sqlite3_value **apArg /* Function arguments */ +){ + assert( nArg==1 ); + (void)nArg; + sqlite3_result_value(pCtx, apArg[0]); + sqlite3_result_subtype(pCtx, FTS5_INSTTOKEN_SUBTYPE); +} + /* ** Return true if zName is the extension on one of the shadow tables used ** by this module. @@ -254997,8 +265596,9 @@ static int fts5IntegrityMethod( " FTS5 table %s.%s: %s", zSchema, zTabname, sqlite3_errstr(rc)); } + }else if( (rc&0xff)==SQLITE_CORRUPT ){ + rc = SQLITE_OK; } - sqlite3Fts5IndexCloseReader(pTab->p.pIndex); pTab->p.pConfig->pzErrmsg = 0; @@ -255037,7 +265637,7 @@ static int fts5Init(sqlite3 *db){ int rc; Fts5Global *pGlobal = 0; - pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global)); + pGlobal = (Fts5Global*)sqlite3_malloc64(sizeof(Fts5Global)); if( pGlobal==0 ){ rc = SQLITE_NOMEM; }else{ @@ -255081,10 +265681,17 @@ static int fts5Init(sqlite3 *db){ if( rc==SQLITE_OK ){ rc = sqlite3_create_function( db, "fts5_locale", 2, - SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_RESULT_SUBTYPE, + SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_RESULT_SUBTYPE|SQLITE_SUBTYPE, p, fts5LocaleFunc, 0, 0 ); } + if( rc==SQLITE_OK ){ + rc = sqlite3_create_function( + db, "fts5_insttoken", 1, + SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_RESULT_SUBTYPE, + p, fts5InsttokenFunc, 0, 0 + ); + } } /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file @@ -255092,8 +265699,8 @@ static int fts5Init(sqlite3 *db){ ** its entry point to enable the matchinfo() demo. */ #ifdef SQLITE_FTS5_ENABLE_TEST_MI if( rc==SQLITE_OK ){ - extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*); - rc = sqlite3Fts5TestRegisterMatchinfo(db); + extern int sqlite3Fts5TestRegisterMatchinfoAPI(fts5_api*); + rc = sqlite3Fts5TestRegisterMatchinfoAPI(&pGlobal->api); } #endif @@ -255348,6 +265955,11 @@ static int fts5StorageGetStmt( if( rc!=SQLITE_OK && pzErrMsg ){ *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db)); } + if( rc==SQLITE_ERROR && eStmt>FTS5_STMT_LOOKUP2 && eStmt<FTS5_STMT_SCAN ){ + /* One of the internal tables - not the %_content table - is missing. + ** This counts as a corrupted table. */ + rc = SQLITE_CORRUPT; + } } } @@ -255503,34 +266115,31 @@ static int sqlite3Fts5StorageOpen( if( pConfig->eContent==FTS5_CONTENT_NORMAL || pConfig->eContent==FTS5_CONTENT_UNINDEXED ){ - int nDefn = 32 + pConfig->nCol*10; - char *zDefn = sqlite3_malloc64(32 + (sqlite3_int64)pConfig->nCol * 20); - if( zDefn==0 ){ - rc = SQLITE_NOMEM; - }else{ - int i; - int iOff; - sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY"); - iOff = (int)strlen(zDefn); - for(i=0; i<pConfig->nCol; i++){ - if( pConfig->eContent==FTS5_CONTENT_NORMAL - || pConfig->abUnindexed[i] - ){ - sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i); - iOff += (int)strlen(&zDefn[iOff]); - } + int i = 0; + char *zDefn = 0; + sqlite3_str *pDefn = sqlite3_str_new(pConfig->db); + + sqlite3_str_appendf(pDefn, "id INTEGER PRIMARY KEY"); + for(i=0; i<pConfig->nCol; i++){ + if( pConfig->eContent==FTS5_CONTENT_NORMAL || pConfig->abUnindexed[i] ){ + sqlite3_str_appendf(pDefn, ", c%d", i); } - if( pConfig->bLocale ){ - for(i=0; i<pConfig->nCol; i++){ - if( pConfig->abUnindexed[i]==0 ){ - sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", l%d", i); - iOff += (int)strlen(&zDefn[iOff]); - } + } + if( pConfig->bLocale ){ + for(i=0; i<pConfig->nCol; i++){ + if( pConfig->abUnindexed[i]==0 ){ + sqlite3_str_appendf(pDefn, ", l%d", i); } } + } + zDefn = sqlite3_str_finish(pDefn); + + if( zDefn ){ rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr); + sqlite3_free(zDefn); + }else{ + rc = SQLITE_NOMEM; } - sqlite3_free(zDefn); } if( rc==SQLITE_OK && pConfig->bColumnsize ){ @@ -255677,6 +266286,7 @@ static int fts5StorageDeleteFromIndex( for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){ if( pConfig->abUnindexed[iCol-1]==0 ){ sqlite3_value *pVal = 0; + sqlite3_value *pFree = 0; const char *pText = 0; int nText = 0; const char *pLoc = 0; @@ -255693,11 +266303,22 @@ static int fts5StorageDeleteFromIndex( if( pConfig->bLocale && sqlite3Fts5IsLocaleValue(pConfig, pVal) ){ rc = sqlite3Fts5DecodeLocaleValue(pVal, &pText, &nText, &pLoc, &nLoc); }else{ - pText = (const char*)sqlite3_value_text(pVal); - nText = sqlite3_value_bytes(pVal); - if( pConfig->bLocale && pSeek ){ - pLoc = (const char*)sqlite3_column_text(pSeek, iCol + pConfig->nCol); - nLoc = sqlite3_column_bytes(pSeek, iCol + pConfig->nCol); + if( sqlite3_value_type(pVal)!=SQLITE_TEXT ){ + /* Make a copy of the value to work with. This is because the call + ** to sqlite3_value_text() below forces the type of the value to + ** SQLITE_TEXT, and we may need to use it again later. */ + pFree = pVal = sqlite3_value_dup(pVal); + if( pVal==0 ){ + rc = SQLITE_NOMEM; + } + } + if( rc==SQLITE_OK ){ + pText = (const char*)sqlite3_value_text(pVal); + nText = sqlite3_value_bytes(pVal); + if( pConfig->bLocale && pSeek ){ + pLoc = (const char*)sqlite3_column_text(pSeek, iCol+pConfig->nCol); + nLoc = sqlite3_column_bytes(pSeek, iCol + pConfig->nCol); + } } } @@ -255713,6 +266334,7 @@ static int fts5StorageDeleteFromIndex( } sqlite3Fts5ClearLocale(pConfig); } + sqlite3_value_free(pFree); } } if( rc==SQLITE_OK && p->nTotalRow<1 ){ @@ -255744,6 +266366,64 @@ static void sqlite3Fts5StorageReleaseDeleteRow(Fts5Storage *pStorage){ pStorage->pSavedRow = 0; } +/* +** Load the contents of the "averages" record from disk into the +** p->nTotalRow and p->aTotalSize[] variables. If successful, and if +** argument bCache is true, set the p->bTotalsValid flag to indicate +** that the contents of aTotalSize[] and nTotalRow are valid until +** further notice. +** +** Return SQLITE_OK if successful, or an SQLite error code if an error +** occurs. +*/ +static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){ + int rc = SQLITE_OK; + if( p->bTotalsValid==0 ){ + rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize); + p->bTotalsValid = bCache; + } + return rc; +} + +/* +** Store the current contents of the p->nTotalRow and p->aTotalSize[] +** variables in the "averages" record on disk. +** +** Return SQLITE_OK if successful, or an SQLite error code if an error +** occurs. +*/ +static int fts5StorageSaveTotals(Fts5Storage *p){ + int nCol = p->pConfig->nCol; + int i; + Fts5Buffer buf; + int rc = SQLITE_OK; + memset(&buf, 0, sizeof(buf)); + + sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow); + for(i=0; i<nCol; i++){ + sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]); + } + if( rc==SQLITE_OK ){ + rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n); + } + sqlite3_free(buf.p); + + return rc; +} + +static int fts5StorageDecodeSizeArray( + int *aCol, int nCol, /* Array to populate */ + const u8 *aBlob, int nBlob /* Record to read varints from */ +){ + int i; + int iOff = 0; + for(i=0; i<nCol; i++){ + if( iOff>=nBlob ) return 1; + iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]); + } + return (iOff!=nBlob); +} + /* ** This function is called to process a DELETE on a contentless_delete=1 ** table. It adds the tombstone required to delete the entry with rowid @@ -255760,19 +266440,41 @@ static int fts5StorageContentlessDelete(Fts5Storage *p, i64 iDel){ || p->pConfig->eContent==FTS5_CONTENT_UNINDEXED ); + rc = fts5StorageLoadTotals(p, 1); + if( rc!=SQLITE_OK ) return rc; + /* Look up the origin of the document in the %_docsize table. Store ** this in stack variable iOrigin. */ rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0); if( rc==SQLITE_OK ){ + int rc2; sqlite3_bind_int64(pLookup, 1, iDel); if( SQLITE_ROW==sqlite3_step(pLookup) ){ - iOrigin = sqlite3_column_int64(pLookup, 1); + int *aCol = (int*)sqlite3_malloc64(p->pConfig->nCol * sizeof(int)); + if( aCol==0 ){ + rc = SQLITE_NOMEM; + }else{ + const u8 *aBlob = sqlite3_column_blob(pLookup, 0); + int nBlob = sqlite3_column_bytes(pLookup, 0); + int ii; + if( fts5StorageDecodeSizeArray(aCol, p->pConfig->nCol, aBlob, nBlob) ){ + rc = SQLITE_CORRUPT_VTAB; + }else{ + for(ii=0; ii<p->pConfig->nCol; ii++){ + p->aTotalSize[ii] -= aCol[ii]; + } + } + sqlite3_free(aCol); + } + iOrigin = sqlite3_column_int(pLookup, 1); } - rc = sqlite3_reset(pLookup); + rc2 = sqlite3_reset(pLookup); + if( rc==SQLITE_OK ) rc = rc2; } if( rc==SQLITE_OK && iOrigin!=0 ){ rc = sqlite3Fts5IndexContentlessDelete(p->pIndex, iOrigin, iDel); + p->nTotalRow--; } return rc; @@ -255813,51 +266515,6 @@ static int fts5StorageInsertDocsize( return rc; } -/* -** Load the contents of the "averages" record from disk into the -** p->nTotalRow and p->aTotalSize[] variables. If successful, and if -** argument bCache is true, set the p->bTotalsValid flag to indicate -** that the contents of aTotalSize[] and nTotalRow are valid until -** further notice. -** -** Return SQLITE_OK if successful, or an SQLite error code if an error -** occurs. -*/ -static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){ - int rc = SQLITE_OK; - if( p->bTotalsValid==0 ){ - rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize); - p->bTotalsValid = bCache; - } - return rc; -} - -/* -** Store the current contents of the p->nTotalRow and p->aTotalSize[] -** variables in the "averages" record on disk. -** -** Return SQLITE_OK if successful, or an SQLite error code if an error -** occurs. -*/ -static int fts5StorageSaveTotals(Fts5Storage *p){ - int nCol = p->pConfig->nCol; - int i; - Fts5Buffer buf; - int rc = SQLITE_OK; - memset(&buf, 0, sizeof(buf)); - - sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow); - for(i=0; i<nCol; i++){ - sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]); - } - if( rc==SQLITE_OK ){ - rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n); - } - sqlite3_free(buf.p); - - return rc; -} - /* ** Remove a row from the FTS table. */ @@ -256519,19 +267176,6 @@ static void sqlite3Fts5StorageStmtRelease( } } -static int fts5StorageDecodeSizeArray( - int *aCol, int nCol, /* Array to populate */ - const u8 *aBlob, int nBlob /* Record to read varints from */ -){ - int i; - int iOff = 0; - for(i=0; i<nCol; i++){ - if( iOff>=nBlob ) return 1; - iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]); - } - return (iOff!=nBlob); -} - /* ** Argument aCol points to an array of integers containing one entry for ** each table column. This function reads the %_docsize record for the @@ -256728,7 +267372,7 @@ static int fts5AsciiCreate( if( nArg%2 ){ rc = SQLITE_ERROR; }else{ - p = sqlite3_malloc(sizeof(AsciiTokenizer)); + p = sqlite3_malloc64(sizeof(AsciiTokenizer)); if( p==0 ){ rc = SQLITE_NOMEM; }else{ @@ -256833,13 +267477,10 @@ static int fts5AsciiTokenize( /* -** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied -** from the sqlite3 source file utf.c. If this file is compiled as part -** of the amalgamation, they are not required. +** The following two macros - FTS5_READ_UTF8 and FTS5_WRITE_UTF8 - have +** been copied from the sqlite3 source file utf.c. */ -#ifndef SQLITE_AMALGAMATION - -static const unsigned char sqlite3Utf8Trans1[] = { +static const unsigned char fts5Utf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, @@ -256850,45 +267491,43 @@ static const unsigned char sqlite3Utf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, }; -#define READ_UTF8(zIn, zTerm, c) \ +#define FTS5_READ_UTF8(zIn, zTerm, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ - c = sqlite3Utf8Trans1[c-0xc0]; \ + c = fts5Utf8Trans1[c-0xc0]; \ while( zIn<zTerm && (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ if( c<0x80 \ - || (c&0xFFFFF800)==0xD800 \ - || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ + || (c&0xFFFFF800)==0xD800 \ + || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ } -#define WRITE_UTF8(zOut, c) { \ - if( c<0x00080 ){ \ - *zOut++ = (unsigned char)(c&0xFF); \ - } \ - else if( c<0x00800 ){ \ - *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \ - *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \ - } \ - else if( c<0x10000 ){ \ - *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \ - *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \ - *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \ - }else{ \ - *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \ - *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \ - *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \ - *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \ - } \ +#define FTS5_WRITE_UTF8(zOut, c) { \ + if( c<0x00080 ){ \ + *zOut++ = (unsigned char)(c&0xFF); \ + } \ + else if( c<0x00800 ){ \ + *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \ + *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \ + } \ + else if( c<0x10000 ){ \ + *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \ + *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \ + *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \ + }else{ \ + *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \ + *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \ + *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \ + *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \ + } \ } -#endif /* ifndef SQLITE_AMALGAMATION */ - -#define FTS5_SKIP_UTF8(zIn) { \ - if( ((unsigned char)(*(zIn++)))>=0xc0 ){ \ - while( (((unsigned char)*zIn) & 0xc0)==0x80 ){ zIn++; } \ - } \ +#define FTS5_SKIP_UTF8(zIn) { \ + if( ((unsigned char)(*(zIn++)))>=0xc0 ){ \ + while( (((unsigned char)*zIn) & 0xc0)==0x80 ){zIn++;} \ + } \ } typedef struct Unicode61Tokenizer Unicode61Tokenizer; @@ -256927,7 +267566,7 @@ static int fts5UnicodeAddExceptions( while( zCsr<zTerm ){ u32 iCode; int bToken; - READ_UTF8(zCsr, zTerm, iCode); + FTS5_READ_UTF8(zCsr, zTerm, iCode); if( iCode<128 ){ p->aTokenChar[iCode] = (unsigned char)bTokenChars; }else{ @@ -257023,7 +267662,7 @@ static int fts5UnicodeCreate( if( nArg%2 ){ rc = SQLITE_ERROR; }else{ - p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer)); + p = (Unicode61Tokenizer*)sqlite3_malloc64(sizeof(Unicode61Tokenizer)); if( p ){ const char *zCat = "L* N* Co"; int i; @@ -257131,7 +267770,7 @@ static int fts5UnicodeTokenize( /* A character outside of the ascii range. Skip past it if it is ** a separator character. Or break out of the loop if it is not. */ is = zCsr - (unsigned char*)pText; - READ_UTF8(zCsr, zTerm, iCode); + FTS5_READ_UTF8(zCsr, zTerm, iCode); if( fts5UnicodeIsAlnum(p, iCode) ){ goto non_ascii_tokenchar; } @@ -257167,11 +267806,11 @@ static int fts5UnicodeTokenize( if( *zCsr & 0x80 ){ /* An non-ascii-range character. Fold it into the output buffer if ** it is a token character, or break out of the loop if it is not. */ - READ_UTF8(zCsr, zTerm, iCode); + FTS5_READ_UTF8(zCsr, zTerm, iCode); if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){ non_ascii_tokenchar: iCode = sqlite3Fts5UnicodeFold(iCode, p->eRemoveDiacritic); - if( iCode ) WRITE_UTF8(zOut, iCode); + if( iCode ) FTS5_WRITE_UTF8(zOut, iCode); }else{ break; } @@ -257242,11 +267881,17 @@ static int fts5PorterCreate( const char *zBase = "unicode61"; fts5_tokenizer_v2 *pV2 = 0; - if( nArg>0 ){ - zBase = azArg[0]; + while( nArg>0 ){ + if( sqlite3_stricmp(azArg[0],"porter")==0 ){ + nArg--; + azArg++; + }else{ + zBase = azArg[0]; + break; + } } - pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer)); + pRet = (PorterTokenizer*)sqlite3_malloc64(sizeof(PorterTokenizer)); if( pRet ){ memset(pRet, 0, sizeof(PorterTokenizer)); rc = pApi->xFindTokenizer_v2(pApi, zBase, &pUserdata, &pV2); @@ -257368,9 +268013,9 @@ static int fts5Porter_Ostar(char *zStem, int nStem){ for(i=0; i<nStem; i++){ bCons = !fts5PorterIsVowel(zStem[i], bCons); assert( bCons==0 || bCons==1 ); - mask = (mask << 1) + bCons; + mask = ((mask << 1) + bCons) & 0x0007; } - return ((mask & 0x0007)==0x0005); + return (mask==0x0005); } } @@ -257953,7 +268598,7 @@ static int fts5TriCreate( rc = SQLITE_ERROR; }else{ int i; - pNew = (TrigramTokenizer*)sqlite3_malloc(sizeof(*pNew)); + pNew = (TrigramTokenizer*)sqlite3_malloc64(sizeof(*pNew)); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ @@ -258009,8 +268654,8 @@ static int fts5TriTokenize( char *zOut = aBuf; int ii; const unsigned char *zIn = (const unsigned char*)pText; - const unsigned char *zEof = &zIn[nText]; - u32 iCode; + const unsigned char *zEof = (zIn ? &zIn[nText] : 0); + u32 iCode = 0; int aStart[3]; /* Input offset of each character in aBuf[] */ UNUSED_PARAM(unusedFlags); @@ -258019,11 +268664,11 @@ static int fts5TriTokenize( for(ii=0; ii<3; ii++){ do { aStart[ii] = zIn - (const unsigned char*)pText; - READ_UTF8(zIn, zEof, iCode); - if( iCode==0 ) return SQLITE_OK; + if( zIn>=zEof ) return SQLITE_OK; + FTS5_READ_UTF8(zIn, zEof, iCode); if( p->bFold ) iCode = sqlite3Fts5UnicodeFold(iCode, p->iFoldParam); }while( iCode==0 ); - WRITE_UTF8(zOut, iCode); + FTS5_WRITE_UTF8(zOut, iCode); } /* At the start of each iteration of this loop: @@ -258041,8 +268686,11 @@ static int fts5TriTokenize( /* Read characters from the input up until the first non-diacritic */ do { iNext = zIn - (const unsigned char*)pText; - READ_UTF8(zIn, zEof, iCode); - if( iCode==0 ) break; + if( zIn>=zEof ){ + iCode = 0; + break; + } + FTS5_READ_UTF8(zIn, zEof, iCode); if( p->bFold ) iCode = sqlite3Fts5UnicodeFold(iCode, p->iFoldParam); }while( iCode==0 ); @@ -258056,7 +268704,7 @@ static int fts5TriTokenize( FTS5_SKIP_UTF8(z1); memmove(aBuf, z1, zOut - z1); zOut -= (z1 - aBuf); - WRITE_UTF8(zOut, iCode); + FTS5_WRITE_UTF8(zOut, iCode); /* Update the aStart[] array */ aStart[0] = aStart[1]; @@ -258923,7 +269571,6 @@ static void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){ aAscii[0] = 0; /* 0x00 is never a token character */ } - /* ** 2015 May 30 ** @@ -259464,12 +270111,12 @@ static int fts5VocabInitVtab( *pzErr = sqlite3_mprintf("wrong number of vtable arguments"); rc = SQLITE_ERROR; }else{ - int nByte; /* Bytes of space to allocate */ + i64 nByte; /* Bytes of space to allocate */ const char *zDb = bDb ? argv[3] : argv[1]; const char *zTab = bDb ? argv[4] : argv[3]; const char *zType = bDb ? argv[5] : argv[4]; - int nDb = (int)strlen(zDb)+1; - int nTab = (int)strlen(zTab)+1; + i64 nDb = strlen(zDb)+1; + i64 nTab = strlen(zTab)+1; int eType = 0; rc = fts5VocabTableType(zType, pzErr, &eType); @@ -259523,6 +270170,14 @@ static int fts5VocabCreateMethod( return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr); } +/* +** Return true if constraint iCons of pInfo uses the "binary" collation +** sequence. Or false it it uses anything else. +*/ +static int fts5VocabIsBinary(sqlite3_index_info *pInfo, int iCons){ + return 0==sqlite3_stricmp("binary", sqlite3_vtab_collation(pInfo, iCons)); +} + /* ** Implementation of the xBestIndex method. ** @@ -259553,7 +270208,7 @@ static int fts5VocabBestIndexMethod( for(i=0; i<pInfo->nConstraint; i++){ struct sqlite3_index_constraint *p = &pInfo->aConstraint[i]; if( p->usable==0 ) continue; - if( p->iColumn==0 ){ /* term column */ + if( p->iColumn==0 && fts5VocabIsBinary(pInfo, i) ){ /* term column */ if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i; if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i; if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i; @@ -259667,7 +270322,12 @@ static int fts5VocabOpenMethod( return rc; } +/* +** Restore cursor pCsr to the state it was in immediately after being +** created by the xOpen() method. +*/ static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){ + int nCol = pCsr->pFts5->pConfig->nCol; pCsr->rowid = 0; sqlite3Fts5IterClose(pCsr->pIter); sqlite3Fts5StructureRelease(pCsr->pStruct); @@ -259677,6 +270337,12 @@ static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){ pCsr->nLeTerm = -1; pCsr->zLeTerm = 0; pCsr->bEof = 0; + pCsr->iCol = 0; + pCsr->iInstPos = 0; + pCsr->iInstOff = 0; + pCsr->colUsed = 0; + memset(pCsr->aCnt, 0, sizeof(i64)*nCol); + memset(pCsr->aDoc, 0, sizeof(i64)*nCol); } /* @@ -259881,6 +270547,26 @@ static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){ return rc; } +/* +** If value pVal is an SQLITE_TEXT value, return a pointer to a buffer +** containing the UTF-8 representation of the value, and set output +** parameter (*pnText) to the size of the buffer contents in bytes. Or, +** if pVal is some other type of value, return NULL and set (*pnText) +** to 0 before returning. +*/ +static const char *fts5VocabValueText(sqlite3_value *pVal, int *pnText){ + const char *zRet = 0; + int nRet = 0; + + if( sqlite3_value_type(pVal)==SQLITE_TEXT ){ + zRet = (const char*)sqlite3_value_text(pVal); + nRet = sqlite3_value_bytes(pVal); + } + + *pnText = nRet; + return zRet; +} + /* ** This is the xFilter implementation for the virtual table. */ @@ -259908,25 +270594,31 @@ static int fts5VocabFilterMethod( UNUSED_PARAM2(zUnused, nUnused); fts5VocabResetCursor(pCsr); - if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++]; - if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++]; - if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++]; + if( idxNum & FTS5_VOCAB_TERM_EQ ){ + pEq = apVal[iVal++]; + if( sqlite3_value_type(pEq)!=SQLITE_TEXT ) pEq = 0; + } + if( idxNum & FTS5_VOCAB_TERM_GE ){ + pGe = apVal[iVal++]; + if( sqlite3_value_type(pGe)!=SQLITE_TEXT ) pGe = 0; + } + if( idxNum & FTS5_VOCAB_TERM_LE ){ + pLe = apVal[iVal++]; + if( sqlite3_value_type(pLe)!=SQLITE_TEXT ) pLe = 0; + } pCsr->colUsed = (idxNum & FTS5_VOCAB_COLUSED_MASK); if( pEq ){ - zTerm = (const char *)sqlite3_value_text(pEq); - nTerm = sqlite3_value_bytes(pEq); + zTerm = fts5VocabValueText(pEq, &nTerm); f = FTS5INDEX_QUERY_NOTOKENDATA; }else{ if( pGe ){ - zTerm = (const char *)sqlite3_value_text(pGe); - nTerm = sqlite3_value_bytes(pGe); + zTerm = fts5VocabValueText(pGe, &nTerm); } if( pLe ){ - const char *zCopy = (const char *)sqlite3_value_text(pLe); + const char *zCopy = fts5VocabValueText(pLe, &pCsr->nLeTerm); if( zCopy==0 ) zCopy = ""; - pCsr->nLeTerm = sqlite3_value_bytes(pLe); - pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1); + pCsr->zLeTerm = sqlite3_malloc64((i64)pCsr->nLeTerm+1); if( pCsr->zLeTerm==0 ){ rc = SQLITE_NOMEM; }else{ @@ -260079,7 +270771,7 @@ static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){ } - +/* Here ends the fts5.c composite file. */ #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */ /************** End of fts5.c ************************************************/ @@ -260435,4 +271127,5 @@ SQLITE_API int sqlite3_stmt_init( /************** End of stmt.c ************************************************/ /* Return the source-id for this library */ SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } +#endif /* SQLITE_AMALGAMATION */ /************************** End of sqlite3.c ******************************/ diff --git a/SQLite/sqlite3.h b/SQLite/sqlite3.h index eaffd1e..30d431b 100644 --- a/SQLite/sqlite3.h +++ b/SQLite/sqlite3.h @@ -133,7 +133,7 @@ extern "C" { ** ** Since [version 3.6.18] ([dateof:3.6.18]), ** SQLite source code has been stored in the -** <a href="http://www.fossil-scm.org/">Fossil configuration management +** <a href="http://fossil-scm.org/">Fossil configuration management ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to ** a string which identifies a particular check-in of SQLite ** within its configuration management system. ^The SQLITE_SOURCE_ID @@ -146,9 +146,12 @@ extern "C" { ** [sqlite3_libversion_number()], [sqlite3_sourceid()], ** [sqlite_version()] and [sqlite_source_id()]. */ -#define SQLITE_VERSION "3.47.0" -#define SQLITE_VERSION_NUMBER 3047000 -#define SQLITE_SOURCE_ID "2024-10-21 16:30:22 03a9703e27c44437c39363d0baf82db4ebc94538a0f28411c85dda156f82636e" +#define SQLITE_VERSION "3.54.1" +#define SQLITE_VERSION_NUMBER 3054001 +#define SQLITE_SOURCE_ID "2026-10-16 14:45:20 555e07ef33f69a0957d24d8e555b702464a131d6f1607f4c3c1e4551e8e6ca76" +#define SQLITE_SCM_BRANCH "branch-3.54" +#define SQLITE_SCM_TAGS "release version-3.54.1" +#define SQLITE_SCM_DATETIME "2026-10-16T14:45:20.546Z" /* ** CAPI3REF: Run-Time Library Version Numbers @@ -168,9 +171,9 @@ extern "C" { ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 ); ** </pre></blockquote>)^ ** -** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] -** macro. ^The sqlite3_libversion() function returns a pointer to the -** to the sqlite3_version[] string constant. The sqlite3_libversion() +** ^The sqlite3_version[] string constant contains the text of the +** [SQLITE_VERSION] macro. ^The sqlite3_libversion() function returns a +** pointer to the sqlite3_version[] string constant. The sqlite3_libversion() ** function is provided for use in DLLs since DLL users usually do not have ** direct access to string constants within the DLL. ^The ** sqlite3_libversion_number() function returns an integer equal to @@ -370,7 +373,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**); ** without having to use a lot of C code. ** ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, -** semicolon-separate SQL statements passed into its 2nd argument, +** semicolon-separated SQL statements passed into its 2nd argument, ** in the context of the [database connection] passed in as its 1st ** argument. ^If the callback function of the 3rd argument to ** sqlite3_exec() is not NULL, then it is invoked for each result row @@ -403,7 +406,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**); ** result row is NULL then the corresponding string pointer for the ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the ** sqlite3_exec() callback is an array of pointers to strings where each -** entry represents the name of corresponding result column as obtained +** entry represents the name of a corresponding result column as obtained ** from [sqlite3_column_name()]. ** ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer @@ -460,7 +463,7 @@ SQLITE_API int sqlite3_exec( #define SQLITE_FULL 13 /* Insertion failed because database is full */ #define SQLITE_CANTOPEN 14 /* Unable to open the database file */ #define SQLITE_PROTOCOL 15 /* Database lock protocol error */ -#define SQLITE_EMPTY 16 /* Internal use only */ +#define SQLITE_EMPTY 16 /* No content */ #define SQLITE_SCHEMA 17 /* The database schema changed */ #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ @@ -497,6 +500,9 @@ SQLITE_API int sqlite3_exec( #define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8)) #define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8)) #define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8)) +#define SQLITE_ERROR_RESERVESIZE (SQLITE_ERROR | (4<<8)) +#define SQLITE_ERROR_KEY (SQLITE_ERROR | (5<<8)) +#define SQLITE_ERROR_UNABLE (SQLITE_ERROR | (6<<8)) #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) @@ -531,6 +537,8 @@ SQLITE_API int sqlite3_exec( #define SQLITE_IOERR_DATA (SQLITE_IOERR | (32<<8)) #define SQLITE_IOERR_CORRUPTFS (SQLITE_IOERR | (33<<8)) #define SQLITE_IOERR_IN_PAGE (SQLITE_IOERR | (34<<8)) +#define SQLITE_IOERR_BADKEY (SQLITE_IOERR | (35<<8)) +#define SQLITE_IOERR_CODEC (SQLITE_IOERR | (36<<8)) #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) #define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8)) #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) @@ -570,7 +578,7 @@ SQLITE_API int sqlite3_exec( #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8)) #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8)) -#define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8)) /* internal use only */ +#define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8)) /* internal only */ /* ** CAPI3REF: Flags For File Open Operations @@ -589,7 +597,7 @@ SQLITE_API int sqlite3_exec( ** Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into ** [sqlite3_open_v2()] does *not* cause the underlying database file ** to be opened using O_EXCL. Passing SQLITE_OPEN_EXCLUSIVE into -** [sqlite3_open_v2()] has historically be a no-op and might become an +** [sqlite3_open_v2()] has historically been a no-op and might become an ** error in future versions of SQLite. */ #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ @@ -652,6 +660,13 @@ SQLITE_API int sqlite3_exec( ** filesystem supports doing multiple write operations atomically when those ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. +** +** The SQLITE_IOCAP_SUBPAGE_READ property means that it is ok to read +** from the database file in amounts that are not a multiple of the +** page size and that do not begin at a page boundary. Without this +** property, SQLite is careful to only do full-page reads and write +** on aligned pages, with the one exception that it will do a sub-page +** read of the first page to access the database header. */ #define SQLITE_IOCAP_ATOMIC 0x00000001 #define SQLITE_IOCAP_ATOMIC512 0x00000002 @@ -668,6 +683,7 @@ SQLITE_API int sqlite3_exec( #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 #define SQLITE_IOCAP_IMMUTABLE 0x00002000 #define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000 +#define SQLITE_IOCAP_SUBPAGE_READ 0x00008000 /* ** CAPI3REF: File Locking Levels @@ -675,7 +691,7 @@ SQLITE_API int sqlite3_exec( ** SQLite uses one of these integer values as the second ** argument to calls it makes to the xLock() and xUnlock() methods ** of an [sqlite3_io_methods] object. These values are ordered from -** lest restrictive to most restrictive. +** least restrictive to most restrictive. ** ** The argument to xLock() is always SHARED or higher. The argument to ** xUnlock is either SHARED or NONE. @@ -814,6 +830,7 @@ struct sqlite3_file { ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE] ** <li> [SQLITE_IOCAP_IMMUTABLE] ** <li> [SQLITE_IOCAP_BATCH_ATOMIC] +** <li> [SQLITE_IOCAP_SUBPAGE_READ] ** </ul> ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of @@ -915,7 +932,7 @@ struct sqlite3_io_methods { ** connection. See also [SQLITE_FCNTL_FILE_POINTER]. ** ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]] -** No longer in use. +** The SQLITE_FCNTL_SYNC_OMITTED file-control is no longer used. ** ** <li>[[SQLITE_FCNTL_SYNC]] ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and @@ -990,7 +1007,7 @@ struct sqlite3_io_methods { ** ** <li>[[SQLITE_FCNTL_VFSNAME]] ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of -** all [VFSes] in the VFS stack. The names are of all VFS shims and the +** all [VFSes] in the VFS stack. The names of all VFS shims and the ** final bottom-level VFS are written into memory obtained from ** [sqlite3_malloc()] and the result is stored in the char* variable ** that the fourth parameter of [sqlite3_file_control()] points to. @@ -1004,7 +1021,7 @@ struct sqlite3_io_methods { ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level ** [VFSes] currently in use. ^(The argument X in ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be -** of type "[sqlite3_vfs] **". This opcodes will set *X +** of type "[sqlite3_vfs] **". This opcode will set *X ** to a pointer to the top-level VFS.)^ ** ^When there are multiple VFS shims in the stack, this opcode finds the ** upper-most shim only. @@ -1091,6 +1108,11 @@ struct sqlite3_io_methods { ** pointed to by the pArg argument. This capability is used during testing ** and only needs to be supported when SQLITE_TEST is defined. ** +** <li>[[SQLITE_FCNTL_NULL_IO]] +** The [SQLITE_FCNTL_NULL_IO] opcode sets the low-level file descriptor +** or file handle for the [sqlite3_file] object such that it will no longer +** read or write to the database file. +** ** <li>[[SQLITE_FCNTL_WAL_BLOCK]] ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might ** be advantageous to block on the next WAL lock if the lock is not immediately @@ -1149,6 +1171,12 @@ struct sqlite3_io_methods { ** the value that M is to be set to. Before returning, the 32-bit signed ** integer is overwritten with the previous value of M. ** +** <li>[[SQLITE_FCNTL_BLOCK_ON_CONNECT]] +** The [SQLITE_FCNTL_BLOCK_ON_CONNECT] opcode is used to configure the +** VFS to block when taking a SHARED lock to connect to a wal mode database. +** This is used to implement the functionality associated with +** SQLITE_SETLK_BLOCK_ON_CONNECT. +** ** <li>[[SQLITE_FCNTL_DATA_VERSION]] ** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to ** a database file. The argument is a pointer to a 32-bit unsigned integer. @@ -1183,7 +1211,7 @@ struct sqlite3_io_methods { ** <li>[[SQLITE_FCNTL_EXTERNAL_READER]] ** The EXPERIMENTAL [SQLITE_FCNTL_EXTERNAL_READER] opcode is used to detect ** whether or not there is a database client in another process with a wal-mode -** transaction open on the database or not. It is only available on unix.The +** transaction open on the database or not. It is only available on unix. The ** (void*) argument passed with this file-control should be a pointer to a ** value of type (int). The integer value is set to 1 if the database is a wal ** mode database and there exists at least one client in another process that @@ -1201,6 +1229,15 @@ struct sqlite3_io_methods { ** database is not a temp db, then the [SQLITE_FCNTL_RESET_CACHE] file-control ** purges the contents of the in-memory page cache. If there is an open ** transaction, or if the db is a temp-db, this opcode is a no-op, not an error. +** +** <li>[[SQLITE_FCNTL_FILESTAT]] +** The [SQLITE_FCNTL_FILESTAT] opcode returns low-level diagnostic information +** about the [sqlite3_file] objects used access the database and journal files +** for the given schema. The fourth parameter to [sqlite3_file_control()] +** should be an initialized [sqlite3_str] pointer. JSON text describing +** various aspects of the sqlite3_file object is appended to the sqlite3_str. +** The SQLITE_FCNTL_FILESTAT opcode is usually a no-op, unless compile-time +** options are used to enable it. ** </ul> */ #define SQLITE_FCNTL_LOCKSTATE 1 @@ -1244,12 +1281,21 @@ struct sqlite3_io_methods { #define SQLITE_FCNTL_EXTERNAL_READER 40 #define SQLITE_FCNTL_CKSM_FILE 41 #define SQLITE_FCNTL_RESET_CACHE 42 +#define SQLITE_FCNTL_NULL_IO 43 +#define SQLITE_FCNTL_BLOCK_ON_CONNECT 44 +#define SQLITE_FCNTL_FILESTAT 45 /* deprecated names */ #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO +/* reserved file-control numbers: +** 101 +** 102 +** 103 +*/ + /* ** CAPI3REF: Mutex Handle @@ -1450,7 +1496,7 @@ typedef const char *sqlite3_filename; ** greater and the function pointer is not NULL) and will fall back ** to xCurrentTime() if xCurrentTimeInt64() is unavailable. ** -** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces +** ^The xSetSystemCall(), xGetSystemCall(), and xNextSystemCall() interfaces ** are not used by the SQLite core. These optional interfaces are provided ** by some VFSes to facilitate testing of the VFS code. By overriding ** system calls with functions under its control, a test program can @@ -1606,7 +1652,7 @@ struct sqlite3_vfs { ** SQLite interfaces so that an application usually does not need to ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] ** calls sqlite3_initialize() so the SQLite library will be automatically -** initialized when [sqlite3_open()] is called if it has not be initialized +** initialized when [sqlite3_open()] is called if it has not been initialized ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] ** compile-time option, then the automatic calls to sqlite3_initialize() ** are omitted and the application must call sqlite3_initialize() directly @@ -1671,7 +1717,8 @@ SQLITE_API int sqlite3_os_end(void); ** are called "anytime configuration options". ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before ** [sqlite3_shutdown()] with a first argument that is not an anytime -** configuration option, then the sqlite3_config() call will return SQLITE_MISUSE. +** configuration option, then the sqlite3_config() call will +** return SQLITE_MISUSE. ** Note, however, that ^sqlite3_config() can be called as part of the ** implementation of an application-defined [sqlite3_os_init()]. ** @@ -1863,21 +1910,21 @@ struct sqlite3_mem_methods { ** The [sqlite3_mem_methods] ** structure is filled with the currently defined memory allocation routines.)^ ** This option can be used to overload the default memory allocation -** routines with a wrapper that simulations memory allocation failure or +** routines with a wrapper that simulates memory allocation failure or ** tracks memory usage, for example. </dd> ** ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt> -** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of +** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes a single argument of ** type int, interpreted as a boolean, which if true provides a hint to ** SQLite that it should avoid large memory allocations if possible. ** SQLite will run faster if it is free to make large memory allocations, -** but some application might prefer to run slower in exchange for +** but some applications might prefer to run slower in exchange for ** guarantees about memory fragmentation that are possible if large ** allocations are avoided. This hint is normally off. ** </dd> ** ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt> -** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int, +** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes a single argument of type int, ** interpreted as a boolean, which enables or disables the collection of ** memory allocation statistics. ^(When memory allocation statistics are ** disabled, the following SQLite interfaces become non-operational: @@ -1922,7 +1969,7 @@ struct sqlite3_mem_methods { ** ^If pMem is NULL and N is non-zero, then each database connection ** does an initial bulk allocation for page cache memory ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or -** of -1024*N bytes if N is negative, . ^If additional +** of -1024*N bytes if N is negative. ^If additional ** page cache memory is needed beyond what is provided by the initial ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each ** additional cache line. </dd> @@ -1951,7 +1998,7 @@ struct sqlite3_mem_methods { ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a ** pointer to an instance of the [sqlite3_mutex_methods] structure. ** The argument specifies alternative low-level mutex routines to be used -** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of +** in place of the mutex routines built into SQLite.)^ ^SQLite makes a copy of ** the content of the [sqlite3_mutex_methods] structure before the call to ** [sqlite3_config()] returns. ^If SQLite is compiled with ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then @@ -1974,13 +2021,16 @@ struct sqlite3_mem_methods { ** ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt> ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine -** the default size of lookaside memory on each [database connection]. +** the default size of [lookaside memory] on each [database connection]. ** The first argument is the -** size of each lookaside buffer slot and the second is the number of -** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE -** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] -** option to [sqlite3_db_config()] can be used to change the lookaside -** configuration on individual connections.)^ </dd> +** size of each lookaside buffer slot ("sz") and the second is the number of +** slots allocated to each database connection ("cnt").)^ +** ^(SQLITE_CONFIG_LOOKASIDE sets the <i>default</i> lookaside size. +** The [SQLITE_DBCONFIG_LOOKASIDE] option to [sqlite3_db_config()] can +** be used to change the lookaside configuration on individual connections.)^ +** The [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to change the +** default lookaside configuration at compile-time. +** </dd> ** ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt> ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is @@ -1990,7 +2040,7 @@ struct sqlite3_mem_methods { ** ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt> ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which -** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of +** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies off ** the current page cache implementation into that object.)^ </dd> ** ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt> @@ -2007,7 +2057,7 @@ struct sqlite3_mem_methods { ** the logger function is a copy of the first parameter to the corresponding ** [sqlite3_log()] call and is intended to be a [result code] or an ** [extended result code]. ^The third parameter passed to the logger is -** log message after formatting via [sqlite3_snprintf()]. +** a log message after formatting via [sqlite3_snprintf()]. ** The SQLite logging interface is not reentrant; the logger function ** supplied by the application must not invoke any SQLite interface. ** In a multi-threaded application, the application-defined logger @@ -2196,7 +2246,15 @@ struct sqlite3_mem_methods { ** CAPI3REF: Database Connection Configuration Options ** ** These constants are the available integer configuration options that -** can be passed as the second argument to the [sqlite3_db_config()] interface. +** can be passed as the second parameter to the [sqlite3_db_config()] interface. +** +** The [sqlite3_db_config()] interface is a var-args function. It takes a +** variable number of parameters, though always at least two. The number of +** parameters passed into sqlite3_db_config() depends on which of these +** constants is given as the second parameter. This documentation page +** refers to parameters beyond the second as "arguments". Thus, when this +** page says "the N-th argument" it means "the N-th parameter past the +** configuration option" or "the (N+2)-th parameter to sqlite3_db_config()". ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications @@ -2208,31 +2266,58 @@ struct sqlite3_mem_methods { ** <dl> ** [[SQLITE_DBCONFIG_LOOKASIDE]] ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt> -** <dd> ^This option takes three additional arguments that determine the -** [lookaside memory allocator] configuration for the [database connection]. -** ^The first argument (the third parameter to [sqlite3_db_config()] is a +** <dd> The SQLITE_DBCONFIG_LOOKASIDE option is used to adjust the +** configuration of the [lookaside memory allocator] within a database +** connection. +** The arguments to the SQLITE_DBCONFIG_LOOKASIDE option are <i>not</i> +** in the [DBCONFIG arguments|usual format]. +** The SQLITE_DBCONFIG_LOOKASIDE option takes three arguments, not two, +** so that a call to [sqlite3_db_config()] that uses SQLITE_DBCONFIG_LOOKASIDE +** should have a total of five parameters. +** <ol> +** <li><p>The first argument ("buf") is a ** pointer to a memory buffer to use for lookaside memory. -** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb -** may be NULL in which case SQLite will allocate the -** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the -** size of each lookaside buffer slot. ^The third argument is the number of -** slots. The size of the buffer in the first argument must be greater than -** or equal to the product of the second and third arguments. The buffer -** must be aligned to an 8-byte boundary. ^If the second argument to -** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally -** rounded down to the next smaller multiple of 8. ^(The lookaside memory +** The first argument may be NULL in which case SQLite will allocate the +** lookaside buffer itself using [sqlite3_malloc()]. +** <li><P>The second argument ("sz") is the +** size of each lookaside buffer slot. Lookaside is disabled if "sz" +** is less than 8. The "sz" argument should be a multiple of 8 less than +** 65536. If "sz" does not meet this constraint, it is reduced in size until +** it does. +** <li><p>The third argument ("cnt") is the number of slots. +** Lookaside is disabled if "cnt"is less than 1. +* The "cnt" value will be reduced, if necessary, so +** that the product of "sz" and "cnt" does not exceed 2,147,418,112. The "cnt" +** parameter is usually chosen so that the product of "sz" and "cnt" is less +** than 1,000,000. +** </ol> +** <p>If the "buf" argument is not NULL, then it must +** point to a memory buffer with a size that is greater than +** or equal to the product of "sz" and "cnt". +** The buffer must be aligned to an 8-byte boundary. +** The lookaside memory ** configuration for a database connection can only be changed when that ** connection is not currently using lookaside memory, or in other words -** when the "current value" returned by -** [sqlite3_db_status](D,[SQLITE_DBSTATUS_LOOKASIDE_USED],...) is zero. +** when the value returned by [SQLITE_DBSTATUS_LOOKASIDE_USED] is zero. ** Any attempt to change the lookaside memory configuration when lookaside ** memory is in use leaves the configuration unchanged and returns -** [SQLITE_BUSY].)^</dd> +** [SQLITE_BUSY]. +** If the "buf" argument is NULL and an attempt +** to allocate memory based on "sz" and "cnt" fails, then +** lookaside is silently disabled. +** <p> +** The [SQLITE_CONFIG_LOOKASIDE] configuration option can be used to set the +** default lookaside configuration at initialization. The +** [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to set the default lookaside +** configuration at compile-time. Typical values for lookaside are 1200 for +** "sz" and 40 to 100 for "cnt". +** </dd> ** ** [[SQLITE_DBCONFIG_ENABLE_FKEY]] ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt> ** <dd> ^This option is used to enable or disable the enforcement of -** [foreign key constraints]. There should be two additional arguments. +** [foreign key constraints]. This is the same setting that is +** enabled or disabled by the [PRAGMA foreign_keys] statement. ** The first argument is an integer which is 0 to disable FK enforcement, ** positive to enable FK enforcement or negative to leave FK enforcement ** unchanged. The second parameter is a pointer to an integer into which @@ -2254,13 +2339,13 @@ struct sqlite3_mem_methods { ** <p>Originally this option disabled all triggers. ^(However, since ** SQLite version 3.35.0, TEMP triggers are still allowed even if ** this option is off. So, in other words, this option now only disables -** triggers in the main database schema or in the schemas of ATTACH-ed +** triggers in the main database schema or in the schemas of [ATTACH]-ed ** databases.)^ </dd> ** ** [[SQLITE_DBCONFIG_ENABLE_VIEW]] ** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt> ** <dd> ^This option is used to enable or disable [CREATE VIEW | views]. -** There should be two additional arguments. +** There must be two additional arguments. ** The first argument is an integer which is 0 to disable views, ** positive to enable views or negative to leave the setting unchanged. ** The second parameter is a pointer to an integer into which @@ -2276,17 +2361,20 @@ struct sqlite3_mem_methods { ** ** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]] ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt> -** <dd> ^This option is used to enable or disable the -** [fts3_tokenizer()] function which is part of the -** [FTS3] full-text search engine extension. -** There should be two additional arguments. -** The first argument is an integer which is 0 to disable fts3_tokenizer() or -** positive to enable fts3_tokenizer() or negative to leave the setting -** unchanged. -** The second parameter is a pointer to an integer into which -** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled -** following this call. The second parameter may be a NULL pointer, in -** which case the new setting is not reported back. </dd> +** <dd> ^This option is used to enable or disable using the +** [fts3_tokenizer()] function - part of the [FTS3] full-text search engine +** extension - without using bound parameters as the parameters. Doing so +** is disabled by default. There must be two additional arguments. The first +** argument is an integer. If it is passed 0, then using fts3_tokenizer() +** without bound parameters is disabled. If it is passed a positive value, +** then calling fts3_tokenizer without bound parameters is enabled. If it +** is passed a negative value, this setting is not modified - this can be +** used to query for the current setting. The second parameter is a pointer +** to an integer into which is written 0 or 1 to indicate the current value +** of this setting (after it is modified, if applicable). The second +** parameter may be a NULL pointer, in which case the value of the setting +** is not reported back. Refer to [FTS3] documentation for further details. +** </dd> ** ** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]] ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt> @@ -2294,12 +2382,12 @@ struct sqlite3_mem_methods { ** interface independently of the [load_extension()] SQL function. ** The [sqlite3_enable_load_extension()] API enables or disables both the ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()]. -** There should be two additional arguments. +** There must be two additional arguments. ** When the first argument to this interface is 1, then only the C-API is ** enabled and the SQL function remains disabled. If the first argument to ** this interface is 0, then both the C-API and the SQL function are disabled. -** If the first argument is -1, then no changes are made to state of either the -** C-API or the SQL function. +** If the first argument is -1, then no changes are made to the state of either +** the C-API or the SQL function. ** The second parameter is a pointer to an integer into which ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface ** is disabled or enabled following this call. The second parameter may @@ -2308,23 +2396,30 @@ struct sqlite3_mem_methods { ** ** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt> ** <dd> ^This option is used to change the name of the "main" database -** schema. ^The sole argument is a pointer to a constant UTF8 string -** which will become the new schema name in place of "main". ^SQLite -** does not make a copy of the new main schema name string, so the application -** must ensure that the argument passed into this DBCONFIG option is unchanged -** until after the database connection closes. +** schema. This option does not follow the +** [DBCONFIG arguments|usual SQLITE_DBCONFIG argument format]. +** This option takes exactly one additional argument so that the +** [sqlite3_db_config()] call has a total of three parameters. The +** extra argument must be a pointer to a constant UTF8 string which +** will become the new schema name in place of "main". ^SQLite does +** not make a copy of the new main schema name string, so the application +** must ensure that the argument passed into SQLITE_DBCONFIG MAINDBNAME +** is unchanged until after the database connection closes. ** </dd> ** ** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]] ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt> -** <dd> Usually, when a database in wal mode is closed or detached from a -** database handle, SQLite checks if this will mean that there are now no -** connections at all to the database. If so, it performs a checkpoint -** operation before closing the connection. This option may be used to -** override this behavior. The first parameter passed to this operation -** is an integer - positive to disable checkpoints-on-close, or zero (the -** default) to enable them, and negative to leave the setting unchanged. -** The second parameter is a pointer to an integer +** <dd> Usually, when a database in [WAL mode] is closed or detached from a +** database handle, SQLite checks if if there are other connections to the +** same database, and if there are no other database connection (if the +** connection being closed is the last open connection to the database), +** then SQLite performs a [checkpoint] before closing the connection and +** deletes the WAL file. The SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE option can +** be used to override that behavior. The first argument passed to this +** operation (the third parameter to [sqlite3_db_config()]) is an integer +** which is positive to disable checkpoints-on-close, or zero (the default) +** to enable them, and negative to leave the setting unchanged. +** The second argument (the fourth parameter) is a pointer to an integer ** into which is written 0 or 1 to indicate whether checkpoints-on-close ** have been disabled - 0 if they are not disabled, 1 if they are. ** </dd> @@ -2410,7 +2505,7 @@ struct sqlite3_mem_methods { ** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]] ** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt> ** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates -** the legacy behavior of the [ALTER TABLE RENAME] command such it +** the legacy behavior of the [ALTER TABLE RENAME] command such that it ** behaves as it did prior to [version 3.24.0] (2018-06-04). See the ** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for ** additional information. This feature can also be turned on and off @@ -2459,7 +2554,7 @@ struct sqlite3_mem_methods { ** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</dt> ** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates ** the legacy file format flag. When activated, this flag causes all newly -** created database file to have a schema format version number (the 4-byte +** created database files to have a schema format version number (the 4-byte ** integer found at offset 44 into the database header) of 1. This in turn ** means that the resulting database file will be readable and writable by ** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting, @@ -2480,13 +2575,16 @@ struct sqlite3_mem_methods { ** [[SQLITE_DBCONFIG_STMT_SCANSTATUS]] ** <dt>SQLITE_DBCONFIG_STMT_SCANSTATUS</dt> ** <dd>The SQLITE_DBCONFIG_STMT_SCANSTATUS option is only useful in -** SQLITE_ENABLE_STMT_SCANSTATUS builds. In this case, it sets or clears -** a flag that enables collection of the sqlite3_stmt_scanstatus_v2() -** statistics. For statistics to be collected, the flag must be set on -** the database handle both when the SQL statement is prepared and when it -** is stepped. The flag is set (collection of statistics is enabled) -** by default. This option takes two arguments: an integer and a pointer to -** an integer.. The first argument is 1, 0, or -1 to enable, disable, or +** [SQLITE_ENABLE_STMT_SCANSTATUS] builds. In this case, it sets or clears +** a flag that enables collection of run-time performance statistics +** used by [sqlite3_stmt_scanstatus_v2()] and the [nexec and ncycle] +** columns of the [bytecode virtual table]. +** For statistics to be collected, the flag must be set on +** the database handle both when the SQL statement is +** [sqlite3_prepare|prepared] and when it is [sqlite3_step|stepped]. +** The flag is set (collection of statistics is enabled) by default. +** <p>This option takes two arguments: an integer and a pointer to +** an integer. The first argument is 1, 0, or -1 to enable, disable, or ** leave unchanged the statement scanstatus option. If the second argument ** is not NULL, then the value of the statement scanstatus setting after ** processing the first argument is written into the integer that the second @@ -2499,7 +2597,7 @@ struct sqlite3_mem_methods { ** in which tables and indexes are scanned so that the scans start at the end ** and work toward the beginning rather than starting at the beginning and ** working toward the end. Setting SQLITE_DBCONFIG_REVERSE_SCANORDER is the -** same as setting [PRAGMA reverse_unordered_selects]. This option takes +** same as setting [PRAGMA reverse_unordered_selects]. <p>This option takes ** two arguments which are an integer and a pointer to an integer. The first ** argument is 1, 0, or -1 to enable, disable, or leave unchanged the ** reverse scan order flag, respectively. If the second argument is not NULL, @@ -2508,7 +2606,95 @@ struct sqlite3_mem_methods { ** first argument. ** </dd> ** +** [[SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE]] +** <dt>SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE</dt> +** <dd>The SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE option enables or disables +** the ability of the [ATTACH DATABASE] SQL command to create a new database +** file if the database filed named in the ATTACH command does not already +** exist. This ability of ATTACH to create a new database is enabled by +** default. Applications can disable or reenable the ability for ATTACH to +** create new database files using this DBCONFIG option.<p> +** This option takes two arguments which are an integer and a pointer +** to an integer. The first argument is 1, 0, or -1 to enable, disable, or +** leave unchanged the attach-create flag, respectively. If the second +** argument is not NULL, then 0 or 1 is written into the integer that the +** second argument points to depending on if the attach-create flag is set +** after processing the first argument. +** </dd> +** +** [[SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE]] +** <dt>SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE</dt> +** <dd>The SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE option enables or disables the +** ability of the [ATTACH DATABASE] SQL command to open a database for writing. +** This capability is enabled by default. Applications can disable or +** reenable this capability using the current DBCONFIG option. If +** this capability is disabled, the [ATTACH] command will still work, +** but the database will be opened read-only. If this option is disabled, +** then the ability to create a new database using [ATTACH] is also disabled, +** regardless of the value of the [SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE] +** option.<p> +** This option takes two arguments which are an integer and a pointer +** to an integer. The first argument is 1, 0, or -1 to enable, disable, or +** leave unchanged the ability to ATTACH another database for writing, +** respectively. If the second argument is not NULL, then 0 or 1 is written +** into the integer to which the second argument points, depending on whether +** the ability to ATTACH a read/write database is enabled or disabled +** after processing the first argument. +** </dd> +** +** [[SQLITE_DBCONFIG_ENABLE_COMMENTS]] +** <dt>SQLITE_DBCONFIG_ENABLE_COMMENTS</dt> +** <dd>The SQLITE_DBCONFIG_ENABLE_COMMENTS option enables or disables the +** ability to include comments in SQL text. Comments are enabled by default. +** An application can disable or reenable comments in SQL text using this +** DBCONFIG option.<p> +** This option takes two arguments which are an integer and a pointer +** to an integer. The first argument is 1, 0, or -1 to enable, disable, or +** leave unchanged the ability to use comments in SQL text, +** respectively. If the second argument is not NULL, then 0 or 1 is written +** into the integer that the second argument points to depending on if +** comments are allowed in SQL text after processing the first argument. +** </dd> +** +** [[SQLITE_DBCONFIG_FP_DIGITS]] +** <dt>SQLITE_DBCONFIG_FP_DIGITS</dt> +** <dd>The SQLITE_DBCONFIG_FP_DIGITS setting is a small integer that determines +** the number of significant digits that SQLite will attempt to preserve when +** converting floating point numbers (IEEE 754 "doubles") into text. The +** default value 17, as of SQLite version 3.52.0. The value was 15 in all +** prior versions.<p> +** This option takes two arguments which are an integer and a pointer +** to an integer. The first argument is a small integer, between 3 and 23, or +** zero. The FP_DIGITS setting is changed to that small integer, or left +** unaltered if the first argument is zero or out of range. The second argument +** is a pointer to an integer. If the pointer is not NULL, then the value of +** the FP_DIGITS setting, after possibly being modified by the first +** arguments, is written into the integer to which the second argument points. +** </dd> +** ** </dl> +** +** [[DBCONFIG arguments]] <h3>Arguments To SQLITE_DBCONFIG Options</h3> +** +** <p>Most of the SQLITE_DBCONFIG options take two arguments, so that the +** overall call to [sqlite3_db_config()] has a total of four parameters. +** The first argument (the third parameter to sqlite3_db_config()) is +** an integer. +** The second argument is a pointer to an integer. If the first argument is 1, +** then the option becomes enabled. If the first integer argument is 0, +** then the option is disabled. +** If the first argument is -1, then the option setting +** is unchanged. The second argument, the pointer to an integer, may be NULL. +** If the second argument is not NULL, then a value of 0 or 1 is written into +** the integer to which the second argument points, depending on whether the +** setting is disabled or enabled after applying any changes specified by +** the first argument. +** +** <p>While most SQLITE_DBCONFIG options use the argument format +** described in the previous paragraph, the [SQLITE_DBCONFIG_MAINDBNAME], +** [SQLITE_DBCONFIG_LOOKASIDE], and [SQLITE_DBCONFIG_FP_DIGITS] options +** are different. See the documentation of those exceptional options for +** details. */ #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */ #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ @@ -2530,7 +2716,11 @@ struct sqlite3_mem_methods { #define SQLITE_DBCONFIG_TRUSTED_SCHEMA 1017 /* int int* */ #define SQLITE_DBCONFIG_STMT_SCANSTATUS 1018 /* int int* */ #define SQLITE_DBCONFIG_REVERSE_SCANORDER 1019 /* int int* */ -#define SQLITE_DBCONFIG_MAX 1019 /* Largest DBCONFIG */ +#define SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE 1020 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE 1021 /* int int* */ +#define SQLITE_DBCONFIG_ENABLE_COMMENTS 1022 /* int int* */ +#define SQLITE_DBCONFIG_FP_DIGITS 1023 /* int int* */ +#define SQLITE_DBCONFIG_MAX 1023 /* Largest DBCONFIG */ /* ** CAPI3REF: Enable Or Disable Extended Result Codes @@ -2622,10 +2812,14 @@ SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64); ** deleted by the most recently completed INSERT, UPDATE or DELETE ** statement on the database connection specified by the only parameter. ** The two functions are identical except for the type of the return value -** and that if the number of rows modified by the most recent INSERT, UPDATE +** and that if the number of rows modified by the most recent INSERT, UPDATE, ** or DELETE is greater than the maximum value supported by type "int", then ** the return value of sqlite3_changes() is undefined. ^Executing any other ** type of SQL statement does not modify the value returned by these functions. +** For the purposes of this interface, a CREATE TABLE AS SELECT statement +** does not count as an INSERT, UPDATE or DELETE statement and hence the rows +** added to the new table by the CREATE TABLE AS SELECT statement are not +** counted. ** ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], @@ -2766,8 +2960,9 @@ SQLITE_API int sqlite3_is_interrupted(sqlite3*); ** These routines are useful during command-line input to determine if the ** currently entered text seems to form a complete SQL statement or ** if additional input is needed before sending the text into -** SQLite for parsing. ^These routines return 1 if the input string -** appears to be a complete SQL statement. ^A statement is judged to be +** SQLite for parsing. ^The sqlite3_complete(X) and sqlite3_complete16(X) +** routines return 1 if the input string X appears to be a complete SQL +** statement. ^A statement is judged to be ** complete if it ends with a semicolon token and is not a prefix of a ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within ** string literals or quoted identifier names or comments are not @@ -2775,11 +2970,25 @@ SQLITE_API int sqlite3_is_interrupted(sqlite3*); ** embedded) and thus do not count as a statement terminator. ^Whitespace ** and comments that follow the final semicolon are ignored. ** -** ^These routines return 0 if the statement is incomplete. ^If a -** memory allocation fails, then SQLITE_NOMEM is returned. -** -** ^These routines do not parse the SQL statements thus -** will not detect syntactically incorrect SQL. +** ^The sqlite3_complete(X) and sqlite3_complete16(X) routines return 0 +** if the statement is incomplete. ^If a memory allocation fails, then +** SQLITE_NOMEM is returned. +** +** The [sqlite3_incomplete(X)] routine is similar to [sqlite3_complete(X)] +** except that sqlite3_incomplete(X) returns SQLITE_OK if the input X is +** complete, SQLITE_EMPTY if input X consists entirely of whitespace and/or +** comments, SQLITE_MISUSE if X is a NULL pointer, and some other non-zero +** value if X is incomplete. The non-zero return from +** sqlite3_incomplete(X) contains additional information about what is +** needed to complete the input X. See the header comment on the +** implemenation of the sqlite3_incomplete() routine for a full description +** of its non-zero return values. The sqlite3_incomplete(X) interface +** is only available for UTF-8 text. +** +** ^None of these routines do a full parse the SQL statements and thus +** will not detect syntactically incorrect SQL. They only determine if +** input text has properly terminated comments, string literals, and +** quoted identifiers, and if the statement ends with a semicolon. ** ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked @@ -2787,14 +2996,15 @@ SQLITE_API int sqlite3_is_interrupted(sqlite3*); ** then the return value from sqlite3_complete16() will be non-zero ** regardless of whether or not the input SQL is complete.)^ ** -** The input to [sqlite3_complete()] must be a zero-terminated -** UTF-8 string. +** The X input to [sqlite3_complete(X)] and [sqlite3_incomplete(X)] +** must be a zero-terminated UTF-8 string. ** ** The input to [sqlite3_complete16()] must be a zero-terminated ** UTF-16 string in native byte order. */ SQLITE_API int sqlite3_complete(const char *sql); SQLITE_API int sqlite3_complete16(const void *sql); +SQLITE_API sqlite3_int64 sqlite3_incomplete(const char *sql); /* ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors @@ -2880,6 +3090,44 @@ SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*); */ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); +/* +** CAPI3REF: Set the Setlk Timeout +** METHOD: sqlite3 +** +** This routine is only useful in SQLITE_ENABLE_SETLK_TIMEOUT builds. If +** the VFS supports blocking locks, it sets the timeout in ms used by +** eligible locks taken on wal mode databases by the specified database +** handle. In non-SQLITE_ENABLE_SETLK_TIMEOUT builds, or if the VFS does +** not support blocking locks, this function is a no-op. +** +** Passing 0 to this function disables blocking locks altogether. Passing +** -1 to this function requests that the VFS blocks for a long time - +** indefinitely if possible. The results of passing any other negative value +** are undefined. +** +** Internally, each SQLite database handle stores two timeout values - the +** busy-timeout (used for rollback mode databases, or if the VFS does not +** support blocking locks) and the setlk-timeout (used for blocking locks +** on wal-mode databases). The sqlite3_busy_timeout() method sets both +** values, this function sets only the setlk-timeout value. Therefore, +** to configure separate busy-timeout and setlk-timeout values for a single +** database handle, call sqlite3_busy_timeout() followed by this function. +** +** Whenever the number of connections to a wal mode database falls from +** 1 to 0, the last connection takes an exclusive lock on the database, +** then checkpoints and deletes the wal file. While it is doing this, any +** new connection that tries to read from the database fails with an +** SQLITE_BUSY error. Or, if the SQLITE_SETLK_BLOCK_ON_CONNECT flag is +** passed to this API, the new connection blocks until the exclusive lock +** has been released. +*/ +SQLITE_API int sqlite3_setlk_timeout(sqlite3*, int ms, int flags); + +/* +** CAPI3REF: Flags for sqlite3_setlk_timeout() +*/ +#define SQLITE_SETLK_BLOCK_ON_CONNECT 0x01 + /* ** CAPI3REF: Convenience Routines For Running Queries ** METHOD: sqlite3 @@ -2887,7 +3135,7 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); ** This is a legacy interface that is preserved for backwards compatibility. ** Use of this interface is not recommended. ** -** Definition: A <b>result table</b> is memory data structure created by the +** Definition: A <b>result table</b> is a memory data structure created by the ** [sqlite3_get_table()] interface. A result table records the ** complete query results from one or more queries. ** @@ -3030,7 +3278,7 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); ** ^Calling sqlite3_free() with a pointer previously returned ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so ** that it might be reused. ^The sqlite3_free() routine is -** a no-op if is called with a NULL pointer. Passing a NULL pointer +** a no-op if it is called with a NULL pointer. Passing a NULL pointer ** to sqlite3_free() is harmless. After being freed, memory ** should neither be read nor written. Even reading previously freed ** memory might result in a segmentation fault or other severe error. @@ -3048,13 +3296,13 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); ** sqlite3_free(X). ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation ** of at least N bytes in size or NULL if insufficient memory is available. -** ^If M is the size of the prior allocation, then min(N,M) bytes -** of the prior allocation are copied into the beginning of buffer returned +** ^If M is the size of the prior allocation, then min(N,M) bytes of the +** prior allocation are copied into the beginning of the buffer returned ** by sqlite3_realloc(X,N) and the prior allocation is freed. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the ** prior allocation is not freed. ** -** ^The sqlite3_realloc64(X,N) interfaces works the same as +** ^The sqlite3_realloc64(X,N) interface works the same as ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead ** of a 32-bit signed integer. ** @@ -3104,7 +3352,7 @@ SQLITE_API sqlite3_uint64 sqlite3_msize(void*); ** was last reset. ^The values returned by [sqlite3_memory_used()] and ** [sqlite3_memory_highwater()] include any overhead ** added by SQLite in its implementation of [sqlite3_malloc()], -** but not overhead added by the any underlying system library +** but not overhead added by any underlying system library ** routines that [sqlite3_malloc()] may call. ** ** ^The memory high-water mark is reset to the current value of @@ -3169,7 +3417,7 @@ SQLITE_API void sqlite3_randomness(int N, void *P); ** ** ^The first parameter to the authorizer callback is a copy of the third ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter -** to the callback is an integer [SQLITE_COPY | action code] that specifies +** to the callback is an integer [SQLITE_READ | action code] that specifies ** the particular action to be authorized. ^The third through sixth parameters ** to the callback are either NULL pointers or zero-terminated strings ** that contain additional details about the action to be authorized. @@ -3212,21 +3460,33 @@ SQLITE_API void sqlite3_randomness(int N, void *P); ** previous call.)^ ^Disable the authorizer by installing a NULL callback. ** The authorizer is disabled by default. ** -** The authorizer callback must not do anything that will modify +** <h3>Limitations And Caveats</h3><ul> +** +** <li>The authorizer callback must not do anything that will modify ** the database connection that invoked the authorizer callback. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** -** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the +** <li>^When [sqlite3_prepare_v2()] is used to prepare a statement, the ** statement might be re-prepared during [sqlite3_step()] due to a ** schema change. Hence, the application should ensure that the ** correct authorizer callback remains in place during the [sqlite3_step()]. ** -** ^Note that the authorizer callback is invoked only during +** <li>^The authorizer callback is invoked only during ** [sqlite3_prepare()] or its variants. Authorization is not ** performed during statement evaluation in [sqlite3_step()], unless ** as stated in the previous paragraph, sqlite3_step() invokes ** sqlite3_prepare_v2() to reprepare a statement after a schema change. +** +** <li>Authorizer callbacks for the expressions of a +** [generated column] are invoked when the schema is parsed (and specifically +** when the [CREATE TABLE] statement that contains the generated column is +** parsed) not when the generated column is used in a DML statement. +** This is deliberate, as one of the purposes of generated columns +** is to give schema designers the ability to provide gated access +** to privileged columns and/or functions. +** +** </ul> */ SQLITE_API int sqlite3_set_authorizer( sqlite3*, @@ -3267,6 +3527,11 @@ SQLITE_API int sqlite3_set_authorizer( ** is the name of the inner-most trigger or view that is responsible for ** the access attempt or NULL if this access attempt is directly from ** top-level SQL code. +** +** The case of strings in the 3rd through the 6th argument to the +** authorization callback is arbitrary. Authorization callbacks +** implementations should use [sqlite3_stricmp()] or similar when +** doing comparisons against those values. */ /******************************************* 3rd ************ 4th ***********/ #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ @@ -3301,9 +3566,14 @@ SQLITE_API int sqlite3_set_authorizer( #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ #define SQLITE_FUNCTION 31 /* NULL Function Name */ #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ -#define SQLITE_COPY 0 /* No longer used */ #define SQLITE_RECURSIVE 33 /* NULL NULL */ +/* +** Note: The SQLITE_COPY macro (with value 0) used to be one of the +** action codes above. That macro has now been repurposed as a possible +** value to the 3rd argument to sqlite3_result_str(). +*/ + /* ** CAPI3REF: Deprecated Tracing And Profiling Functions ** DEPRECATED @@ -3556,7 +3826,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** there is no harm in trying.) ** ** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt> -** <dd>The database is opened [shared cache] enabled, overriding +** <dd>The database is opened with [shared cache] enabled, overriding ** the default shared cache setting provided by ** [sqlite3_enable_shared_cache()].)^ ** The [use of shared cache mode is discouraged] and hence shared cache @@ -3564,7 +3834,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); ** this option is a no-op. ** ** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt> -** <dd>The database is opened [shared cache] disabled, overriding +** <dd>The database is opened with [shared cache] disabled, overriding ** the default shared cache setting provided by ** [sqlite3_enable_shared_cache()].)^ ** @@ -3810,8 +4080,7 @@ SQLITE_API int sqlite3_open_v2( ** ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a ** 64-bit signed integer and returns that integer, or D if P does not -** exist. If the value of P is something other than an integer, then -** zero is returned. +** exist or if the value of P is something other than an integer. ** ** The sqlite3_uri_key(F,N) returns a pointer to the name (not ** the value) of the N-th query parameter for filename F, or a NULL @@ -3899,7 +4168,7 @@ SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*); ** ** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of ** database filename D with corresponding journal file J and WAL file W and -** with N URI parameters key/values pairs in the array P. The result from +** an array P of N URI Key/Value pairs. The result from ** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that ** is safe to pass to routines like: ** <ul> @@ -3970,6 +4239,7 @@ SQLITE_API void sqlite3_free_filename(sqlite3_filename); ** <li> sqlite3_errmsg() ** <li> sqlite3_errmsg16() ** <li> sqlite3_error_offset() +** <li> sqlite3_db_handle() ** </ul> ** ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language @@ -3982,7 +4252,7 @@ SQLITE_API void sqlite3_free_filename(sqlite3_filename); ** subsequent calls to other SQLite interface functions.)^ ** ** ^The sqlite3_errstr(E) interface returns the English-language text -** that describes the [result code] E, as UTF-8, or NULL if E is not an +** that describes the [result code] E, as UTF-8, or NULL if E is not a ** result code for which a text error message is available. ** ^(Memory to hold the error message string is managed internally ** and must not be freed by the application)^. @@ -3990,7 +4260,7 @@ SQLITE_API void sqlite3_free_filename(sqlite3_filename); ** ^If the most recent error references a specific token in the input ** SQL, the sqlite3_error_offset() interface returns the byte offset ** of the start of that token. ^The byte offset returned by -** sqlite3_error_offset() assumes that the input SQL is UTF8. +** sqlite3_error_offset() assumes that the input SQL is UTF-8. ** ^If the most recent error does not reference a specific token in the input ** SQL, then the sqlite3_error_offset() function returns -1. ** @@ -4015,6 +4285,34 @@ SQLITE_API const void *sqlite3_errmsg16(sqlite3*); SQLITE_API const char *sqlite3_errstr(int); SQLITE_API int sqlite3_error_offset(sqlite3 *db); +/* +** CAPI3REF: Set Error Code And Message +** METHOD: sqlite3 +** +** Set the error code of the database handle passed as the first argument +** to errcode, and the error message to a copy of nul-terminated string +** zErrMsg. If zErrMsg is passed NULL, then the error message is set to +** the default message associated with the supplied error code. Subsequent +** calls to [sqlite3_errcode()] and [sqlite3_errmsg()] and similar will +** return the values set by this routine in place of what was previously +** set by SQLite itself. +** +** This function returns SQLITE_OK if the error code and error message are +** successfully set, SQLITE_NOMEM if an OOM occurs, and SQLITE_MISUSE if +** the database handle is NULL or invalid. +** +** The error code and message set by this routine remains in effect until +** they are changed, either by another call to this routine or until they are +** changed to by SQLite itself to reflect the result of some subsquent +** API call. +** +** This function is intended for use by SQLite extensions or wrappers. The +** idea is that an extension or wrapper can use this routine to set error +** messages and error codes and thus behave more like a core SQLite +** feature from the point of view of an application. +*/ +SQLITE_API int sqlite3_set_errmsg(sqlite3 *db, int errcode, const char *zErrMsg); + /* ** CAPI3REF: Prepared Statement Object ** KEYWORDS: {prepared statement} {prepared statements} @@ -4089,8 +4387,8 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** ** These constants define various performance limits ** that can be lowered at run-time using [sqlite3_limit()]. -** The synopsis of the meanings of the various limits is shown below. -** Additional information is available at [limits | Limits in SQLite]. +** A concise description of these limits follows, and additional information +** is available at [limits | Limits in SQLite]. ** ** <dl> ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt> @@ -4105,7 +4403,12 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** or in an ORDER BY or GROUP BY clause.</dd>)^ ** ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt> -** <dd>The maximum depth of the parse tree on any expression.</dd>)^ +** <dd>The maximum depth of the parse tree on any expression and +** the maximum nesting depth for subqueries and VIEWs</dd>)^ +** +** [[SQLITE_LIMIT_PARSER_DEPTH]] ^(<dt>SQLITE_LIMIT_PARSER_DEPTH</dt> +** <dd>The maximum depth of the LALR(1) parser stack used to analyze +** input SQL statements.</dd>)^ ** ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt> ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^ @@ -4132,11 +4435,20 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** <dd>The maximum index number of any [parameter] in an SQL statement.)^ ** ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt> -** <dd>The maximum depth of recursion for triggers.</dd>)^ +** <dd>The maximum depth of recursion for triggers, and the maximum +** nesting depth for separate triggers.</dd>)^ ** ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt> ** <dd>The maximum number of auxiliary worker threads that a single ** [prepared statement] may start.</dd>)^ +** +** [[SQLITE_LIMIT_SCHEMA]] ^(<dt>SQLITE_LIMIT_SCHEMA</dt> +** <dd>The maximum number of objects (tables, indexes, triggers, and views) +** defined by the database schema.</dd>)^ +** +** [[SQLITE_LIMIT_TRIGGER_STEPS]] ^(<dt>SQLITE_LIMIT_TRIGGER_STEPS</dt> +** <dd>The maximum number of SQL statements that can be contained within +** a single trigger.</dd>)^ ** </dl> */ #define SQLITE_LIMIT_LENGTH 0 @@ -4151,11 +4463,14 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); #define SQLITE_LIMIT_VARIABLE_NUMBER 9 #define SQLITE_LIMIT_TRIGGER_DEPTH 10 #define SQLITE_LIMIT_WORKER_THREADS 11 +#define SQLITE_LIMIT_PARSER_DEPTH 12 +#define SQLITE_LIMIT_SCHEMA 13 +#define SQLITE_LIMIT_TRIGGER_STEPS 14 /* ** CAPI3REF: Prepare Flags ** -** These constants define various flags that can be passed into +** These constants define various flags that can be passed into the ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and ** [sqlite3_prepare16_v3()] interfaces. ** @@ -4185,11 +4500,39 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler ** to return an error (error code SQLITE_ERROR) if the statement uses ** any virtual tables. +** +** [[SQLITE_PREPARE_DONT_LOG]] <dt>SQLITE_PREPARE_DONT_LOG</dt> +** <dd>The SQLITE_PREPARE_DONT_LOG flag prevents SQL compiler +** errors from being sent to the error log defined by +** [SQLITE_CONFIG_LOG]. This can be used, for example, to do test +** compiles to see if some SQL syntax is well-formed, without generating +** messages on the global error log when it is not. If the test compile +** fails, the sqlite3_prepare_v3() call returns the same error indications +** with or without this flag; it just omits the call to [sqlite3_log()] that +** logs the error. +** +** [[SQLITE_PREPARE_FROM_DDL]] <dt>SQLITE_PREPARE_FROM_DDL</dt> +** <dd>The SQLITE_PREPARE_FROM_DDL flag causes the SQL compiler to enforce +** security constraints that would otherwise only be enforced when parsing +** the database schema. In other words, the SQLITE_PREPARE_FROM_DDL flag +** causes the SQL compiler to treat the SQL statement being prepared as if +** it had come from an attacker. When SQLITE_PREPARE_FROM_DDL is used and +** [SQLITE_DBCONFIG_TRUSTED_SCHEMA] is off, SQL functions may only be called +** if they are tagged with [SQLITE_INNOCUOUS] and virtual tables may only +** be used if they are tagged with [SQLITE_VTAB_INNOCUOUS]. Best practice +** is to use the SQLITE_PREPARE_FROM_DDL option when preparing any SQL that +** is derived from parts of the database schema. In particular, virtual +** table implementations that run SQL statements that are derived from +** arguments to their CREATE VIRTUAL TABLE statement should always use +** [sqlite3_prepare_v3()] and set the SQLITE_PREPARE_FROM_DDL flag to +** prevent bypass of the [SQLITE_DBCONFIG_TRUSTED_SCHEMA] security checks. ** </dl> */ #define SQLITE_PREPARE_PERSISTENT 0x01 #define SQLITE_PREPARE_NORMALIZE 0x02 #define SQLITE_PREPARE_NO_VTAB 0x04 +#define SQLITE_PREPARE_DONT_LOG 0x10 +#define SQLITE_PREPARE_FROM_DDL 0x20 /* ** CAPI3REF: Compiling An SQL Statement @@ -4203,8 +4546,9 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** ** The preferred routine to use is [sqlite3_prepare_v2()]. The ** [sqlite3_prepare()] interface is legacy and should be avoided. -** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used -** for special purposes. +** [sqlite3_prepare_v3()] has an extra +** [SQLITE_PREPARE_FROM_DDL|"prepFlags" option] that is sometimes +** needed for special purpose or to pass along security restrictions. ** ** The use of the UTF-8 interfaces is preferred, as SQLite currently ** does all parsing using UTF-8. The UTF-16 interfaces are provided @@ -4231,8 +4575,10 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); ** there is a small performance advantage to passing an nByte parameter that ** is the number of bytes in the input string <i>including</i> ** the nul-terminator. -** Note that nByte measure the length of the input in bytes, not +** Note that nByte measures the length of the input in bytes, not ** characters, even for the UTF-16 interfaces. +** For the sqlite3_prepare16() and sqlite3_prepare16_v2() interfaces, +** the nByte value must be even or undefined behavior can result. ** ** ^If pzTail is not NULL then *pzTail is made to point to the first byte ** past the end of the first SQL statement in zSql. These routines only @@ -4365,7 +4711,7 @@ SQLITE_API int sqlite3_prepare16_v3( ** ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory ** is available to hold the result, or if the result would exceed the -** the maximum string length determined by the [SQLITE_LIMIT_LENGTH]. +** maximum string length determined by the [SQLITE_LIMIT_LENGTH]. ** ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time @@ -4553,7 +4899,7 @@ typedef struct sqlite3_value sqlite3_value; ** ** The context in which an SQL function executes is stored in an ** sqlite3_context object. ^A pointer to an sqlite3_context object -** is always first parameter to [application-defined SQL functions]. +** is always the first parameter to [application-defined SQL functions]. ** The application-defined SQL function implementation will pass this ** pointer through into calls to [sqlite3_result_int | sqlite3_result()], ** [sqlite3_aggregate_context()], [sqlite3_user_data()], @@ -4569,7 +4915,7 @@ typedef struct sqlite3_context sqlite3_context; ** METHOD: sqlite3_stmt ** ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, -** literals may be replaced by a [parameter] that matches one of following +** literals may be replaced by a [parameter] that matches one of the following ** templates: ** ** <ul> @@ -4609,12 +4955,12 @@ typedef struct sqlite3_context sqlite3_context; ** it should be a pointer to well-formed UTF16 text. ** ^If the third parameter to sqlite3_bind_text64() is not NULL, then ** it should be a pointer to a well-formed unicode string that is -** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16 -** otherwise. +** either UTF8 if the sixth parameter is SQLITE_UTF8 or SQLITE_UTF8_ZT, +** or UTF16 otherwise. ** ** [[byte-order determination rules]] ^The byte-order of ** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF) -** found in first character, which is removed, or in the absence of a BOM +** found in the first character, which is removed, or in the absence of a BOM ** the byte order is the native byte order of the host ** machine for sqlite3_bind_text16() or the byte order specified in ** the 6th parameter for sqlite3_bind_text64().)^ @@ -4634,7 +4980,7 @@ typedef struct sqlite3_context sqlite3_context; ** or sqlite3_bind_text16() or sqlite3_bind_text64() then ** that parameter must be the byte offset ** where the NUL terminator would occur assuming the string were NUL -** terminated. If any NUL characters occurs at byte offsets less than +** terminated. If any NUL characters occur at byte offsets less than ** the value of the fourth parameter then the resulting string value will ** contain embedded NULs. The result of expressions involving strings ** with embedded NULs is undefined. @@ -4656,10 +5002,15 @@ typedef struct sqlite3_context sqlite3_context; ** object and pointer to it must remain valid until then. ^SQLite will then ** manage the lifetime of its private copy. ** -** ^The sixth argument to sqlite3_bind_text64() must be one of -** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE] -** to specify the encoding of the text in the third parameter. If -** the sixth argument to sqlite3_bind_text64() is not one of the +** ^The sixth argument (the E argument) +** to sqlite3_bind_text64(S,K,Z,N,D,E) must be one of +** [SQLITE_UTF8], [SQLITE_UTF8_ZT], [SQLITE_UTF16], [SQLITE_UTF16BE], +** or [SQLITE_UTF16LE] to specify the encoding of the text in the +** third parameter, Z. The special value [SQLITE_UTF8_ZT] means that the +** string argument is both UTF-8 encoded and is zero-terminated. In other +** words, SQLITE_UTF8_ZT means that the Z array is allocated to hold at +** least N+1 bytes and that the Z&#91;N&#93; byte is zero. If +** the E argument to sqlite3_bind_text64(S,K,Z,N,D,E) is not one of the ** allowed values shown above, or if the text encoding is different ** from the encoding specified by the sixth parameter, then the behavior ** is undefined. @@ -4677,9 +5028,11 @@ typedef struct sqlite3_context sqlite3_context; ** associated with the pointer P of type T. ^D is either a NULL pointer or ** a pointer to a destructor function for P. ^SQLite will invoke the ** destructor D with a single argument of P when it is finished using -** P. The T parameter should be a static string, preferably a string -** literal. The sqlite3_bind_pointer() routine is part of the -** [pointer passing interface] added for SQLite 3.20.0. +** P, even if the call to sqlite3_bind_pointer() fails. Due to a +** historical design quirk, results are undefined if D is +** SQLITE_TRANSIENT. The T parameter should be a static string, +** preferably a string literal. The sqlite3_bind_pointer() routine is +** part of the [pointer passing interface] added for SQLite 3.20.0. ** ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer ** for the [prepared statement] or with a prepared statement for which @@ -4846,7 +5199,7 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); ** METHOD: sqlite3_stmt ** ** ^These routines provide a means to determine the database, table, and -** table column that is the origin of a particular result column in +** table column that is the origin of a particular result column in a ** [SELECT] statement. ** ^The name of the database or table or column can be returned as ** either a UTF-8 or UTF-16 string. ^The _database_ routines return @@ -4972,7 +5325,7 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); ** [prepared statement]. ^In the "v2" interface, ** the more specific error code is returned directly by sqlite3_step(). ** -** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** [SQLITE_MISUSE] means that this routine was called inappropriately. ** Perhaps it was called on a [prepared statement] that has ** already been [sqlite3_finalize | finalized] or on one that had ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could @@ -4984,7 +5337,7 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); ** other than [SQLITE_ROW] before any subsequent invocation of ** sqlite3_step(). Failure to reset the prepared statement using ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from -** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1], +** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1]), ** sqlite3_step() began ** calling [sqlite3_reset()] automatically in this circumstance rather ** than returning [SQLITE_MISUSE]. This is not considered a compatibility @@ -5290,7 +5643,7 @@ SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); ** ** ^The sqlite3_finalize() function is called to delete a [prepared statement]. ** ^If the most recent evaluation of the statement encountered no errors -** or if the statement is never been evaluated, then sqlite3_finalize() returns +** or if the statement has never been evaluated, then sqlite3_finalize() returns ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then ** sqlite3_finalize(S) returns the appropriate [error code] or ** [extended error code]. @@ -5415,8 +5768,8 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** ** For best security, the [SQLITE_DIRECTONLY] flag is recommended for ** all application-defined SQL functions that do not need to be -** used inside of triggers, view, CHECK constraints, or other elements of -** the database schema. This flags is especially recommended for SQL +** used inside of triggers, views, CHECK constraints, or other elements of +** the database schema. This flag is especially recommended for SQL ** functions that have side effects or reveal internal application state. ** Without this flag, an attacker might be able to modify the schema of ** a database file to include invocations of the function with parameters @@ -5447,7 +5800,7 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** [user-defined window functions|available here]. ** ** ^(If the final parameter to sqlite3_create_function_v2() or -** sqlite3_create_window_function() is not NULL, then it is destructor for +** sqlite3_create_window_function() is not NULL, then it is the destructor for ** the application data pointer. The destructor is invoked when the function ** is deleted, either by being overloaded or when the database connection ** closes.)^ ^The destructor is also invoked if the call to @@ -5522,8 +5875,54 @@ SQLITE_API int sqlite3_create_window_function( /* ** CAPI3REF: Text Encodings ** -** These constant define integer codes that represent the various +** These constants define integer codes that represent the various ** text encodings supported by SQLite. +** +** <dl> +** [[SQLITE_UTF8]] <dt>SQLITE_UTF8</dt><dd>Text is encoding as UTF-8</dd> +** +** [[SQLITE_UTF16LE]] <dt>SQLITE_UTF16LE</dt><dd>Text is encoding as UTF-16 +** with each code point being expressed "little endian" - the least significant +** byte first. This is the usual encoding, for example on Windows.</dd> +** +** [[SQLITE_UTF16BE]] <dt>SQLITE_UTF16BE</dt><dd>Text is encoding as UTF-16 +** with each code point being expressed "big endian" - the most significant +** byte first. This encoding is less common, but is still sometimes seen, +** specially on older systems. +** +** [[SQLITE_UTF16]] <dt>SQLITE_UTF16</dt><dd>Text is encoding as UTF-16 +** with each code point being expressed either little endian or as big +** endian, according to the native endianness of the host computer. +** +** [[SQLITE_ANY]] <dt>SQLITE_ANY</dt><dd>This encoding value may only be used +** to declare the preferred text for [application-defined SQL functions] +** created using [sqlite3_create_function()] and similar. If the preferred +** encoding (the 4th parameter to sqlite3_create_function() - the eTextRep +** parameter) is SQLITE_ANY, that indicates that the function does not have +** a preference regarding the text encoding of its parameters and can take +** any text encoding that the SQLite core find convenient to supply. This +** option is deprecated. Please do not use it in new applications. +** +** [[SQLITE_UTF16_ALIGNED]] <dt>SQLITE_UTF16_ALIGNED</dt><dd>This encoding +** value may be used as the 3rd parameter (the eTextRep parameter) to +** [sqlite3_create_collation()] and similar. This encoding value means +** that the application-defined collating sequence created expects its +** input strings to be in UTF16 in native byte order, and that the start +** of the strings must be aligned to a 2-byte boundary. +** +** [[SQLITE_UTF8_ZT]] <dt>SQLITE_UTF8_ZT</dt><dd>This option can only be +** used to specify the text encoding to strings input to +** [sqlite3_result_text64()] and [sqlite3_bind_text64()]. +** The SQLITE_UTF8_ZT encoding means that the input string (call it "z") +** is UTF-8 encoded and that it is zero-terminated. If the length parameter +** (call it "n") is non-negative, this encoding option means that the caller +** guarantees that z array contains at least n+1 bytes and that the z&#91;n&#93; +** byte has a value of zero. +** This option gives the same output as SQLITE_UTF8, but can be more efficient +** by avoiding the need to make a copy of the input string, in some cases. +** However, if z is allocated to hold fewer than n+1 bytes or if the +** z&#91;n&#93; byte is not zero, undefined behavior may result. +** </dl> */ #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */ #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */ @@ -5531,6 +5930,7 @@ SQLITE_API int sqlite3_create_window_function( #define SQLITE_UTF16 4 /* Use native byte order */ #define SQLITE_ANY 5 /* Deprecated */ #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ +#define SQLITE_UTF8_ZT 16 /* Zero-terminated UTF8 */ /* ** CAPI3REF: Function Flags @@ -5614,7 +6014,7 @@ SQLITE_API int sqlite3_create_window_function( ** result. ** Every function that invokes [sqlite3_result_subtype()] should have this ** property. If it does not, then the call to [sqlite3_result_subtype()] -** might become a no-op if the function is used as term in an +** might become a no-op if the function is used as a term in an ** [expression index]. On the other hand, SQL functions that never invoke ** [sqlite3_result_subtype()] should avoid setting this property, as the ** purpose of this property is to disable certain optimizations that are @@ -5741,7 +6141,7 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6 ** sqlite3_value_nochange(X) interface returns true if and only if ** the column corresponding to X is unchanged by the UPDATE operation ** that the xUpdate method call was invoked to implement and if -** and the prior [xColumn] method call that was invoked to extracted +** the prior [xColumn] method call that was invoked to extract ** the value for that column returned without setting a result (probably ** because it queried [sqlite3_vtab_nochange()] and found that the column ** was unchanging). ^Within an [xUpdate] method, any value for which @@ -5765,26 +6165,22 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6 ** the SQL function that supplied the [sqlite3_value*] parameters. ** ** As long as the input parameter is correct, these routines can only -** fail if an out-of-memory error occurs during a format conversion. -** Only the following subset of interfaces are subject to out-of-memory -** errors: -** -** <ul> -** <li> sqlite3_value_blob() -** <li> sqlite3_value_text() -** <li> sqlite3_value_text16() -** <li> sqlite3_value_text16le() -** <li> sqlite3_value_text16be() -** <li> sqlite3_value_bytes() -** <li> sqlite3_value_bytes16() -** </ul> -** +** fail if an out-of-memory error occurs while trying to do a +** UTF8&rarr;UTF16 or UTF16&rarr;UTF8 conversion. ** If an out-of-memory error occurs, then the return value from these ** routines is the same as if the column had contained an SQL NULL value. -** Valid SQL NULL returns can be distinguished from out-of-memory errors -** by invoking the [sqlite3_errcode()] immediately after the suspect +** If the input sqlite3_value was not obtained from [sqlite3_value_dup()], +** then valid SQL NULL returns can also be distinguished from +** out-of-memory errors after extracting the value +** by invoking the [sqlite3_errcode()] immediately after the suspicious ** return value is obtained and before any ** other SQLite interface is called on the same [database connection]. +** If the input sqlite3_value was obtained from sqlite3_value_dup() then +** it is disconnected from the database connection and so sqlite3_errcode() +** will not work. +** In that case, the only way to distinguish an out-of-memory +** condition from a true SQL NULL is to invoke sqlite3_value_type() on the +** input to see if it is NULL prior to trying to extract the value. */ SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); SQLITE_API double sqlite3_value_double(sqlite3_value*); @@ -5811,7 +6207,8 @@ SQLITE_API int sqlite3_value_frombind(sqlite3_value*); ** of the value X, assuming that X has type TEXT.)^ If sqlite3_value_type(X) ** returns something other than SQLITE_TEXT, then the return value from ** sqlite3_value_encoding(X) is meaningless. ^Calls to -** [sqlite3_value_text(X)], [sqlite3_value_text16(X)], [sqlite3_value_text16be(X)], +** [sqlite3_value_text(X)], [sqlite3_value_text16(X)], +** [sqlite3_value_text16be(X)], ** [sqlite3_value_text16le(X)], [sqlite3_value_bytes(X)], or ** [sqlite3_value_bytes16(X)] might change the encoding of the value X and ** thus change the return from subsequent calls to sqlite3_value_encoding(X). @@ -5847,7 +6244,7 @@ SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*); ** METHOD: sqlite3_value ** ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value] -** object D and returns a pointer to that copy. ^The [sqlite3_value] returned +** object V and returns a pointer to that copy. ^The [sqlite3_value] returned ** is a [protected sqlite3_value] object even if the input is not. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a ** memory allocation fails. ^If V is a [pointer value], then the result @@ -5885,7 +6282,7 @@ SQLITE_API void sqlite3_value_free(sqlite3_value*); ** allocation error occurs. ** ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is -** determined by the N parameter on first successful call. Changing the +** determined by the N parameter on the first successful call. Changing the ** value of N in any subsequent call to sqlite3_aggregate_context() within ** the same aggregate function instance will not resize the memory ** allocation.)^ Within the xFinal callback, it is customary to set @@ -5942,17 +6339,17 @@ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); ** query execution, under some circumstances the associated auxiliary data ** might be preserved. An example of where this might be useful is in a ** regular-expression matching function. The compiled version of the regular -** expression can be stored as auxiliary data associated with the pattern string. -** Then as long as the pattern string remains the same, +** expression can be stored as auxiliary data associated with the pattern +** string. Then as long as the pattern string remains the same, ** the compiled regular expression can be reused on multiple ** invocations of the same function. ** -** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the auxiliary data -** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument -** value to the application-defined function. ^N is zero for the left-most -** function argument. ^If there is no auxiliary data -** associated with the function argument, the sqlite3_get_auxdata(C,N) interface -** returns a NULL pointer. +** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the auxiliary +** data associated by the sqlite3_set_auxdata(C,N,P,X) function with the +** Nth argument value to the application-defined function. ^N is zero +** for the left-most function argument. ^If there is no auxiliary data +** associated with the function argument, the sqlite3_get_auxdata(C,N) +** interface returns a NULL pointer. ** ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as auxiliary data for the ** N-th argument of the application-defined function. ^Subsequent @@ -6014,6 +6411,7 @@ SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(voi ** or a NULL pointer if there were no prior calls to ** sqlite3_set_clientdata() with the same values of D and N. ** Names are compared using strcmp() and are thus case sensitive. +** It returns 0 on success and SQLITE_NOMEM on allocation failure. ** ** If P and X are both non-NULL, then the destructor X is invoked with ** argument P on the first of the following occurrences: @@ -6035,10 +6433,14 @@ SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(voi ** ** There is no limit (other than available memory) on the number of different ** client data pointers (with different names) that can be attached to a -** single database connection. However, the implementation is optimized -** for the case of having only one or two different client data names. -** Applications and wrapper libraries are discouraged from using more than -** one client data name each. +** single database connection. However, the current implementation stores +** the content on a linked list. Insert and retrieval performance will +** be proportional to the number of entries. The design use case, and +** the use case for which the implementation is optimized, is +** that an application will store only small number of client data names, +** typically just one or two. This interface is not intended to be a +** generalized key/value store for thousands or millions of keys. It +** will work for that, but performance might be disappointing. ** ** There is no way to enumerate the client data pointers ** associated with a database connection. The N parameter can be thought @@ -6047,7 +6449,7 @@ SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(voi ** ** Security Warning: These interfaces should not be exposed in scripting ** languages or in other circumstances where it might be possible for an -** an attacker to invoke them. Any agent that can invoke these interfaces +** attacker to invoke them. Any agent that can invoke these interfaces ** can probably also take control of the process. ** ** Database connection client data is only available for SQLite @@ -6096,7 +6498,11 @@ typedef void (*sqlite3_destructor_type)(void*); ** ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N) ** interfaces set the result of the application-defined function to be -** a BLOB containing all zero bytes and N bytes in size. +** a BLOB containing all zero bytes and N bytes in size. The +** zeroblob64(C,N) interface returns a [result code], which is normally +** [SQLITE_OK] but might be some other value if the requested operation +** could not be complete, for example if insufficient memory is available +** or if the value of N is out of range. ** ** ^The sqlite3_result_double() interface sets the result from ** an application-defined function to be a floating point value specified @@ -6146,10 +6552,14 @@ typedef void (*sqlite3_destructor_type)(void*); ** set the return value of the application-defined function to be ** a text string which is represented as UTF-8, UTF-16 native byte order, ** UTF-16 little endian, or UTF-16 big endian, respectively. -** ^The sqlite3_result_text64() interface sets the return value of an +** ^The sqlite3_result_text64(C,Z,N,D,E) interface sets the return value of an ** application-defined function to be a text string in an encoding -** specified by the fifth (and last) parameter, which must be one -** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]. +** specified the E parameter, which must be one +** of [SQLITE_UTF8], [SQLITE_UTF8_ZT], [SQLITE_UTF16], [SQLITE_UTF16BE], +** or [SQLITE_UTF16LE]. ^The special value [SQLITE_UTF8_ZT] means that +** the result text is both UTF-8 and zero-terminated. In other words, +** SQLITE_UTF8_ZT means that the Z array holds at least N+1 bytes and that +** the Z&#91;N&#93; is zero. ** ^SQLite takes the text result from the application from ** the 2nd parameter of the sqlite3_result_text* interfaces. ** ^If the 3rd parameter to any of the sqlite3_result_text* interfaces @@ -6161,7 +6571,7 @@ typedef void (*sqlite3_destructor_type)(void*); ** pointed to by the 2nd parameter are taken as the application-defined ** function result. If the 3rd parameter is non-negative, then it ** must be the byte offset into the string where the NUL terminator would -** appear if the string where NUL terminated. If any NUL characters occur +** appear if the string were NUL terminated. If any NUL characters occur ** in the string at a byte offset that is less than the value of the 3rd ** parameter, then the resulting string will contain embedded NULs and the ** result of expressions operating on strings with embedded NULs is undefined. @@ -6219,7 +6629,7 @@ typedef void (*sqlite3_destructor_type)(void*); ** string and preferably a string literal. The sqlite3_result_pointer() ** routine is part of the [pointer passing interface] added for SQLite 3.20.0. ** -** If these routines are called from within the different thread +** If these routines are called from within a different thread ** than the one containing the application-defined function that received ** the [sqlite3_context] pointer, the results are undefined. */ @@ -6236,7 +6646,7 @@ SQLITE_API void sqlite3_result_int(sqlite3_context*, int); SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); SQLITE_API void sqlite3_result_null(sqlite3_context*); SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64, +SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char *z, sqlite3_uint64 n, void(*)(void*), unsigned char encoding); SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); @@ -6625,7 +7035,7 @@ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); ** METHOD: sqlite3 ** ** ^The sqlite3_db_name(D,N) interface returns a pointer to the schema name -** for the N-th database on database connection D, or a NULL pointer of N is +** for the N-th database on database connection D, or a NULL pointer if N is ** out of range. An N value of 0 means the main database file. An N of 1 is ** the "temp" schema. Larger values of N correspond to various ATTACH-ed ** databases. @@ -6720,7 +7130,7 @@ SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema); ** <dd>The SQLITE_TXN_READ state means that the database is currently ** in a read transaction. Content has been read from the database file ** but nothing in the database file has changed. The transaction state -** will advanced to SQLITE_TXN_WRITE if any changes occur and there are +** will be advanced to SQLITE_TXN_WRITE if any changes occur and there are ** no other conflicting concurrent write transactions. The transaction ** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or ** [COMMIT].</dd> @@ -6729,7 +7139,7 @@ SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema); ** <dd>The SQLITE_TXN_WRITE state means that the database is currently ** in a write transaction. Content has been written to the database file ** but has not yet committed. The transaction state will change to -** to SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd> +** SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd> */ #define SQLITE_TXN_NONE 0 #define SQLITE_TXN_READ 1 @@ -6880,6 +7290,8 @@ SQLITE_API int sqlite3_autovacuum_pages( ** ** ^The second argument is a pointer to the function to invoke when a ** row is updated, inserted or deleted in a rowid table. +** ^The update hook is disabled by invoking sqlite3_update_hook() +** with a NULL pointer as the second parameter. ** ^The first argument to the callback is a copy of the third argument ** to sqlite3_update_hook(). ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], @@ -7008,7 +7420,7 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*); ** CAPI3REF: Impose A Limit On Heap Size ** ** These interfaces impose limits on the amount of heap memory that will be -** by all database connections within a single process. +** used by all database connections within a single process. ** ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the ** soft limit on the amount of heap memory that may be allocated by SQLite. @@ -7066,7 +7478,7 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*); ** </ul>)^ ** ** The circumstances under which SQLite will enforce the heap limits may -** changes in future releases of SQLite. +** change in future releases of SQLite. */ SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N); @@ -7173,7 +7585,7 @@ SQLITE_API int sqlite3_table_column_metadata( ** ^The sqlite3_load_extension() interface attempts to load an ** [SQLite extension] library contained in the file zFile. If ** the file cannot be loaded directly, attempts are made to load -** with various operating-system specific extensions added. +** with various operating-system specific filename extensions added. ** So for example, if "samplelib" cannot be loaded, then names like ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might ** be tried also. @@ -7181,10 +7593,10 @@ SQLITE_API int sqlite3_table_column_metadata( ** ^The entry point is zProc. ** ^(zProc may be 0, in which case SQLite will try to come up with an ** entry point name on its own. It first tries "sqlite3_extension_init". -** If that does not work, it constructs a name "sqlite3_X_init" where the -** X is consists of the lower-case equivalent of all ASCII alphabetic -** characters in the filename from the last "/" to the first following -** "." and omitting any initial "lib".)^ +** If that does not work, it tries names of the form "sqlite3_X_init" +** where X consists of the lower-case equivalent of all ASCII alphabetic +** characters or all ASCII alphanumeric characters in the filename from +** the last "/" to the first following "." and omitting any initial "lib".)^ ** ^The sqlite3_load_extension() interface returns ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. ** ^If an error occurs and pzErrMsg is not 0, then the @@ -7253,12 +7665,12 @@ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); ** ^(Even though the function prototype shows that xEntryPoint() takes ** no arguments and returns void, SQLite invokes xEntryPoint() with three ** arguments and expects an integer result as if the signature of the -** entry point where as follows: +** entry point were as follows: ** ** <blockquote><pre> ** &nbsp; int xEntryPoint( ** &nbsp; sqlite3 *db, -** &nbsp; const char **pzErrMsg, +** &nbsp; char **pzErrMsg, ** &nbsp; const struct sqlite3_api_routines *pThunk ** &nbsp; ); ** </pre></blockquote>)^ @@ -7417,7 +7829,7 @@ struct sqlite3_module { ** virtual table and might not be checked again by the byte code.)^ ^(The ** aConstraintUsage[].omit flag is an optimization hint. When the omit flag ** is left in its default setting of false, the constraint will always be -** checked separately in byte code. If the omit flag is change to true, then +** checked separately in byte code. If the omit flag is changed to true, then ** the constraint may or may not be checked in byte code. In other words, ** when the omit flag is true there is no guarantee that the constraint will ** not be checked again using byte code.)^ @@ -7443,7 +7855,7 @@ struct sqlite3_module { ** The xBestIndex method may optionally populate the idxFlags field with a ** mask of SQLITE_INDEX_SCAN_* flags. One such flag is ** [SQLITE_INDEX_SCAN_HEX], which if set causes the [EXPLAIN QUERY PLAN] -** output to show the idxNum has hex instead of as decimal. Another flag is +** output to show the idxNum as hex instead of as decimal. Another flag is ** SQLITE_INDEX_SCAN_UNIQUE, which if set indicates that the query plan will ** return at most one row. ** @@ -7584,7 +7996,7 @@ struct sqlite3_index_info { ** the implementation of the [virtual table module]. ^The fourth ** parameter is an arbitrary client data pointer that is passed through ** into the [xCreate] and [xConnect] methods of the virtual table module -** when a new virtual table is be being created or reinitialized. +** when a new virtual table is being created or reinitialized. ** ** ^The sqlite3_create_module_v2() interface has a fifth parameter which ** is a pointer to a destructor for the pClientData. ^SQLite will @@ -7749,7 +8161,7 @@ typedef struct sqlite3_blob sqlite3_blob; ** in *ppBlob. Otherwise an [error code] is returned and, unless the error ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided ** the API is not misused, it is always safe to call [sqlite3_blob_close()] -** on *ppBlob after this function it returns. +** on *ppBlob after this function returns. ** ** This function fails with SQLITE_ERROR if any of the following are true: ** <ul> @@ -7869,7 +8281,7 @@ SQLITE_API int sqlite3_blob_close(sqlite3_blob *); ** ** ^Returns the size in bytes of the BLOB accessible via the ** successfully opened [BLOB handle] in its only argument. ^The -** incremental blob I/O routines can only read or overwriting existing +** incremental blob I/O routines can only read or overwrite existing ** blob content; they cannot change the size of a blob. ** ** This routine only works on a [BLOB handle] which has been created @@ -8008,18 +8420,11 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix ** and Windows. ** -** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor -** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex -** implementation is included with the library. In this case the -** application must supply a custom mutex implementation using the -** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function -** before calling sqlite3_initialize() or any other public sqlite3_ -** function that calls sqlite3_initialize(). ** ** ^The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc() ** routine returns NULL if it is unable to allocate the requested -** mutex. The argument to sqlite3_mutex_alloc() must one of these +** mutex. The argument to sqlite3_mutex_alloc() must be one of these ** integer constants: ** ** <ul> @@ -8252,7 +8657,7 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); ** CAPI3REF: Retrieve the mutex for a database connection ** METHOD: sqlite3 ** -** ^This interface returns a pointer the [sqlite3_mutex] object that +** ^This interface returns a pointer to the [sqlite3_mutex] object that ** serializes access to the [database connection] given in the argument ** when the [threading mode] is Serialized. ** ^If the [threading mode] is Single-thread or Multi-thread then this @@ -8369,13 +8774,14 @@ SQLITE_API int sqlite3_test_control(int op, ...); #define SQLITE_TESTCTRL_TUNE 32 #define SQLITE_TESTCTRL_LOGEST 33 #define SQLITE_TESTCTRL_USELONGDOUBLE 34 /* NOT USED */ +#define SQLITE_TESTCTRL_ATOF 34 #define SQLITE_TESTCTRL_LAST 34 /* Largest TESTCTRL */ /* ** CAPI3REF: SQL Keyword Checking ** ** These routines provide access to the set of SQL language keywords -** recognized by SQLite. Applications can uses these routines to determine +** recognized by SQLite. Applications can use these routines to determine ** whether or not a specific identifier needs to be escaped (for example, ** by enclosing in double-quotes) so as not to confuse the parser. ** @@ -8434,8 +8840,8 @@ SQLITE_API int sqlite3_keyword_check(const char*,int); ** <li> ^The sqlite3_str object is created using [sqlite3_str_new()]. ** <li> ^Text is appended to the sqlite3_str object using various ** methods, such as [sqlite3_str_appendf()]. -** <li> ^The sqlite3_str object is destroyed and the string it created -** is returned using the [sqlite3_str_finish()] interface. +** <li> The sqlite3_str object is destroyed and the string it created +** is returned using [sqlite3_str_finish()] or [sqlite3_result_str()]. ** </ol> */ typedef struct sqlite3_str sqlite3_str; @@ -8477,17 +8883,56 @@ SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*); ** pass the returned value to [sqlite3_free()] to avoid a memory leak. ** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any ** errors were encountered during construction of the string. ^The -** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the +** [sqlite3_str_finish(X)] interface might also return a NULL pointer if the ** string in [sqlite3_str] object X is zero bytes long. +** +** ^The [sqlite3_str_free(X)] interface destroys both the sqlite3_str object +** X and the string content it contains. Calling sqlite3_str_free(X) is +** the equivalent of calling [sqlite3_free](sqlite3_str_finish(X)). */ SQLITE_API char *sqlite3_str_finish(sqlite3_str*); +SQLITE_API void sqlite3_str_free(sqlite3_str*); + +/* +** CAPI3REF: Return A Dynamic String From an SQL Function +** +** The [sqlite3_result_str(C,S,F)] interface causes the +** [sqlite3_str|dynamic string] S to become the return value for the +** application-defined function or virtual table that uses +** [sqlite3_context] C. The F flag can be one of [SQLITE_COPY] +** or [SQLITE_XFER] or [SQLITE_FINISH]. +** +** If the dynamic string is invalid or incomplete due to an out-of-memory +** or string-too-large error, then this routine transfers that error +** over to the SQL function. +** +** If the F argument is SQLITE_COPY, then a copy of the dynamic string +** content is made and the dynamic string object is unchanged. +** If the F argument is SQLITE_XFER, then ownership of the content +** in the dynamic is transferred to the SQL function (via a pointer copy +** rather than a string copy) and the dynamic string is reset to an +** empty string. The SQLITE_FINISH value for F works like SQLITE_RESET +** except that it also invokes the [sqlite3_str_free(S)] destructor +** on the dynamic string object. +*/ +SQLITE_API void sqlite3_result_str(sqlite3_context*, sqlite3_str*, int); + +/* +** CAPI3REF: Control Flags For sqlite3_result_str() +** +** The following integers can be used as the third "F" argument +** to [sqlite3_result_str(C,S,F)]. +*/ +#define SQLITE_COPY 0 /* Results copied. Dynamic string unchanged */ +#define SQLITE_XFER 1 /* Results transfered. Dynamic string reset */ +#define SQLITE_FINISH 2 /* Like SQLITE_XFER, plus dynamic string freed */ /* ** CAPI3REF: Add Content To A Dynamic String ** METHOD: sqlite3_str ** -** These interfaces add content to an sqlite3_str object previously obtained -** from [sqlite3_str_new()]. +** These interfaces add or remove content to an sqlite3_str object +** previously obtained from [sqlite3_str_new()]. ** ** ^The [sqlite3_str_appendf(X,F,...)] and ** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf] @@ -8510,6 +8955,10 @@ SQLITE_API char *sqlite3_str_finish(sqlite3_str*); ** ^The [sqlite3_str_reset(X)] method resets the string under construction ** inside [sqlite3_str] object X back to zero bytes in length. ** +** ^The [sqlite3_str_truncate(X,N)] method changes the length of the string +** under construction to be N bytes or less. This routine is a no-op if +** N is negative or if the string is already N bytes or smaller in size. +** ** These methods do not return a result code. ^If an error occurs, that fact ** is recorded in the [sqlite3_str] object and can be recovered by a ** subsequent call to [sqlite3_str_errcode(X)]. @@ -8520,6 +8969,7 @@ SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N); SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn); SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C); SQLITE_API void sqlite3_str_reset(sqlite3_str*); +SQLITE_API void sqlite3_str_truncate(sqlite3_str*,int N); /* ** CAPI3REF: Status Of A Dynamic String @@ -8543,7 +8993,7 @@ SQLITE_API void sqlite3_str_reset(sqlite3_str*); ** content of the dynamic string under construction in X. The value ** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X ** and might be freed or altered by any subsequent method on the same -** [sqlite3_str] object. Applications must not used the pointer returned +** [sqlite3_str] object. Applications must not use the pointer returned by ** [sqlite3_str_value(X)] after any subsequent method call on the same ** object. ^Applications may change the content of the string returned ** by [sqlite3_str_value(X)] as long as they do not write into any bytes @@ -8629,7 +9079,7 @@ SQLITE_API int sqlite3_status64( ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] ** buffer and where forced to overflow to [sqlite3_malloc()]. The ** returned value includes allocations that overflowed because they -** where too large (they were larger than the "sz" parameter to +** were too large (they were larger than the "sz" parameter to ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because ** no space was left in the page cache.</dd>)^ ** @@ -8688,9 +9138,18 @@ SQLITE_API int sqlite3_status64( ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a ** non-zero [error code] on failure. ** +** ^The sqlite3_db_status64(D,O,C,H,R) routine works exactly the same +** way as sqlite3_db_status(D,O,C,H,R) routine except that the C and H +** parameters are pointer to 64-bit integers (type: sqlite3_int64) instead +** of pointers to 32-bit integers, which allows larger status values +** to be returned. If a status value exceeds 2,147,483,647 then +** sqlite3_db_status() will truncate the value whereas sqlite3_db_status64() +** will return the full value. +** ** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. */ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); +SQLITE_API int sqlite3_db_status64(sqlite3*,int,sqlite3_int64*,sqlite3_int64*,int); /* ** CAPI3REF: Status Parameters for database connections @@ -8713,28 +9172,29 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt> ** <dd>This parameter returns the number of malloc attempts that were ** satisfied using lookaside memory. Only the high-water value is meaningful; -** the current value is always zero.)^ +** the current value is always zero.</dd>)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt> -** <dd>This parameter returns the number malloc attempts that might have +** <dd>This parameter returns the number of malloc attempts that might have ** been satisfied using lookaside memory but failed due to the amount of ** memory requested being larger than the lookaside slot size. ** Only the high-water value is meaningful; -** the current value is always zero.)^ +** the current value is always zero.</dd>)^ ** ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt> -** <dd>This parameter returns the number malloc attempts that might have +** <dd>This parameter returns the number of malloc attempts that might have ** been satisfied using lookaside memory but failed due to all lookaside ** memory already being in use. ** Only the high-water value is meaningful; -** the current value is always zero.)^ +** the current value is always zero.</dd>)^ ** ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt> ** <dd>This parameter returns the approximate number of bytes of heap ** memory used by all pager caches associated with the database connection.)^ ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. +** </dd> ** ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt> @@ -8743,10 +9203,10 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** memory used by that pager cache is divided evenly between the attached ** connections.)^ In other words, if none of the pager caches associated ** with the database connection are shared, this request returns the same -** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are +** value as DBSTATUS_CACHE_USED. Or, if one or more of the pager caches are ** shared, the value returned by this call will be smaller than that returned ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with -** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0. +** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.</dd> ** ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt> ** <dd>This parameter returns the approximate number of bytes of heap @@ -8756,6 +9216,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** schema memory is shared with other database connections due to ** [shared cache mode] being enabled. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. +** </dd> ** ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt> ** <dd>This parameter returns the approximate number of bytes of heap @@ -8785,6 +9246,10 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** If an IO or other error occurs while writing a page to disk, the effect ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. +** <p> +** ^(There is overlap between the quantities measured by this parameter +** (SQLITE_DBSTATUS_CACHE_WRITE) and SQLITE_DBSTATUS_TEMPBUF_SPILL. +** Resetting one will reduce the other.)^ ** </dd> ** ** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt> @@ -8792,7 +9257,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** been written to disk in the middle of a transaction due to the page ** cache overflowing. Transactions are more efficient if they are written ** to disk all at once. When pages spill mid-transaction, that introduces -** additional overhead. This parameter can be used help identify +** additional overhead. This parameter can be used to help identify ** inefficiencies that can be resolved by increasing the cache size. ** </dd> ** @@ -8800,6 +9265,18 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r ** <dd>This parameter returns zero for the current value if and only if ** all foreign key constraints (deferred or immediate) have been ** resolved.)^ ^The highwater mark is always 0. +** +** [[SQLITE_DBSTATUS_TEMPBUF_SPILL] ^(<dt>SQLITE_DBSTATUS_TEMPBUF_SPILL</dt> +** <dd>^(This parameter returns the number of bytes written to temporary +** files on disk that could have been kept in memory had sufficient memory +** been available. This value includes writes to intermediate tables that +** are part of complex queries, external sorts that spill to disk, and +** writes to TEMP tables.)^ +** ^The highwater mark is always 0. +** <p> +** ^(There is overlap between the quantities measured by this parameter +** (SQLITE_DBSTATUS_TEMPBUF_SPILL) and SQLITE_DBSTATUS_CACHE_WRITE. +** Resetting one will reduce the other.)^ ** </dd> ** </dl> */ @@ -8816,7 +9293,8 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r #define SQLITE_DBSTATUS_DEFERRED_FKS 10 #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11 #define SQLITE_DBSTATUS_CACHE_SPILL 12 -#define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */ +#define SQLITE_DBSTATUS_TEMPBUF_SPILL 13 +#define SQLITE_DBSTATUS_MAX 13 /* Largest defined DBSTATUS */ /* @@ -8863,13 +9341,13 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt> ** <dd>^This is the number of sort operations that have occurred. ** A non-zero value in this counter may indicate an opportunity to -** improvement performance through careful use of indices.</dd> +** improve performance through careful use of indices.</dd> ** ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt> ** <dd>^This is the number of rows inserted into transient indices that ** were created automatically in order to help joins run faster. ** A non-zero value in this counter may indicate an opportunity to -** improvement performance by adding permanent indices that do not +** improve performance by adding permanent indices that do not ** need to be reinitialized each time the statement is run.</dd> ** ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt> @@ -8878,19 +9356,19 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); ** to 2147483647. The number of virtual machine operations can be ** used as a proxy for the total work done by the prepared statement. ** If the number of virtual machine operations exceeds 2147483647 -** then the value returned by this statement status code is undefined. +** then the value returned by this statement status code is undefined.</dd> ** ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt> ** <dd>^This is the number of times that the prepare statement has been ** automatically regenerated due to schema changes or changes to -** [bound parameters] that might affect the query plan. +** [bound parameters] that might affect the query plan.</dd> ** ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt> ** <dd>^This is the number of times that the prepared statement has ** been run. A single "run" for the purposes of this counter is one ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()]. ** The counter is incremented on the first [sqlite3_step()] call of each -** cycle. +** cycle.</dd> ** ** [[SQLITE_STMTSTATUS_FILTER_MISS]] ** [[SQLITE_STMTSTATUS_FILTER HIT]] @@ -8900,7 +9378,7 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); ** step was bypassed because a Bloom filter returned not-found. The ** corresponding SQLITE_STMTSTATUS_FILTER_MISS value is the number of ** times that the Bloom filter returned a find, and thus the join step -** had to be processed as normal. +** had to be processed as normal.</dd> ** ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt> ** <dd>^This is the approximate number of bytes of heap memory @@ -9005,9 +9483,9 @@ struct sqlite3_pcache_page { ** SQLite will typically create one cache instance for each open database file, ** though this is not guaranteed. ^The ** first parameter, szPage, is the size in bytes of the pages that must -** be allocated by the cache. ^szPage will always a power of two. ^The +** be allocated by the cache. ^szPage will always be a power of two. ^The ** second parameter szExtra is a number of bytes of extra storage -** associated with each page cache entry. ^The szExtra parameter will +** associated with each page cache entry. ^The szExtra parameter will be ** a number less than 250. SQLite will use the ** extra szExtra bytes on each page to store metadata about the underlying ** database page on disk. The value passed into szExtra depends @@ -9015,17 +9493,17 @@ struct sqlite3_pcache_page { ** ^The third argument to xCreate(), bPurgeable, is true if the cache being ** created will be used to cache database pages of a file stored on disk, or ** false if it is used for an in-memory database. The cache implementation -** does not have to do anything special based with the value of bPurgeable; +** does not have to do anything special based upon the value of bPurgeable; ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will ** never invoke xUnpin() except to deliberately delete a page. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to ** false will always have the "discard" flag set to true. -** ^Hence, a cache created with bPurgeable false will +** ^Hence, a cache created with bPurgeable set to false will ** never contain any unpinned pages. ** ** [[the xCachesize() page cache method]] ** ^(The xCachesize() method may be called at any time by SQLite to set the -** suggested maximum cache-size (number of pages stored by) the cache +** suggested maximum cache-size (number of pages stored) for the cache ** instance passed as the first argument. This is the value configured using ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable ** parameter, the implementation is not required to do anything with this @@ -9052,12 +9530,12 @@ struct sqlite3_pcache_page { ** implementation must return a pointer to the page buffer with its content ** intact. If the requested page is not already in the cache, then the ** cache implementation should use the value of the createFlag -** parameter to help it determined what action to take: +** parameter to help it determine what action to take: ** ** <table border=1 width=85% align=center> ** <tr><th> createFlag <th> Behavior when page is not already in cache ** <tr><td> 0 <td> Do not allocate a new page. Return NULL. -** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so. +** <tr><td> 1 <td> Allocate a new page if it is easy and convenient to do so. ** Otherwise return NULL. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return ** NULL if allocating a new page is effectively impossible. @@ -9074,7 +9552,7 @@ struct sqlite3_pcache_page { ** as its second argument. If the third parameter, discard, is non-zero, ** then the page must be evicted from the cache. ** ^If the discard parameter is -** zero, then the page may be discarded or retained at the discretion of +** zero, then the page may be discarded or retained at the discretion of the ** page cache implementation. ^The page cache implementation ** may choose to evict unpinned pages at any time. ** @@ -9092,7 +9570,7 @@ struct sqlite3_pcache_page { ** When SQLite calls the xTruncate() method, the cache must discard all ** existing cache entries with page numbers (keys) greater than or equal ** to the value of the iLimit parameter passed to xTruncate(). If any -** of these pages are pinned, they are implicitly unpinned, meaning that +** of these pages are pinned, they become implicitly unpinned, meaning that ** they can be safely discarded. ** ** [[the xDestroy() page cache method]] @@ -9272,7 +9750,7 @@ typedef struct sqlite3_backup sqlite3_backup; ** external process or via a database connection other than the one being ** used by the backup operation, then the backup will be automatically ** restarted by the next call to sqlite3_backup_step(). ^If the source -** database is modified by the using the same database connection as is used +** database is modified by using the same database connection as is used ** by the backup operation, then the backup database is automatically ** updated at the same time. ** @@ -9289,7 +9767,7 @@ typedef struct sqlite3_backup sqlite3_backup; ** and may not be used following a call to sqlite3_backup_finish(). ** ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no -** sqlite3_backup_step() errors occurred, regardless or whether or not +** sqlite3_backup_step() errors occurred, regardless of whether or not ** sqlite3_backup_step() completed. ** ^If an out-of-memory condition or IO error occurred during any prior ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then @@ -9391,7 +9869,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** application receives an SQLITE_LOCKED error, it may call the ** sqlite3_unlock_notify() method with the blocked connection handle as ** the first argument to register for a callback that will be invoked -** when the blocking connections current transaction is concluded. ^The +** when the blocking connection's current transaction is concluded. ^The ** callback is invoked from within the [sqlite3_step] or [sqlite3_close] ** call that concludes the blocking connection's transaction. ** @@ -9411,7 +9889,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); ** blocked connection already has a registered unlock-notify callback, ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is ** called with a NULL pointer as its second argument, then any existing -** unlock-notify callback is canceled. ^The blocked connections +** unlock-notify callback is canceled. ^The blocked connection's ** unlock-notify callback may also be canceled by closing the blocked ** connection using [sqlite3_close()]. ** @@ -9581,7 +10059,7 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); ** is the number of pages currently in the write-ahead log file, ** including those that were just committed. ** -** The callback function should normally return [SQLITE_OK]. ^If an error +** ^The callback function should normally return [SQLITE_OK]. ^If an error ** code is returned, that error will propagate back up through the ** SQLite code base to cause the statement that provoked the callback ** to report an error, though the commit will have still occurred. If the @@ -9589,13 +10067,26 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); ** that does not correspond to any valid SQLite error code, the results ** are undefined. ** -** A single database handle may have at most a single write-ahead log callback -** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any -** previously registered write-ahead log callback. ^The return value is -** a copy of the third parameter from the previous call, if any, or 0. -** ^Note that the [sqlite3_wal_autocheckpoint()] interface and the -** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will -** overwrite any prior [sqlite3_wal_hook()] settings. +** ^A single database handle may have at most a single write-ahead log +** callback registered at one time. ^Calling [sqlite3_wal_hook()] +** replaces the default behavior or previously registered write-ahead +** log callback. +** +** ^The return value is a copy of the third parameter from the +** previous call, if any, or 0. +** +** ^The [sqlite3_wal_autocheckpoint()] interface and the +** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and +** will overwrite any prior [sqlite3_wal_hook()] settings. +** +** ^If a write-ahead log callback is set using this function then +** [sqlite3_wal_checkpoint_v2()] or [PRAGMA wal_checkpoint] +** should be invoked periodically to keep the write-ahead log file +** from growing without bound. +** +** ^Passing a NULL pointer for the callback disables automatic +** checkpointing entirely. To re-enable the default behavior, call +** sqlite3_wal_autocheckpoint(db,1000) or use [PRAGMA wal_checkpoint]. */ SQLITE_API void *sqlite3_wal_hook( sqlite3*, @@ -9612,7 +10103,7 @@ SQLITE_API void *sqlite3_wal_hook( ** to automatically [checkpoint] ** after committing a transaction if there are N or ** more frames in the [write-ahead log] file. ^Passing zero or -** a negative value as the nFrame parameter disables automatic +** a negative value as the N parameter disables automatic ** checkpoints entirely. ** ** ^The callback registered by this function replaces any existing callback @@ -9628,9 +10119,10 @@ SQLITE_API void *sqlite3_wal_hook( ** ** ^Every new [database connection] defaults to having the auto-checkpoint ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] -** pages. The use of this interface -** is only necessary if the default setting is found to be suboptimal -** for a particular application. +** pages. +** +** ^The use of this interface is only necessary if the default setting +** is found to be suboptimal for a particular application. */ SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); @@ -9695,6 +10187,11 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the ** addition that it also truncates the log file to zero bytes just prior ** to a successful return. +** +** <dt>SQLITE_CHECKPOINT_NOOP<dd> +** ^This mode always checkpoints zero frames. The only reason to invoke +** a NOOP checkpoint is to access the values returned by +** sqlite3_wal_checkpoint_v2() via output parameters *pnLog and *pnCkpt. ** </dl> ** ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in @@ -9765,6 +10262,7 @@ SQLITE_API int sqlite3_wal_checkpoint_v2( ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the ** meaning of each of these checkpoint modes. */ +#define SQLITE_CHECKPOINT_NOOP -1 /* Do no work at all */ #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */ #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */ #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for readers */ @@ -9809,7 +10307,7 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); ** support constraints. In this configuration (which is the default) if ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been -** specified as part of the users SQL statement, regardless of the actual +** specified as part of the user's SQL statement, regardless of the actual ** ON CONFLICT mode specified. ** ** If X is non-zero, then the virtual table implementation guarantees @@ -9843,7 +10341,7 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); ** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt> ** <dd>Calls of the form ** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the -** the [xConnect] or [xCreate] methods of a [virtual table] implementation +** [xConnect] or [xCreate] methods of a [virtual table] implementation ** identify that virtual table as being safe to use from within triggers ** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the ** virtual table can do no serious harm even if it is controlled by a @@ -10002,7 +10500,8 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int); ** <tr> ** <td valign="top">sqlite3_vtab_distinct() return value ** <td valign="top">Rows are returned in aOrderBy order -** <td valign="top">Rows with the same value in all aOrderBy columns are adjacent +** <td valign="top">Rows with the same value in all aOrderBy columns are +** adjacent ** <td valign="top">Duplicates over all colUsed columns may be omitted ** <tr><td>0<td>yes<td>yes<td>no ** <tr><td>1<td>no<td>yes<td>no @@ -10011,8 +10510,8 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int); ** </table> ** ** ^For the purposes of comparing virtual table output values to see if the -** values are same value for sorting purposes, two NULL values are considered -** to be the same. In other words, the comparison operator is "IS" +** values are the same value for sorting purposes, two NULL values are +** considered to be the same. In other words, the comparison operator is "IS" ** (or "IS NOT DISTINCT FROM") and not "==". ** ** If a virtual table implementation is unable to meet the requirements @@ -10021,7 +10520,7 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info*,int); ** ** ^A virtual table implementation is always free to return rows in any order ** it wants, as long as the "orderByConsumed" flag is not set. ^When the -** the "orderByConsumed" flag is unset, the query planner will add extra +** "orderByConsumed" flag is unset, the query planner will add extra ** [bytecode] to ensure that the final results returned by the SQL query are ** ordered correctly. The use of the "orderByConsumed" flag and the ** sqlite3_vtab_distinct() interface is merely an optimization. ^Careful @@ -10118,7 +10617,7 @@ SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle); ** sqlite3_vtab_in_next(X,P) should be one of the parameters to the ** xFilter method which invokes these routines, and specifically ** a parameter that was previously selected for all-at-once IN constraint -** processing use the [sqlite3_vtab_in()] interface in the +** processing using the [sqlite3_vtab_in()] interface in the ** [xBestIndex|xBestIndex method]. ^(If the X parameter is not ** an xFilter argument that was selected for all-at-once IN constraint ** processing, then these routines return [SQLITE_ERROR].)^ @@ -10133,7 +10632,7 @@ SQLITE_API int sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle); ** &nbsp; ){ ** &nbsp; // do something with pVal ** &nbsp; } -** &nbsp; if( rc!=SQLITE_OK ){ +** &nbsp; if( rc!=SQLITE_DONE ){ ** &nbsp; // an error has occurred ** &nbsp; } ** </pre></blockquote>)^ @@ -10173,7 +10672,7 @@ SQLITE_API int sqlite3_vtab_in_next(sqlite3_value *pVal, sqlite3_value **ppOut); ** and only if *V is set to a value. ^The sqlite3_vtab_rhs_value(P,J,V) ** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th ** constraint is not available. ^The sqlite3_vtab_rhs_value() interface -** can return an result code other than SQLITE_OK or SQLITE_NOTFOUND if +** can return a result code other than SQLITE_OK or SQLITE_NOTFOUND if ** something goes wrong. ** ** The sqlite3_vtab_rhs_value() interface is usually only successful if @@ -10201,8 +10700,8 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value ** ** KEYWORDS: {conflict resolution mode} ** ** These constants are returned by [sqlite3_vtab_on_conflict()] to -** inform a [virtual table] implementation what the [ON CONFLICT] mode -** is for the SQL statement being evaluated. +** inform a [virtual table] implementation of the [ON CONFLICT] mode +** for the SQL statement being evaluated. ** ** Note that the [SQLITE_IGNORE] constant is also used as a potential ** return value from the [sqlite3_set_authorizer()] callback and that @@ -10242,39 +10741,39 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value ** ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt> ** <dd>^The "double" variable pointed to by the V parameter will be set to the ** query planner's estimate for the average number of rows output from each -** iteration of the X-th loop. If the query planner's estimates was accurate, +** iteration of the X-th loop. If the query planner's estimate was accurate, ** then this value will approximate the quotient NVISIT/NLOOP and the ** product of this value for all prior loops with the same SELECTID will -** be the NLOOP value for the current loop. +** be the NLOOP value for the current loop.</dd> ** ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt> ** <dd>^The "const char *" variable pointed to by the V parameter will be set ** to a zero-terminated UTF-8 string containing the name of the index or table -** used for the X-th loop. +** used for the X-th loop.</dd> ** ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt> ** <dd>^The "const char *" variable pointed to by the V parameter will be set ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN] -** description for the X-th loop. +** description for the X-th loop.</dd> ** ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECTID</dt> ** <dd>^The "int" variable pointed to by the V parameter will be set to the ** id for the X-th query plan element. The id value is unique within the ** statement. The select-id is the same value as is output in the first -** column of an [EXPLAIN QUERY PLAN] query. +** column of an [EXPLAIN QUERY PLAN] query.</dd> ** ** [[SQLITE_SCANSTAT_PARENTID]] <dt>SQLITE_SCANSTAT_PARENTID</dt> ** <dd>The "int" variable pointed to by the V parameter will be set to the -** the id of the parent of the current query element, if applicable, or +** id of the parent of the current query element, if applicable, or ** to zero if the query element has no parent. This is the same value as -** returned in the second column of an [EXPLAIN QUERY PLAN] query. +** returned in the second column of an [EXPLAIN QUERY PLAN] query.</dd> ** ** [[SQLITE_SCANSTAT_NCYCLE]] <dt>SQLITE_SCANSTAT_NCYCLE</dt> ** <dd>The sqlite3_int64 output value is set to the number of cycles, ** according to the processor time-stamp counter, that elapsed while the ** query element was being processed. This value is not available for ** all query elements - if it is unavailable the output variable is -** set to -1. +** set to -1.</dd> ** </dl> */ #define SQLITE_SCANSTAT_NLOOP 0 @@ -10305,9 +10804,9 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value ** ** a variable pointed to by the "pOut" parameter. ** ** The "flags" parameter must be passed a mask of flags. At present only -** one flag is defined - SQLITE_SCANSTAT_COMPLEX. If SQLITE_SCANSTAT_COMPLEX +** one flag is defined - [SQLITE_SCANSTAT_COMPLEX]. If SQLITE_SCANSTAT_COMPLEX ** is specified, then status information is available for all elements -** of a query plan that are reported by "EXPLAIN QUERY PLAN" output. If +** of a query plan that are reported by "[EXPLAIN QUERY PLAN]" output. If ** SQLITE_SCANSTAT_COMPLEX is not specified, then only query plan elements ** that correspond to query loops (the "SCAN..." and "SEARCH..." elements of ** the EXPLAIN QUERY PLAN output) are available. Invoking API @@ -10315,13 +10814,14 @@ SQLITE_API int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value ** ** sqlite3_stmt_scanstatus_v2() with a zeroed flags parameter. ** ** Parameter "idx" identifies the specific query element to retrieve statistics -** for. Query elements are numbered starting from zero. A value of -1 may be -** to query for statistics regarding the entire query. ^If idx is out of range +** for. Query elements are numbered starting from zero. A value of -1 may +** retrieve statistics for the entire query. ^If idx is out of range ** - less than -1 or greater than or equal to the total number of query ** elements used to implement the statement - a non-zero value is returned and ** the variable that pOut points to is unchanged. ** -** See also: [sqlite3_stmt_scanstatus_reset()] +** See also: [sqlite3_stmt_scanstatus_reset()] and the +** [nexec and ncycle] columns of the [bytecode virtual table]. */ SQLITE_API int sqlite3_stmt_scanstatus( sqlite3_stmt *pStmt, /* Prepared statement for which info desired */ @@ -10359,7 +10859,7 @@ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); ** METHOD: sqlite3 ** ** ^If a write-transaction is open on [database connection] D when the -** [sqlite3_db_cacheflush(D)] interface invoked, any dirty +** [sqlite3_db_cacheflush(D)] interface is invoked, any dirty ** pages in the pager-cache that are not currently in use are written out ** to disk. A dirty page may be in use if a database cursor created by an ** active SQL statement is reading from it, or if it is page 1 of a database @@ -10473,8 +10973,8 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*); ** triggers; and so forth. ** ** When the [sqlite3_blob_write()] API is used to update a blob column, -** the pre-update hook is invoked with SQLITE_DELETE. This is because the -** in this case the new values are not available. In this case, when a +** the pre-update hook is invoked with SQLITE_DELETE, because +** the new values are not yet available. In this case, when a ** callback made with op==SQLITE_DELETE is actually a write using the ** sqlite3_blob_write() API, the [sqlite3_preupdate_blobwrite()] returns ** the index of the column being written. In other cases, where the @@ -10592,7 +11092,7 @@ typedef struct sqlite3_snapshot { ** The [sqlite3_snapshot_get()] interface is only available when the ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( +SQLITE_API int sqlite3_snapshot_get( sqlite3 *db, const char *zSchema, sqlite3_snapshot **ppSnapshot @@ -10641,7 +11141,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get( ** The [sqlite3_snapshot_open()] interface is only available when the ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( +SQLITE_API int sqlite3_snapshot_open( sqlite3 *db, const char *zSchema, sqlite3_snapshot *pSnapshot @@ -10658,7 +11158,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open( ** The [sqlite3_snapshot_free()] interface is only available when the ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used. */ -SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); +SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot*); /* ** CAPI3REF: Compare the ages of two snapshot handles. @@ -10685,7 +11185,7 @@ SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*); ** This interface is only available if SQLite is compiled with the ** [SQLITE_ENABLE_SNAPSHOT] option. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( +SQLITE_API int sqlite3_snapshot_cmp( sqlite3_snapshot *p1, sqlite3_snapshot *p2 ); @@ -10713,20 +11213,21 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( ** This interface is only available if SQLite is compiled with the ** [SQLITE_ENABLE_SNAPSHOT] option. */ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); +SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); /* ** CAPI3REF: Serialize a database ** -** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory -** that is a serialization of the S database on [database connection] D. +** The sqlite3_serialize(D,S,P,F) interface returns a pointer to +** memory that is a serialization of the S database on +** [database connection] D. If S is a NULL pointer, the main database is used. ** If P is not a NULL pointer, then the size of the database in bytes ** is written into *P. ** ** For an ordinary on-disk database file, the serialization is just a ** copy of the disk file. For an in-memory database or a "TEMP" database, ** the serialization is the same sequence of bytes which would be written -** to disk if that database where backed up to disk. +** to disk if that database were backed up to disk. ** ** The usual case is that sqlite3_serialize() copies the serialization of ** the database into memory obtained from [sqlite3_malloc64()] and returns @@ -10735,7 +11236,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const c ** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations ** are made, and the sqlite3_serialize() function will return a pointer ** to the contiguous memory representation of the database that SQLite -** is currently using for that database, or NULL if the no such contiguous +** is currently using for that database, or NULL if no such contiguous ** memory representation of the database exists. A contiguous memory ** representation of the database will usually only exist if there has ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same @@ -10786,12 +11287,24 @@ SQLITE_API unsigned char *sqlite3_serialize( ** ** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the ** [database connection] D to disconnect from database S and then -** reopen S as an in-memory database based on the serialization contained -** in P. The serialized database P is N bytes in size. M is the size of -** the buffer P, which might be larger than N. If M is larger than N, and -** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is -** permitted to add content to the in-memory database as long as the total -** size does not exceed M bytes. +** reopen S as an in-memory database based on the serialization +** contained in P. If S is a NULL pointer, the main database is +** used. The serialized database P is N bytes in size. M is the size +** of the buffer P, which might be larger than N. If M is larger than +** N, and the SQLITE_DESERIALIZE_READONLY bit is not set in F, then +** SQLite is permitted to add content to the in-memory database, in +** page-sized chunks, as long as the total size does not exceed M bytes. +** +** The parameter M must be greater than or equal to N. Ideally, M +** should have a value which is N+(512&times;K)+20 where K determines how +** must extra space is available to hold new content as the database +** grows. K can be 0 if the database is read-only. +** +** If the database content in P is malformed in a malicious way then +** it is possible that SQLite might try to read a few more than N bytes +** from P. If the veracity of the database content P is uncertain, +** then applications are advised to allocate about 20 extra bytes on +** the end of the P buffer to avoid a memory error. ** ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will ** invoke sqlite3_free() on the serialization buffer when the database @@ -10806,7 +11319,7 @@ SQLITE_API unsigned char *sqlite3_serialize( ** database is currently in a read transaction or is involved in a backup ** operation. ** -** It is not possible to deserialized into the TEMP database. If the +** It is not possible to deserialize into the TEMP database. If the ** S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the ** function returns SQLITE_ERROR. ** @@ -10828,7 +11341,7 @@ SQLITE_API int sqlite3_deserialize( sqlite3 *db, /* The database connection */ const char *zSchema, /* Which DB to reopen with the deserialization */ unsigned char *pData, /* The serialized database content */ - sqlite3_int64 szDb, /* Number bytes in the deserialization */ + sqlite3_int64 szDb, /* Number of bytes in the deserialization */ sqlite3_int64 szBuf, /* Total size of buffer pData[] */ unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */ ); @@ -10836,7 +11349,7 @@ SQLITE_API int sqlite3_deserialize( /* ** CAPI3REF: Flags for sqlite3_deserialize() ** -** The following are allowed values for 6th argument (the F argument) to +** The following are allowed values for the 6th argument (the F argument) to ** the [sqlite3_deserialize(D,S,P,N,M,F)] interface. ** ** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization @@ -10858,6 +11371,77 @@ SQLITE_API int sqlite3_deserialize( #define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */ #define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */ +/* +** CAPI3REF: Bind array values to the CARRAY table-valued function +** +** The sqlite3_carray_bind_v2(S,I,P,N,F,X,D) interface binds an array value to +** parameter that is the first argument of the [carray() table-valued function]. +** The S parameter is a pointer to the [prepared statement] that uses the +** carray() functions. I is the parameter index to be bound. I must be the +** index of the parameter that is the first argument to the carray() +** table-valued function. P is a pointer to the array to be bound, and N +** is the number of elements in the array. The F argument is one of +** constants [SQLITE_CARRAY_INT32], [SQLITE_CARRAY_INT64], +** [SQLITE_CARRAY_DOUBLE], [SQLITE_CARRAY_TEXT], +** or [SQLITE_CARRAY_BLOB] to indicate the datatype of the array P. +** +** If the X argument is not a NULL pointer or one of the special +** values [SQLITE_STATIC] or [SQLITE_TRANSIENT], then SQLite will invoke +** the function X with argument D when it is finished using the data in P. +** The call to X(D) is a destructor for the array P. The destructor X(D) +** is invoked even if the call to sqlite3_carray_bind_v2() fails. If the X +** parameter is the special-case value [SQLITE_STATIC], then SQLite assumes +** that the data static and the destructor is never invoked. If the X +** parameter is the special-case value [SQLITE_TRANSIENT], then +** sqlite3_carray_bind_v2() makes its own private copy of the data prior +** to returning and never invokes the destructor X. +** +** The sqlite3_carray_bind() function works the same as sqlite3_carray_bind_v2() +** with a D parameter set to P. In other words, +** sqlite3_carray_bind(S,I,P,N,F,X) is same as +** sqlite3_carray_bind_v2(S,I,P,N,F,X,P). +*/ +SQLITE_API int sqlite3_carray_bind_v2( + sqlite3_stmt *pStmt, /* Statement to be bound */ + int i, /* Parameter index */ + void *aData, /* Pointer to array data */ + int nData, /* Number of data elements */ + int mFlags, /* CARRAY flags */ + void (*xDel)(void*), /* Destructor for aData */ + void *pDel /* Optional argument to xDel() */ +); +SQLITE_API int sqlite3_carray_bind( + sqlite3_stmt *pStmt, /* Statement to be bound */ + int i, /* Parameter index */ + void *aData, /* Pointer to array data */ + int nData, /* Number of data elements */ + int mFlags, /* CARRAY flags */ + void (*xDel)(void*) /* Destructor for aData */ +); + +/* +** CAPI3REF: Datatypes for the CARRAY table-valued function +** +** The fifth argument to the [sqlite3_carray_bind()] interface musts be +** one of the following constants, to specify the datatype of the array +** that is being bound into the [carray table-valued function]. +*/ +#define SQLITE_CARRAY_INT32 0 /* Data is 32-bit signed integers */ +#define SQLITE_CARRAY_INT64 1 /* Data is 64-bit signed integers */ +#define SQLITE_CARRAY_DOUBLE 2 /* Data is doubles */ +#define SQLITE_CARRAY_TEXT 3 /* Data is char* */ +#define SQLITE_CARRAY_BLOB 4 /* Data is struct iovec */ + +/* +** Versions of the above #defines that omit the initial SQLITE_, for +** legacy compatibility. +*/ +#define CARRAY_INT32 0 /* Data is 32-bit signed integers */ +#define CARRAY_INT64 1 /* Data is 64-bit signed integers */ +#define CARRAY_DOUBLE 2 /* Data is doubles */ +#define CARRAY_TEXT 3 /* Data is char* */ +#define CARRAY_BLOB 4 /* Data is struct iovec */ + /* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. @@ -10880,7 +11464,7 @@ SQLITE_API int sqlite3_deserialize( #ifdef __cplusplus } /* End of the 'extern "C"' block */ #endif -#endif /* SQLITE3_H */ +/* #endif for SQLITE3_H will be added by mksqlite3.tcl */ /******** Begin file sqlite3rtree.h *********/ /* @@ -11361,9 +11945,10 @@ SQLITE_API void sqlite3session_table_filter( ** is inserted while a session object is enabled, then later deleted while ** the same session object is disabled, no INSERT record will appear in the ** changeset, even though the delete took place while the session was disabled. -** Or, if one field of a row is updated while a session is disabled, and -** another field of the same row is updated while the session is enabled, the -** resulting changeset will contain an UPDATE change that updates both fields. +** Or, if one field of a row is updated while a session is enabled, and +** then another field of the same row is updated while the session is disabled, +** the resulting changeset will contain an UPDATE change that updates both +** fields. */ SQLITE_API int sqlite3session_changeset( sqlite3_session *pSession, /* Session object */ @@ -11435,8 +12020,9 @@ SQLITE_API sqlite3_int64 sqlite3session_changeset_size(sqlite3_session *pSession ** database zFrom the contents of the two compatible tables would be ** identical. ** -** It an error if database zFrom does not exist or does not contain the -** required compatible table. +** Unless the call to this function is a no-op as described above, it is an +** error if database zFrom does not exist or does not contain the required +** compatible table. ** ** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg @@ -11571,7 +12157,7 @@ SQLITE_API int sqlite3changeset_start_v2( ** The following flags may passed via the 4th parameter to ** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]: ** -** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd> +** <dt>SQLITE_CHANGESETSTART_INVERT <dd> ** Invert the changeset while iterating through it. This is equivalent to ** inverting a changeset using sqlite3changeset_invert() before applying it. ** It is an error to specify this flag with a patchset. @@ -11886,19 +12472,6 @@ SQLITE_API int sqlite3changeset_concat( void **ppOut /* OUT: Buffer containing output changeset */ ); - -/* -** CAPI3REF: Upgrade the Schema of a Changeset/Patchset -*/ -SQLITE_API int sqlite3changeset_upgrade( - sqlite3 *db, - const char *zDb, - int nIn, const void *pIn, /* Input changeset */ - int *pnOut, void **ppOut /* OUT: Inverse of input */ -); - - - /* ** CAPI3REF: Changegroup Handle ** @@ -12128,14 +12701,32 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*); ** update the "main" database attached to handle db with the changes found in ** the changeset passed via the second and third arguments. ** +** All changes made by these functions are enclosed in a savepoint transaction. +** If any other error (aside from a constraint failure when attempting to +** write to the target database) occurs, then the savepoint transaction is +** rolled back, restoring the target database to its original state, and an +** SQLite error code returned. Additionally, starting with version 3.51.0, +** an error code and error message that may be accessed using the +** [sqlite3_errcode()] and [sqlite3_errmsg()] APIs are left in the database +** handle. +** ** The fourth argument (xFilter) passed to these functions is the "filter -** callback". If it is not NULL, then for each table affected by at least one -** change in the changeset, the filter callback is invoked with -** the table name as the second argument, and a copy of the context pointer -** passed as the sixth argument as the first. If the "filter callback" -** returns zero, then no attempt is made to apply any changes to the table. -** Otherwise, if the return value is non-zero or the xFilter argument to -** is NULL, all changes related to the table are attempted. +** callback". This may be passed NULL, in which case all changes in the +** changeset are applied to the database. For sqlite3changeset_apply() and +** sqlite3_changeset_apply_v2(), if it is not NULL, then it is invoked once +** for each table affected by at least one change in the changeset. In this +** case the table name is passed as the second argument, and a copy of +** the context pointer passed as the sixth argument to apply() or apply_v2() +** as the first. If the "filter callback" returns zero, then no attempt is +** made to apply any changes to the table. Otherwise, if the return value is +** non-zero, all changes related to the table are attempted. +** +** For sqlite3_changeset_apply_v3(), the xFilter callback is invoked once +** per change. The second argument in this case is an sqlite3_changeset_iter +** that may be queried using the usual APIs for the details of the current +** change. If the "filter callback" returns zero in this case, then no attempt +** is made to apply the current change. If it returns non-zero, the change +** is applied. ** ** For each table that is not excluded by the filter callback, this function ** tests that the target database contains a compatible table. A table is @@ -12156,11 +12747,11 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*); ** one such warning is issued for each table in the changeset. ** ** For each change for which there is a compatible table, an attempt is made -** to modify the table contents according to the UPDATE, INSERT or DELETE -** change. If a change cannot be applied cleanly, the conflict handler -** function passed as the fifth argument to sqlite3changeset_apply() may be -** invoked. A description of exactly when the conflict handler is invoked for -** each type of change is below. +** to modify the table contents according to each UPDATE, INSERT or DELETE +** change that is not excluded by a filter callback. If a change cannot be +** applied cleanly, the conflict handler function passed as the fifth argument +** to sqlite3changeset_apply() may be invoked. A description of exactly when +** the conflict handler is invoked for each type of change is below. ** ** Unlike the xFilter argument, xConflict may not be passed NULL. The results ** of passing anything other than a valid function pointer as the xConflict @@ -12256,12 +12847,6 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*); ** This can be used to further customize the application's conflict ** resolution strategy. ** -** All changes made by these functions are enclosed in a savepoint transaction. -** If any other error (aside from a constraint failure when attempting to -** write to the target database) occurs, then the savepoint transaction is -** rolled back, restoring the target database to its original state, and an -** SQLite error code returned. -** ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and ** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2() ** may set (*ppRebase) to point to a "rebase" that may be used with the @@ -12311,6 +12896,23 @@ SQLITE_API int sqlite3changeset_apply_v2( void **ppRebase, int *pnRebase, /* OUT: Rebase data */ int flags /* SESSION_CHANGESETAPPLY_* flags */ ); +SQLITE_API int sqlite3changeset_apply_v3( + sqlite3 *db, /* Apply change to "main" db of this handle */ + int nChangeset, /* Size of changeset in bytes */ + void *pChangeset, /* Changeset blob */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + sqlite3_changeset_iter *p /* Handle describing change */ + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, /* OUT: Rebase data */ + int flags /* SESSION_CHANGESETAPPLY_* flags */ +); /* ** CAPI3REF: Flags for sqlite3changeset_apply_v2 @@ -12351,11 +12953,23 @@ SQLITE_API int sqlite3changeset_apply_v2( ** database behave as if they were declared with "ON UPDATE NO ACTION ON ** DELETE NO ACTION", even if they are actually CASCADE, RESTRICT, SET NULL ** or SET DEFAULT. +** +** <dt>SQLITE_CHANGESETAPPLY_NOUPDATELOOP <dd> +** Sometimes, a changeset contains two or more update statements such that +** although after applying all updates the database will contain no +** constraint violations, no single update can be applied before the others. +** The simplest example of this is a pair of UPDATEs that have "swapped" +** two column values with a UNIQUE constraint. +** <p> +** Usually, sqlite3changeset_apply() and similar functions work hard to try +** to find a way to apply such a changeset. However, if this flag is set, +** then all such updates are considered CONSTRAINT conflicts. */ #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001 #define SQLITE_CHANGESETAPPLY_INVERT 0x0002 #define SQLITE_CHANGESETAPPLY_IGNORENOOP 0x0004 #define SQLITE_CHANGESETAPPLY_FKNOACTION 0x0008 +#define SQLITE_CHANGESETAPPLY_NOUPDATELOOP 0x0010 /* ** CAPI3REF: Constants Passed To The Conflict Handler @@ -12730,6 +13344,23 @@ SQLITE_API int sqlite3changeset_apply_v2_strm( void **ppRebase, int *pnRebase, int flags ); +SQLITE_API int sqlite3changeset_apply_v3_strm( + sqlite3 *db, /* Apply change to "main" db of this handle */ + int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */ + void *pIn, /* First arg for xInput */ + int(*xFilter)( + void *pCtx, /* Copy of sixth arg to _apply() */ + sqlite3_changeset_iter *p + ), + int(*xConflict)( + void *pCtx, /* Copy of sixth arg to _apply() */ + int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */ + sqlite3_changeset_iter *p /* Handle describing change and conflict */ + ), + void *pCtx, /* First argument passed to xConflict */ + void **ppRebase, int *pnRebase, + int flags +); SQLITE_API int sqlite3changeset_concat_strm( int (*xInputA)(void *pIn, void *pData, int *pnData), void *pInA, @@ -12821,6 +13452,232 @@ SQLITE_API int sqlite3session_config(int op, void *pArg); */ #define SQLITE_SESSION_CONFIG_STRMSIZE 1 +/* +** CAPI3REF: Configure a changegroup object +** +** Configure the changegroup object passed as the first argument. +** At present the only valid value for the second parameter is +** [SQLITE_CHANGEGROUP_CONFIG_PATCHSET]. +*/ +SQLITE_API int sqlite3changegroup_config(sqlite3_changegroup*, int, void *pArg); + +/* +** CAPI3REF: Options for sqlite3changegroup_config(). +** +** The following values may be passed as the 2nd parameter to +** sqlite3changegroup_config(). +** +** <dt>SQLITE_CHANGEGROUP_CONFIG_PATCHSET <dd> +** A changegroup object generates either a changeset or patchset. Usually, +** this is determined by whether the first call to sqlite3changegroup_add() +** is passed a changeset or a patchset. Or, if the first changes are added +** to the changegroup object using the sqlite3changegroup_change_xxx() +** APIs, then this option may be used to configure whether the changegroup +** object generates a changeset or patchset. +** +** When this option is invoked, parameter pArg must point to a value of +** type int. If the changegroup currently contains zero changes, and the +** value of the int variable is zero or greater than zero, then the +** changegroup is configured to generate a changeset or patchset, +** respectively. It is a no-op, not an error, if the changegroup is not +** configured because it has already started accumulating changes. +** +** Before returning, the int variable is set to 0 if the changegroup is +** configured to generate a changeset, or 1 if it is configured to generate +** a patchset. +*/ +#define SQLITE_CHANGEGROUP_CONFIG_PATCHSET 1 + + +/* +** CAPI3REF: Begin adding a change to a changegroup +** +** This API is used, in concert with other sqlite3changegroup_change_xxx() +** APIs, to add changes to a changegroup object one at a time. To add a +** single change, the caller must: +** +** 1. Invoke sqlite3changegroup_change_begin() to indicate the type of +** change (INSERT, UPDATE or DELETE), the affected table and whether +** or not the change should be marked as indirect. +** +** 2. Invoke sqlite3changegroup_change_int64() or one of the other four +** value functions - _null(), _double(), _text() or _blob() - one or +** more times to specify old.* and new.* values for the change being +** constructed. +** +** 3. Invoke sqlite3changegroup_change_finish() to either finish adding +** the change to the group, or to discard the change altogether. +** +** The first argument to this function must be a pointer to the existing +** changegroup object that the change will be added to. The second argument +** must be SQLITE_INSERT, SQLITE_UPDATE or SQLITE_DELETE. The third is the +** name of the table that the change affects, and the fourth is a boolean +** flag specifying whether the change should be marked as "indirect" (if +** bIndirect is non-zero) or not indirect (if bIndirect is zero). +** +** Following a successful call to this function, this function may not be +** called again on the same changegroup object until after +** sqlite3changegroup_change_finish() has been called. Doing so is an +** SQLITE_MISUSE error. +** +** The changegroup object passed as the first argument must be already +** configured with schema data for the specified table. It may be configured +** either by calling sqlite3changegroup_schema() with a database that contains +** the table, or sqlite3changegroup_add() with a changeset that contains the +** table. If the changegroup object has not been configured with a schema for +** the specified table when this function is called, SQLITE_ERROR is returned. +** +** If successful, SQLITE_OK is returned. Otherwise, if an error occurs, an +** SQLite error code is returned. In this case, if argument pzErr is non-NULL, +** then (*pzErr) may be set to point to a buffer containing a utf-8 formated, +** nul-terminated, English language error message. It is the responsibility +** of the caller to eventually free this buffer using sqlite3_free(). +*/ +SQLITE_API int sqlite3changegroup_change_begin( + sqlite3_changegroup*, + int eOp, + const char *zTab, + int bIndirect, + char **pzErr +); + +/* +** CAPI3REF: Add a 64-bit integer to a changegroup +** +** This function may only be called between a successful call to +** sqlite3changegroup_change_begin() and its matching +** sqlite3changegroup_change_finish() call. If it is called at any +** other time, it is an SQLITE_MISUSE error. Calling this function +** specifies a 64-bit integer value to be used in the change currently being +** added to the changegroup object passed as the first argument. +** +** The second parameter, bNew, specifies whether the value is to be part of +** the new.* (if bNew is non-zero) or old.* (if bNew is zero) record of +** the change under construction. If this does not match the type of change +** specified by the preceding call to sqlite3changegroup_change_begin() (i.e. +** an old.* value for an SQLITE_INSERT change, or a new.* value for an +** SQLITE_DELETE), then SQLITE_ERROR is returned. +** +** The third parameter specifies the column of the old.* or new.* record that +** the value will be a part of. If the specified table has an explicit primary +** key, then this is the index of the table column, numbered from 0 in the order +** specified within the CREATE TABLE statement. Or, if the table uses an +** implicit rowid key, then the column 0 is the rowid and the explicit columns +** are numbered starting from 1. If the iCol parameter is less than 0 or greater +** than the index of the last column in the table, SQLITE_RANGE is returned. +** +** The fourth parameter is the integer value to use as part of the old.* or +** new.* record. +** +** If this call is successful, SQLITE_OK is returned. Otherwise, if an +** error occurs, an SQLite error code is returned. +*/ +SQLITE_API int sqlite3changegroup_change_int64( + sqlite3_changegroup*, + int bNew, + int iCol, + sqlite3_int64 iVal +); + +/* +** CAPI3REF: Add a NULL to a changegroup +** +** This function is similar to sqlite3changegroup_change_int64(). Except that +** it configures the change currently under construction with a NULL value +** instead of a 64-bit integer. +*/ +SQLITE_API int sqlite3changegroup_change_null(sqlite3_changegroup*, int, int); + +/* +** CAPI3REF: Add an double to a changegroup +** +** This function is similar to sqlite3changegroup_change_int64(). Except that +** it configures the change currently being constructed with a real value +** instead of a 64-bit integer. +*/ +SQLITE_API int sqlite3changegroup_change_double(sqlite3_changegroup*, int, int, double); + +/* +** CAPI3REF: Add a text value to a changegroup +** +** This function is similar to sqlite3changegroup_change_int64(). It configures +** the currently accumulated change with a text value instead of a 64-bit +** integer. Parameter pVal points to a buffer containing the text encoded using +** utf-8. Parameter nVal may either be the size of the text value in bytes, or +** else a negative value, in which case the buffer pVal points to is assumed to +** be nul-terminated. +*/ +SQLITE_API int sqlite3changegroup_change_text( + sqlite3_changegroup*, int, int, const char *pVal, int nVal +); + +/* +** CAPI3REF: Add a blob to a changegroup +** +** This function is similar to sqlite3changegroup_change_int64(). It configures +** the currently accumulated change with a blob value instead of a 64-bit +** integer. Parameter pVal points to a buffer containing the blob. Parameter +** nVal is the size of the blob in bytes. +*/ +SQLITE_API int sqlite3changegroup_change_blob( + sqlite3_changegroup*, int, int, const void *pVal, int nVal +); + +/* +** CAPI3REF: Finish adding one-at-at-time changes to a changegroup +** +** This function may only be called following a successful call to +** sqlite3changegroup_change_begin(). Otherwise, it is an SQLITE_MISUSE error. +** +** If parameter bDiscard is non-zero, then the current change is simply +** discarded. In this case this function is always successful and SQLITE_OK +** returned. +** +** If parameter bDiscard is zero, then an attempt is made to add the current +** change to the changegroup. Assuming the changegroup is configured to +** produce a changeset (not a patchset), this requires that: +** +** * If the change is an INSERT or DELETE, then a value must be specified +** for all columns of the new.* or old.* record, respectively. +** +** * If the change is an UPDATE record, then values must be provided for +** the PRIMARY KEY columns of the old.* record, but must not be provided +** for PRIMARY KEY columns of the new.* record. +** +** * If the change is an UPDATE record, then for each non-PRIMARY KEY +** column in the old.* record for which a value has been provided, a +** value must also be provided for the same column in the new.* record. +** Similarly, for each non-PK column in the old.* record for which +** a value is not provided, a value must not be provided for the same +** column in the new.* record. +** +** * All values specified for PRIMARY KEY columns must be non-NULL. +** +** Otherwise, it is an error. +** +** If the changegroup already contains a change for the same row (identified +** by PRIMARY KEY columns), then the current change is combined with the +** existing change in the same way as for sqlite3changegroup_add(). +** +** For a patchset, all of the above rules apply except that it doesn't matter +** whether or not values are provided for the non-PK old.* record columns +** for an UPDATE or DELETE change. This means that code used to produce +** a changeset using the sqlite3changegroup_change_xxx() APIs may also +** be used to produce patchsets. +** +** If the call is successful, SQLITE_OK is returned. Otherwise, if an error +** occurs, an SQLite error code is returned. If an error is returned and +** parameter pzErr is not NULL, then (*pzErr) may be set to point to a buffer +** containing a nul-terminated, utf-8 encoded, English language error message. +** It is the responsibility of the caller to eventually free any such error +** message buffer using sqlite3_free(). +*/ +SQLITE_API int sqlite3changegroup_change_finish( + sqlite3_changegroup*, + int bDiscard, + char **pzErr +); + /* ** Make sure we can call this stuff from C++. */ @@ -13131,14 +13988,29 @@ struct Fts5PhraseIter { ** value returned by xInstCount(), SQLITE_RANGE is returned. Otherwise, ** output variable (*ppToken) is set to point to a buffer containing the ** matching document token, and (*pnToken) to the size of that buffer in -** bytes. This API is not available if the specified token matches a -** prefix query term. In that case both output variables are always set -** to 0. +** bytes. ** ** The output text is not a copy of the document text that was tokenized. ** It is the output of the tokenizer module. For tokendata=1 tables, this ** includes any embedded 0x00 and trailing data. ** +** This API may be slow in some cases if the token identified by parameters +** iIdx and iToken matched a prefix token in the query. In most cases, the +** first call to this API for each prefix token in the query is forced +** to scan the portion of the full-text index that matches the prefix +** token to collect the extra data required by this API. If the prefix +** token matches a large number of token instances in the document set, +** this may be a performance problem. +** +** If the user knows in advance that a query may use this API for a +** prefix token, FTS5 may be configured to collect all required data as part +** of the initial querying of the full-text index, avoiding the second scan +** entirely. This also causes prefix queries that do not use this API to +** run more slowly and use more memory. FTS5 may be configured in this way +** either on a per-table basis using the [FTS5 insttoken | 'insttoken'] +** option, or on a per-query basis using the +** [fts5_insttoken | fts5_insttoken()] user function. +** ** This API can be quite slow if used with an FTS5 table created with the ** "detail=none" or "detail=column" option. ** @@ -13572,3 +14444,4 @@ struct fts5_api { #endif /* _FTS5_H */ /******** End of fts5.h *********/ +#endif /* SQLITE3_H */ diff --git a/SQLite/sqlite3ext.h b/SQLite/sqlite3ext.h index ae0949b..d377778 100644 --- a/SQLite/sqlite3ext.h +++ b/SQLite/sqlite3ext.h @@ -109,7 +109,7 @@ struct sqlite3_api_routines { const char * (*libversion)(void); int (*libversion_number)(void); void *(*malloc)(int); - char * (*mprintf)(const char*,...); + char *(SQLITE_CDECL*mprintf)(const char*,...); int (*open)(const char*,sqlite3**); int (*open16)(const void*,sqlite3**); int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); @@ -130,11 +130,11 @@ struct sqlite3_api_routines { void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); void (*result_value)(sqlite3_context*,sqlite3_value*); - void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); + void *(*rollback_hook)(sqlite3*,void(*)(void*),void*); int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*, const char*,const char*),void*); void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); - char * (*xsnprintf)(int,char*,const char*,...); + char *(SQLITE_CDECL*xsnprintf)(int,char*,const char*,...); int (*step)(sqlite3_stmt*); int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*, char const**,char const**,int*,int*,int*); @@ -198,7 +198,7 @@ struct sqlite3_api_routines { int (*xthreadsafe)(void); void (*result_zeroblob)(sqlite3_context*,int); void (*result_error_code)(sqlite3_context*,int); - int (*test_control)(int, ...); + int (SQLITE_CDECL*test_control)(int, ...); void (*randomness)(int,void*); sqlite3 *(*context_db_handle)(sqlite3_context*); int (*extended_result_codes)(sqlite3*,int); @@ -218,11 +218,11 @@ struct sqlite3_api_routines { void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*), void(*xDestroy)(void*)); - int (*db_config)(sqlite3*,int,...); + int (SQLITE_CDECL*db_config)(sqlite3*,int,...); sqlite3_mutex *(*db_mutex)(sqlite3*); int (*db_status)(sqlite3*,int,int*,int*,int); int (*extended_errcode)(sqlite3*); - void (*log)(int,const char*,...); + void (SQLITE_CDECL*log)(int,const char*,...); sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64); const char *(*sourceid)(void); int (*stmt_status)(sqlite3_stmt*,int,int); @@ -232,7 +232,7 @@ struct sqlite3_api_routines { int (*wal_checkpoint)(sqlite3*,const char*); void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*); int (*blob_reopen)(sqlite3_blob*,sqlite3_int64); - int (*vtab_config)(sqlite3*,int op,...); + int (SQLITE_CDECL*vtab_config)(sqlite3*,int op,...); int (*vtab_on_conflict)(sqlite3*); /* Version 3.7.16 and later */ int (*close_v2)(sqlite3*); @@ -301,7 +301,7 @@ struct sqlite3_api_routines { int (*keyword_check)(const char*,int); sqlite3_str *(*str_new)(sqlite3*); char *(*str_finish)(sqlite3_str*); - void (*str_appendf)(sqlite3_str*, const char *zFormat, ...); + void (SQLITE_CDECL*str_appendf)(sqlite3_str*, const char *zFormat, ...); void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list); void (*str_append)(sqlite3_str*, const char *zIn, int N); void (*str_appendall)(sqlite3_str*, const char *zIn); @@ -366,6 +366,19 @@ struct sqlite3_api_routines { /* Version 3.44.0 and later */ void *(*get_clientdata)(sqlite3*,const char*); int (*set_clientdata)(sqlite3*, const char*, void*, void(*)(void*)); + /* Version 3.50.0 and later */ + int (*setlk_timeout)(sqlite3*,int,int); + /* Version 3.51.0 and later */ + int (*set_errmsg)(sqlite3*,int,const char*); + int (*db_status64)(sqlite3*,int,sqlite3_int64*,sqlite3_int64*,int); + /* Version 3.52.0 and later */ + void (*str_truncate)(sqlite3_str*,int); + void (*str_free)(sqlite3_str*); + int (*carray_bind)(sqlite3_stmt*,int,void*,int,int,void(*)(void*)); + int (*carray_bind_v2)(sqlite3_stmt*,int,void*,int,int,void(*)(void*),void*); + /* Version 3.54.0 and later */ + sqlite3_int64 (*incomplete)(const char*); + void (*result_str)(sqlite3_context*,sqlite3_str*,int); }; /* @@ -699,6 +712,19 @@ typedef int (*sqlite3_loadext_entry)( /* Version 3.44.0 and later */ #define sqlite3_get_clientdata sqlite3_api->get_clientdata #define sqlite3_set_clientdata sqlite3_api->set_clientdata +/* Version 3.50.0 and later */ +#define sqlite3_setlk_timeout sqlite3_api->setlk_timeout +/* Version 3.51.0 and later */ +#define sqlite3_set_errmsg sqlite3_api->set_errmsg +#define sqlite3_db_status64 sqlite3_api->db_status64 +/* Version 3.52.0 and later */ +#define sqlite3_str_truncate sqlite3_api->str_truncate +#define sqlite3_str_free sqlite3_api->str_free +#define sqlite3_carray_bind sqlite3_api->carray_bind +#define sqlite3_carray_bind_v2 sqlite3_api->carray_bind_v2 +/* Version 3.54.0 and later */ +#define sqlite3_incomplete sqlite3_api->incomplete +#define sqlite3_result_str sqlite3_api->result_str #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */ #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) diff --git a/UnitTest/CMakeLists.txt b/UnitTest/CMakeLists.txt index 8244000..1ec5d97 100644 --- a/UnitTest/CMakeLists.txt +++ b/UnitTest/CMakeLists.txt @@ -1,16 +1,16 @@ -# Collect all .c files in this subdirectory +# Unit tests for the async SQLite wrapper file(GLOB SUBDIR_SOURCES "*.c" "*.cpp") - -# Collect all .h files in this subdirectory file(GLOB SUBDIR_HEADERS "*.h") -# Create a library target +# Create a library target add_library(UnitTestLib STATIC ${SUBDIR_SOURCES} ${SUBDIR_HEADERS}) # Include directories for the library target_include_directories(UnitTestLib PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}") -# Add /bigobj flag for MSVC +target_link_libraries(UnitTestLib PUBLIC SQLiteLib) + +# Add /bigobj flag for MSVC if (MSVC) target_compile_options(UnitTestLib PRIVATE /bigobj) -endif() \ No newline at end of file +endif()

(predicate)); - - auto filter = dmq::xmake_shared>(std::move(funcUD), std::move(predUD)); - // DelegateMember holds the shared_ptr strongly, so the Filter lives as long as the - // connection. No lambda: wrapping one that captures a shared_ptr in a std::function - // heap-allocates on GCC/Clang (not trivially copyable), see detail::AsyncSubscriber. - return GetInstance().InternalSubscribe(topic, - dmq::DelegateMember, void(const T&)>(std::move(filter), &detail::Filter::Invoke), - thread, qos); - } - - /// @brief Publish data to a topic — delivered to every local subscriber - /// (synchronously, or asynchronously if they registered with a thread), - /// then forwarded to any remote participants interested in this topic. - /// @tparam T Message type. Must match every other Publish/Subscribe/ - /// RegisterSerializer call on this topic string. - /// @param topic Topic string to publish to. - /// @param data The message payload, copied to each subscriber/participant. - template - static void Publish(const dmq::xstring& topic, const T& data) { - GetInstance().InternalPublish(topic, data, false); - } - - /// @brief Publish data to local subscribers only — does NOT forward to - /// remote participants. - /// @tparam T Message type. Must match every other Publish/Subscribe/ - /// RegisterSerializer call on this topic string. - /// @param topic Topic string to publish to. - /// @param data The message payload, copied to each local subscriber. - /// @note Used by AddIncomingTopic to prevent relay loops when a topic is - /// both incoming and outgoing on the same node. - template - static void PublishLocal(const dmq::xstring& topic, const T& data) { - GetInstance().InternalPublish(topic, data, true); - } - - // Add a remote participant to the bus. - static void AddParticipant(std::shared_ptr participant) { - GetInstance().InternalAddParticipant(participant); - } - - static void RemoveParticipant(std::shared_ptr participant) { - GetInstance().InternalRemoveParticipant(participant); - } - - // Register a serializer for a topic (required for remote distribution). - // Use this overload if the serializer is a long-lived object (e.g., static or - // global). The DataBus does NOT take ownership. - template - static void RegisterSerializer(const dmq::xstring& topic, dmq::ISerializer& serializer) { - auto shared = std::shared_ptr(&serializer, [](void*) {}, ::dmq::stl_allocator()); - GetInstance().InternalRegisterSerializer(topic, std::move(shared)); - } - - // Register a serializer for a topic with ownership. - // Use this overload to allow the DataBus to manage the serializer's lifetime - // through a shared_ptr. - template - static void RegisterSerializer(const dmq::xstring& topic, std::shared_ptr> serializer) { - GetInstance().InternalRegisterSerializer(topic, std::static_pointer_cast(serializer)); - } - - // Register an incoming remote topic and republish received data to the local bus only. - // Uses PublishLocal — the message reaches local subscribers, the spy, and the LVC, but is - // NOT re-forwarded to remote participants. This prevents relay loops when the same topic - // is registered as both incoming and outgoing on the same node. - // - // For bridge/relay nodes that must forward incoming data to other remote participants, - // use AddRelayTopic instead. - template - static void AddIncomingTopic(const dmq::xstring& topic, dmq::DelegateRemoteId remoteId, Participant& participant, dmq::ISerializer& serializer) { - participant.RegisterHandler(remoteId, serializer, [topic](const T& data) { - PublishLocal(topic, data); - }); - } - - // Register an incoming remote topic and re-publish received data to ALL local subscribers - // AND all registered remote participants (full Publish). Use this only on bridge/relay nodes - // where the explicit intent is to forward incoming data to other remote nodes. - // - // The relay forwards only to participants that already list the topic as outgoing - // (AddRemoteTopic on the downstream participants, plus RegisterSerializer). The inbound - // participant is NOT made outgoing for the topic, so on a duplex link (one participant - // that both receives and is registered with AddParticipant) relayed data is not echoed - // back out the link it arrived on. - // - // WARNING: Using AddRelayTopic on a node that also has the same topic as an outgoing - // (RegisterSerializer + AddParticipant) AND receives from a node that also relays will - // create an infinite relay loop. Use AddIncomingTopic instead for subscriber-only nodes. - template - static void AddRelayTopic(const dmq::xstring& topic, dmq::DelegateRemoteId remoteId, Participant& participant, dmq::ISerializer& serializer) { - participant.RegisterHandler(remoteId, serializer, [topic](const T& data) { - Publish(topic, data); - }); - } - - // Register a stringifier for a topic to enable spying/logging. - template - static void RegisterStringifier(const dmq::xstring& topic, F&& func) { - dmq::UnicastDelegate ud; - if constexpr (std::is_base_of_v, std::decay_t>) - ud = std::forward(func); - else - ud = dmq::DelegateFunction(std::forward(func)); - GetInstance().InternalRegisterStringifier(topic, std::move(ud)); - } - - // Enable/Disable Last Value Cache (LVC) for a topic. - static void LastValueCache(const dmq::xstring& topic, bool enabled) { - GetInstance().InternalLastValueCache(topic, enabled); - } - - // Subscribe to all bus traffic (topic and stringified value). - // NOTE: priority is only applied when thread != nullptr; passing a non-default - // priority without a thread is a programming error and triggers FaultHandler. - template - [[nodiscard]] static dmq::ScopedConnection Monitor(F&& func, dmq::IThread* thread = nullptr, dmq::Priority priority = dmq::Priority::NORMAL) { - DMQ_ASSERT_TRUE(thread || priority == dmq::Priority::NORMAL); - - dmq::UnicastDelegate ud; - if constexpr (std::is_base_of_v, std::decay_t>) - ud = std::forward(func); - else - ud = dmq::DelegateFunction(std::forward(func)); - - DataBus& instance = GetInstance(); - - // Establish connection OUTSIDE the global DataBus lock to prevent - // lock inversion deadlocks. Signal::Connect() is already thread-safe. - if (thread) { - auto del = detail::MakeAsyncSubscriber(std::move(ud), *thread); // see detail::AsyncSubscriber - del.SetPriority(priority); - return instance.m_monitorSignal.Connect(std::move(del)); - } else { - return instance.m_monitorSignal.Connect(std::move(ud)); - } - } - - /// Fired when a message is published but has no local or remote subscribers. - template - [[nodiscard]] static dmq::ScopedConnection SubscribeUnhandled(F&& func) { - dmq::UnicastDelegate ud; - if constexpr (std::is_base_of_v, std::decay_t>) - ud = std::forward(func); - else - ud = dmq::DelegateFunction(std::forward(func)); - return GetInstance().m_unhandledSignal.Connect(std::move(ud)); - } - - /// Fired when a message is published but a technical error occurs (e.g. serialization failure). - template - [[nodiscard]] static dmq::ScopedConnection SubscribeError(F&& func) { - dmq::UnicastDelegate ud; - if constexpr (std::is_base_of_v, std::decay_t>) - ud = std::forward(func); - else - ud = dmq::DelegateFunction(std::forward(func)); - return GetInstance().m_errorSignal.Connect(std::move(ud)); - } - - // Reset the DataBus (mostly for testing). - static void ResetForTesting() { - GetInstance().InternalReset(); - } - - // Enable or disable continuous error mode (disables error latching). - static void EnableContinuousErrors(bool enable) { - GetInstance().InternalEnableContinuousErrors(enable); - } - -private: - void InternalEnableContinuousErrors(bool enable) { - dmq::LockGuard lock(m_mutex); - m_continuousErrors = enable; - for (size_t i = 0; i < m_participantCount; ++i) { - if (m_participants[i]) { - m_participants[i]->EnableContinuousErrors(enable); - } - } - } - - void InternalReportLatchedError(const dmq::xstring& topic, dmq::DelegateError error) { - bool shouldFire = false; - { - dmq::LockGuard lock(m_mutex); - uint16_t bit = uint16_t(1u << static_cast(error)); - auto& bits = m_reportedErrors[topic]; - if (!(bits & bit)) { - bits |= bit; - shouldFire = true; - } else if (m_continuousErrors) { - shouldFire = true; - } - } - if (shouldFire) { - m_errorSignal(topic, error); - } - } - - void InternalReportError(const dmq::xstring& topic, dmq::DelegateError error) { - m_errorSignal(topic, error); - } - - void InternalLastValueCache(const dmq::xstring& topic, bool enabled) { - dmq::LockGuard lock(m_mutex); - m_topicQos[topic].lastValueCache = enabled; - } - - DataBus() = default; - ~DataBus() = default; - - DataBus(const DataBus&) = delete; - DataBus& operator=(const DataBus&) = delete; - - static DataBus& GetInstance() { - static DataBus instance; - return instance; - } - - template - using SignalPtr = std::shared_ptr>; - - template - [[nodiscard]] dmq::ScopedConnection InternalSubscribe(const dmq::xstring& topic, dmq::UnicastDelegate typedFunc, dmq::IThread* thread, QoS qos) { - SignalPtr signal; - - // Wrap with min separation rate limiter if requested. Each subscriber gets its - // own independent last-delivery timestamp, so different subscribers on the same - // topic can have different (or no) rate limits without affecting each other. - if (qos.minSeparation.has_value()) { - auto minSepRep = static_cast(std::chrono::duration_cast(qos.minSeparation.value()).count()); - auto limiter = dmq::xmake_shared>(std::move(typedFunc), minSepRep); - // DelegateMember holds the shared_ptr strongly (not MakeDelegate(limiter.get(), ...), - // which would store a raw pointer), so the RateLimiter lives as long as the - // connection. No lambda/std::function, as for the Filter above. - typedFunc = dmq::DelegateMember, void(const T&)>( - std::move(limiter), &detail::RateLimiter::Invoke); - } - - T* cachedValPtr = nullptr; - std::optional cachedVal; - dmq::ScopedConnection conn; - - { - dmq::LockGuard lock(m_mutex); - - // 1. Enable LVC if requested (persists for topic lifetime until ResetForTesting) - if (qos.lastValueCache) { - m_topicQos[topic].lastValueCache = true; - } - - // 2. Get or create signal with type safety check (std::type_index) - signal = GetOrCreateSignal(topic); - } - - if (!signal) { - // Type mismatch: report through the error signal for diagnosability, - // then hard fault (wrong type is an invariant violation). - InternalReportLatchedError(topic, dmq::DelegateError::ERR_TYPE_MISMATCH); - DMQ_ASSERT(); - return {}; - } - - // 3. Establish connection OUTSIDE the lock to prevent deadlock with Timer/Signal locks. - // NOTE: There is a theoretical race where a publish happens between releasing the - // DataBus lock and acquiring the Signal lock. However, both use RecursiveMutex - // and InternalPublish also snapshots signals outside its lock, so this is - // architecturally consistent with the "lock-free dispatch" pattern used elsewhere. - using AsyncDelType = dmq::DelegateMemberAsync, void(const T&)>; - std::optional asyncDel; - if (thread) { - // No std::function here: see detail::AsyncSubscriber. - asyncDel.emplace(detail::MakeAsyncSubscriber(std::move(typedFunc), *thread)); - conn = signal->Connect(*asyncDel); - } else { - conn = signal->Connect(typedFunc); - } - - { - dmq::LockGuard lock(m_mutex); - // 4. Prepare LVC delivery if enabled and available - if (qos.lastValueCache) { - auto it = m_lastValues.find(topic); - if (it != m_lastValues.end()) { - // Check lifespan: skip delivery if the cached value is too old - bool expired = false; - if (qos.lifespan.has_value()) { - auto age = dmq::Clock::now() - it->second.timestamp; - expired = (age > qos.lifespan.value()); - } - if (!expired) { - cachedVal.emplace(*std::static_pointer_cast(it->second.value)); - cachedValPtr = &cachedVal.value(); - } - } - } - } - - // 5. Dispatch LVC outside the lock to prevent deadlocks. - // IMPORTANT: Because this happens after releasing the lock, a high-frequency - // publisher on another thread could have already sent a new value to the - // connected signal. The subscriber might receive the fresh value FIRST, - // followed by this stale LVC value — a "rewind" to an older state. - // - // Recommended mitigation: embed a monotonic sequence number in every message - // (see MessageBase) and reject stale arrivals in the subscriber using - // dmq::util::MonotonicGuard::IsNewer(). This is an application-level guard - // and is the correct fix — resolving the race inside the DataBus lock would - // require holding the lock across the async dispatch, which deadlocks. - if (cachedValPtr) { - if (asyncDel) - asyncDel->AsyncInvoke(*cachedValPtr); - else - typedFunc(*cachedValPtr); - } - - return conn; - } - - template - void InternalPublish(const dmq::xstring& topic, const T& data, bool localOnly) { - // Capture timestamp before lock acquisition for maximum accuracy and - // monotonic ordering using dmq::Clock. - auto now = dmq::Clock::now(); - uint64_t timestamp = std::chrono::duration_cast(now.time_since_epoch()).count(); - - std::shared_ptr signalVoid; - std::shared_ptr serializerPtr; - dmq::ISerializer* serializer = nullptr; - std::array, dmq::MAX_PARTICIPANTS> participantsSnapshot; - size_t participantSnapshotCount = 0; - dmq::xstring strVal = "?"; - bool hasMonitor = false; - - bool typeMismatch; - { - dmq::LockGuard lock(m_mutex); - - // 1. Type safety: verify T matches the registered type for this topic. - // Must be first — before any writes — so a mismatch never corrupts LVC. - // Also establishes the topic's type on first use (mirrors GetOrCreateSignal - // and the serializer registration paths). Without this, a topic that's - // never been subscribed to or serializer-registered would let a later - // Publish with a different U reach the LVC reuse block below and - // reinterpret a live T object as U. - typeMismatch = CheckOrEstablishType(topic, std::type_index(typeid(T))); - - if (!typeMismatch) { - // 2. Update LVC ONLY if enabled for this topic to save memory. - // NOTE: QoS lastValueCache is currently "sticky" per topic. Once enabled - // by any subscriber, it remains active for that topic until ResetForTesting(). - if (IsLvcEnabledLocked(topic)) { - if (LvcEntry* entry = FindLvcEntryLocked(topic)) { - // Avoid hot-path allocation: reuse the existing memory block by - // destroying and copy-constructing in place, rather than - // copy-assigning. This only requires T to be copy-constructible - // (the same requirement as every other T published through - // DataBus) instead of also requiring T to be copy-assignable. - // The copy is built on the stack first so that if T's copy - // constructor throws, the cached slot is untouched rather than - // left destroyed with nothing reconstructed in its place. - T* cachedObj = static_cast(entry->value.get()); - T replacement(data); - cachedObj->~T(); -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - ::new (static_cast(cachedObj)) T(std::move(replacement)); -#else - try { - ::new (static_cast(cachedObj)) T(std::move(replacement)); - } - catch (...) { - // The move constructor threw, leaving cachedObj's memory - // destroyed with no live object in it -- but the shared_ptr - // from xmake_shared still expects to destroy a live T at - // this address whenever the entry is later replaced or the - // topic is reset/torn down. Reconstruct a valid object in - // place from a fresh copy of `data` (T is already required - // to be copy-constructible for use with DataBus) so that - // invariant holds again, then propagate the original - // exception to the caller. - try { - ::new (static_cast(cachedObj)) T(data); - } - catch (...) { - // Recovery copy also failed: the slot cannot be safely - // restored to a valid state. This is an unrecoverable - // invariant violation, not a normal operational error. - DMQ_ASSERT(); - } - throw; - } -#endif - entry->timestamp = now; - } else { - // First publish for this topic: perform the initial allocation - StoreLvcEntryLocked(topic, dmq::xmake_shared(data), now); - } - } - - // 3. Prepare monitor data - hasMonitor = HasMonitorLocked(); - if (hasMonitor) { - if (auto strf = FindStringifierLocked(topic)) { - auto func = static_cast*>(strf.get()); - strVal = (*func)(data); - } - } - - // 4. Get signal and remote info. Only create Signal if there is local interest. - signalVoid = FindSignalLocked(topic); - - serializerPtr = FindSerializerLocked(topic); - if (serializerPtr) { - serializer = static_cast*>(serializerPtr.get()); - } - - // 5. Snapshot participants while locked to ensure atomicity between - // local and remote dispatch sets. - participantSnapshotCount = SnapshotParticipantsLocked(participantsSnapshot); - } - } - - if (typeMismatch) { - InternalReportLatchedError(topic, dmq::DelegateError::ERR_TYPE_MISMATCH); - DMQ_ASSERT(); - return; - } - - // 6. Dispatch Monitor outside lock to allow re-entry/prevent deadlocks - if (hasMonitor) { - DispatchMonitor(topic, strVal, timestamp); - } - - // 7. Local distribution - bool handled = false; - if (signalVoid) { - auto signal = std::static_pointer_cast>(signalVoid); - (*signal)(data); - handled = true; - } - - // 8. Remote distribution using the snapshot - if (!localOnly) { - bool anyInterested = false; - for (size_t i = 0; i < participantSnapshotCount; ++i) { - if (participantsSnapshot[i]->DispatchIfInterested(topic, data, serializer)) { - anyInterested = true; - } - } - - if (anyInterested) { - if (!serializer) { - // Topic has remote interest but no serializer — fire once per topic. - InternalReportLatchedError(topic, dmq::DelegateError::ERR_NO_SERIALIZER); - } - handled = true; - } - } - - // 9. Notify if no one received the message - if (!handled) { - m_unhandledSignal(topic); - } - } - - void InternalRemoveParticipant(std::shared_ptr participant) { - dmq::LockGuard lock(m_mutex); - for (size_t i = 0; i < m_participantCount; ++i) { - if (m_participants[i] == participant) { - m_participantErrorConnections[i].Disconnect(); - for (size_t j = i; j < m_participantCount - 1; ++j) { - m_participants[j] = std::move(m_participants[j + 1]); - m_participantErrorConnections[j] = std::move(m_participantErrorConnections[j + 1]); - } - --m_participantCount; - m_participants[m_participantCount].reset(); - break; - } - } - } - - void InternalAddParticipant(std::shared_ptr participant) { - // Establish connection OUTSIDE the global DataBus lock to prevent - // lock inversion deadlocks. Signal::Connect() is already thread-safe. - auto conn = participant->SubscribeError( - dmq::MakeDelegate(this, &DataBus::InternalReportLatchedError)); - - dmq::LockGuard lock(m_mutex); - if (m_participantCount >= dmq::MAX_PARTICIPANTS) { - // Report via the error signal for diagnosability, then hard fault — - // same "report, then fault" hybrid as the ERR_TYPE_MISMATCH sites - // above. Recursive mutex allows re-entry into InternalReportLatchedError - // while m_mutex is already held. - InternalReportLatchedError("", dmq::DelegateError::ERR_CAPACITY_EXCEEDED); - DMQ_ASSERT(); - return; - } - m_participantErrorConnections[m_participantCount] = std::move(conn); - participant->EnableContinuousErrors(m_continuousErrors); - m_participants[m_participantCount++] = participant; - } - - template - void InternalRegisterSerializer(const dmq::xstring& topic, std::shared_ptr serializer) { - bool typeMismatch; - { - dmq::LockGuard lock(m_mutex); - typeMismatch = CheckOrEstablishType(topic, std::type_index(typeid(T))); - if (!typeMismatch) { - m_serializers[topic] = std::move(serializer); - } - } - if (typeMismatch) { - InternalReportLatchedError(topic, dmq::DelegateError::ERR_TYPE_MISMATCH); - DMQ_ASSERT(); - } - } - - template - void InternalRegisterStringifier(const dmq::xstring& topic, dmq::UnicastDelegate func) { - bool typeMismatch; - { - dmq::LockGuard lock(m_mutex); - typeMismatch = CheckOrEstablishType(topic, std::type_index(typeid(T))); - if (!typeMismatch) { - // Use shared_ptr with custom deleter and stl_allocator. - // Allocate function object from fixed-block pool using xnew. - using DelegateType = dmq::UnicastDelegate; - m_stringifiers[topic] = std::shared_ptr( - dmq::xnew(std::move(func)), - [](void* ptr) { dmq::xdelete(static_cast(ptr)); }, - ::dmq::stl_allocator() - ); - } - } - if (typeMismatch) { - InternalReportLatchedError(topic, dmq::DelegateError::ERR_TYPE_MISMATCH); - DMQ_ASSERT(); - } - } - - void InternalReset() { - dmq::LockGuard lock(m_mutex); - m_signals.clear(); - for (size_t i = 0; i < m_participantCount; ++i) { - if (m_participants[i]) m_participants[i]->ResetErrors(); - m_participants[i].reset(); - m_participantErrorConnections[i].Disconnect(); - } - m_participantCount = 0; - m_serializers.clear(); - m_lastValues.clear(); - m_topicQos.clear(); - m_stringifiers.clear(); - m_typeIndices.clear(); - m_monitorSignal.Clear(); - m_unhandledSignal.Clear(); - m_errorSignal.Clear(); - m_reportedErrors.clear(); - } - - // Type-instantiated but non-templated-TYPE deleter: &DeleteSignal decays to the - // same void(*)(void*) regardless of T, so the shared_ptr control block built - // from it in GetOrCreateSignal below is not templated on T either. Same trick as - // Participant::DeleteRemoteChannel. - template - static void DeleteSignal(void* p) { - delete static_cast*>(p); - } - - template - SignalPtr GetOrCreateSignal(const dmq::xstring& topic) { - // Assume lock is held by caller - if (CheckOrEstablishType(topic, std::type_index(typeid(T)))) - return nullptr; - - if (auto sig = FindSignalLocked(topic)) { - return std::static_pointer_cast>(sig); - } - - // Erase to void* BEFORE constructing the shared_ptr (rather than - // xmake_shared>) so the control block's deduced - // pointer/deleter types are non-templated -- one control-block type is then - // shared across every distinct topic message type instead of duplicated per - // signature. Signal's own XALLOCATOR-overridden operator new already checks - // for allocation failure and calls BAD_ALLOC() internally (see xallocator.h), - // same as Participant::GetOrCreateChannelLocked's plain `new` for RemoteChannel. - auto* raw = new dmq::Signal(); - std::shared_ptr signalVoid(static_cast(raw), &DeleteSignal, ::dmq::stl_allocator()); - m_signals[topic] = signalVoid; - return std::static_pointer_cast>(signalVoid); - } - - struct LvcEntry { - std::shared_ptr value; - dmq::TimePoint timestamp; - }; - - // --- Non-templated helpers shared by every InternalPublish/InternalRegister*/ - // GetOrCreateSignal instantiation. None of this logic depends on the message - // type -- it operates purely on the already type-erased xmap storage below -- so - // living here as ordinary member functions means it's compiled once for the whole - // program instead of once per distinct topic type. "*Locked" methods assume - // m_mutex is already held by the caller. - - // Look up topic's registered type; if none yet, establish it as `expected`. - // Returns true if topic was already registered with a DIFFERENT type -- a - // programming-error type mismatch the caller must report/DMQ_ASSERT on. - bool CheckOrEstablishType(const dmq::xstring& topic, std::type_index expected) { - auto it = m_typeIndices.find(topic); - if (it != m_typeIndices.end()) - return it->second != expected; - m_typeIndices.emplace(topic, expected); - return false; - } - - bool IsLvcEnabledLocked(const dmq::xstring& topic) const { - auto it = m_topicQos.find(topic); - return it != m_topicQos.end() && it->second.lastValueCache; - } - - // Returns a pointer to topic's existing LVC entry, or nullptr if none exists yet. - // The returned pointer is only valid until the next m_lastValues mutation -- - // callers must use it within the same locked scope it was obtained in. - LvcEntry* FindLvcEntryLocked(const dmq::xstring& topic) { - auto it = m_lastValues.find(topic); - return it != m_lastValues.end() ? &it->second : nullptr; - } - - void StoreLvcEntryLocked(const dmq::xstring& topic, std::shared_ptr value, dmq::TimePoint ts) { - m_lastValues[topic] = LvcEntry{ std::move(value), ts }; - } - - bool HasMonitorLocked() const { return !m_monitorSignal.Empty(); } - - std::shared_ptr FindStringifierLocked(const dmq::xstring& topic) const { - auto it = m_stringifiers.find(topic); - return it != m_stringifiers.end() ? it->second : nullptr; - } - - std::shared_ptr FindSignalLocked(const dmq::xstring& topic) const { - auto it = m_signals.find(topic); - return it != m_signals.end() ? it->second : nullptr; - } - - std::shared_ptr FindSerializerLocked(const dmq::xstring& topic) const { - auto it = m_serializers.find(topic); - return it != m_serializers.end() ? it->second : nullptr; - } - - // Copies the live participant list into `out`, up to m_participantCount entries. - // Called while locked to keep the snapshot atomic with the rest of a publish. - size_t SnapshotParticipantsLocked(std::array, dmq::MAX_PARTICIPANTS>& out) const { - for (size_t i = 0; i < m_participantCount; ++i) - out[i] = m_participants[i]; - return m_participantCount; - } - - // Fires the monitor signal with a freshly-built SpyPacket. Called outside the - // lock, same as the code it replaces. - void DispatchMonitor(const dmq::xstring& topic, const dmq::xstring& strVal, uint64_t timestamp) { - SpyPacket packet{ topic, strVal, timestamp }; - m_monitorSignal(packet); - } - - bool m_continuousErrors = false; - dmq::RecursiveMutex m_mutex; - dmq::xmap m_reportedErrors; - dmq::xmap> m_signals; - dmq::xmap m_typeIndices; - std::array, dmq::MAX_PARTICIPANTS> m_participants{}; - size_t m_participantCount = 0; - dmq::xmap> m_serializers; - dmq::xmap m_lastValues; - dmq::xmap m_topicQos; - dmq::xmap> m_stringifiers; - dmq::Signal m_monitorSignal; - dmq::Signal m_unhandledSignal; - dmq::Signal m_errorSignal; - std::array m_participantErrorConnections; -}; - -} // namespace dmq::databus - - -#endif // DMQ_DATABUS_H diff --git a/DelegateMQ/extras/databus/DataBusQos.h b/DelegateMQ/extras/databus/DataBusQos.h deleted file mode 100644 index 23869e2..0000000 --- a/DelegateMQ/extras/databus/DataBusQos.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef DMQ_DATABUSQOS_H -#define DMQ_DATABUSQOS_H - -#include "delegate/DelegateOpt.h" -#include - -namespace dmq::databus { - -// Quality of Service settings for a topic subscription. -struct QoS { - // If true, new subscribers receive the last published value immediately on subscribe. - bool lastValueCache = false; - - // Maximum age of a cached LVC value. If the cached value is older than this duration - // when a new subscriber connects, it is considered stale and not delivered. - // Only meaningful when lastValueCache = true. - std::optional lifespan; - - // Minimum time between deliveries to this subscriber. Publishes that arrive faster - // than this interval are silently dropped for this subscriber only. Other subscribers - // with a different (or no) minSeparation are unaffected. - std::optional minSeparation; -}; - -} // namespace dmq::databus - - -#endif // DMQ_DATABUSQOS_H diff --git a/DelegateMQ/extras/databus/DeadlineSubscription.h b/DelegateMQ/extras/databus/DeadlineSubscription.h deleted file mode 100644 index ec2ebf9..0000000 --- a/DelegateMQ/extras/databus/DeadlineSubscription.h +++ /dev/null @@ -1,149 +0,0 @@ -#ifndef DMQ_DEADLINE_SUBSCRIPTION_H -#define DMQ_DEADLINE_SUBSCRIPTION_H - -/// @file DeadlineSubscription.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief RAII helper that combines a DataBus subscription with a deadline timer. -/// -/// @details -/// `DeadlineSubscription` monitors a DataBus topic and fires a user callback -/// if no message arrives within a configurable deadline window. It is built -/// entirely from existing DelegateMQ primitives — `DataBus::Subscribe`, `Timer`, -/// and `ScopedConnection` — and adds no library-internal mechanism. -/// -/// **How it works:** -/// A `Timer` is started at construction time. Every incoming message resets the -/// timer. If the timer fires before the next message arrives, the `onMissed` -/// callback is invoked. Both the data handler and the deadline callback are -/// dispatched to the same optional worker thread. -/// -/// **Lifetime:** -/// The object is non-copyable and non-movable. All resources — the DataBus -/// connection, the timer expiry connection, and the timer itself — are released -/// automatically when the object is destroyed. Members are destroyed in reverse -/// declaration order, so the DataBus connection disconnects before the timer is -/// torn down. -/// -/// When a `thread` argument is supplied, stop or join that thread before -/// destroying this object. `ScopedConnection` prevents new callbacks from being -/// queued, but any callback already waiting in the thread's message queue will -/// still execute and will access members of this object. This is the same rule -/// that applies to any async delegate that captures a raw pointer. -/// -/// **`Timer::ProcessTimers()` requirement:** -/// The deadline timer fires only when `Timer::ProcessTimers()` is called. On -/// platforms with a running `Thread`, this is typically driven by the thread's -/// internal timer. On bare-metal targets, call `ProcessTimers()` from the main -/// super-loop or a SysTick handler. If `ProcessTimers()` is not called, the -/// deadline callback silently never fires. -/// -/// **`onMissed` callback context:** -/// - With a `thread` argument: the callback is dispatched asynchronously to -/// that thread, matching the delivery context of the data handler. -/// - Without a `thread` argument: the callback fires synchronously on whatever -/// thread calls `Timer::ProcessTimers()`. On bare-metal this may be an ISR — -/// keep the callback short and non-blocking. -/// -/// **Usage:** -/// @code -/// dmq::DeadlineSubscription m_watch{ -/// "sensor/temp", -/// std::chrono::milliseconds(500), -/// [](const SensorData& d) { /* handle data */ }, -/// []() { /* deadline missed — sensor silent */ }, -/// &m_workerThread -/// }; -/// @endcode - -#include "DataBus.h" -#include "extras/util/Timer.h" -#include "delegate/UnicastDelegate.h" -#include - -namespace dmq::databus { - -template -class DeadlineSubscription { - XALLOCATOR -public: - /// Construct a deadline-monitored DataBus subscription. - /// - /// @param topic DataBus topic to subscribe to. - /// @param deadline Maximum allowed interval between deliveries. Must be > 0. - /// @param handler Called on each data delivery. Accepts any callable (lambda, - /// function pointer, member delegate, UnicastDelegate). - /// @param onMissed Called when no delivery arrives within the deadline window. - /// Accepts any callable with signature void(). - /// @param thread Optional worker thread for both callbacks. If nullptr, - /// handler fires on the publisher's thread and onMissed fires - /// on the Timer::ProcessTimers() thread. - template - DeadlineSubscription( - const dmq::xstring& topic, - dmq::Duration deadline, - H&& handler, - M&& onMissed, - dmq::IThread* thread = nullptr) - : m_deadline(deadline) - { - if constexpr (std::is_base_of_v, std::decay_t>) - m_handler = std::forward(handler); - else - m_handler = dmq::DelegateFunction(std::forward(handler)); - - if constexpr (std::is_base_of_v, std::decay_t>) - m_onMissed = std::forward(onMissed); - else - m_onMissed = dmq::DelegateFunction(std::forward(onMissed)); - - // Connect onMissed to the timer expiry signal, dispatching to thread if provided - if (thread) { - m_timerConn = m_timer.OnExpired.Connect( - dmq::util::MakeTimerDelegate(this, &DeadlineSubscription::OnTimerExpired, *thread)); - } else { - m_timerConn = m_timer.OnExpired.Connect( - dmq::MakeDelegate(this, &DeadlineSubscription::OnTimerExpired)); - } - - // Arm the timer immediately. It fires if no delivery arrives within deadline. - m_timer.Start(m_deadline, false); - - // Subscribe and reset the timer on every delivery - m_conn = DataBus::Subscribe(topic, dmq::MakeDelegate(this, &DeadlineSubscription::OnDataReceived), thread); - } - - ~DeadlineSubscription() = default; - - DeadlineSubscription(const DeadlineSubscription&) = delete; - DeadlineSubscription& operator=(const DeadlineSubscription&) = delete; - DeadlineSubscription(DeadlineSubscription&&) = delete; - DeadlineSubscription& operator=(DeadlineSubscription&&) = delete; - -private: - void OnDataReceived(const T& data) { - m_timer.Start(m_deadline, false); // reset deadline window - m_handler(data); - } - - void OnTimerExpired() { - m_onMissed(); - } - - // Declaration order controls destruction order (reverse). - // m_conn disconnects first (no more timer resets via the data lambda), - // then m_timerConn disconnects (onMissed removed from timer signal), - // then m_timer destructs (removed from global timer list). - dmq::Duration m_deadline; - dmq::UnicastDelegate m_handler; - dmq::UnicastDelegate m_onMissed; - dmq::util::Timer m_timer; - dmq::ScopedConnection m_timerConn; - dmq::ScopedConnection m_conn; -}; - -} // namespace dmq::databus - - -#endif // DMQ_DEADLINE_SUBSCRIPTION_H diff --git a/DelegateMQ/extras/databus/NetworkNode.h b/DelegateMQ/extras/databus/NetworkNode.h deleted file mode 100644 index 2628d08..0000000 --- a/DelegateMQ/extras/databus/NetworkNode.h +++ /dev/null @@ -1,527 +0,0 @@ -#ifndef DMQ_NETWORK_NODE_H -#define DMQ_NETWORK_NODE_H - -/// @file NetworkNode.h -/// @brief Generic multi-peer DataBus network node for any ITransport type. -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @details -/// NetworkNode wraps the full DataBus networking plumbing — transport setup, -/// Participant creation, reliability stacking, receive-loop thread — behind -/// a five-method API. A new user brings up a multi-process distributed DataBus -/// system by writing only a SetupNetwork() function: -/// -/// @code -/// // In your node's System.cpp: -/// void System::SetupNetwork() { -/// m_network.Start("GUI", 5010); -/// -/// m_network.Receive(topics::SAFETY_HB, RID_SAFETY_HB, serHB); -/// m_network.Receive (topics::FAULT, RID_FAULT, serFault); -/// -/// m_network.AddPeer("Safety", "127.0.0.1", 5013); -/// -/// m_network.Send(topics::GUI_HB, RID_GUI_HB, serHB); -/// m_network.Send (topics::FAULT, RID_FAULT, serFault, -/// dmq::databus::Reliability::RELIABLE); -/// } -/// // From here, use DataBus::Subscribe / DataBus::Publish normally. -/// @endcode -/// -/// A node can run several links on its one DataBus, e.g. a NetworkNode to Ethernet -/// peers and a serial link to each MCU. Each link sends only the topics registered -/// on it with Send(). A received topic reaches this node's subscribers only, unless -/// it is received with Delivery::RELAY, which also forwards it out the other links -/// that Send() it. Each peer takes two DataBus participants (reliable and -/// unreliable) out of dmq::MAX_PARTICIPANTS, shared by all links in the process. -/// -/// Topic ordering: Receive() and Send() may be called before or after Start() / -/// AddPeer() in any order. NetworkNode defers registration and applies it -/// retroactively when the participant is created. -/// -/// @tparam Transport Any ITransport-derived class with a nested Type enum -/// providing Type::PUB (sender) and Type::SUB (receiver). -/// @tparam MaxPeers Maximum remote peers (fixed allocation). Defaults to -/// dmq::NETWORK_NODE_MAX_PEERS (DMQ_NETWORK_NODE_MAX_PEERS -/// in delegatemqconfig.h). -/// @tparam MaxTopics Maximum in- or out-topics each (fixed allocation). Defaults -/// to dmq::NETWORK_NODE_MAX_TOPICS (DMQ_NETWORK_NODE_MAX_TOPICS -/// in delegatemqconfig.h). - -#include "DataBus.h" -#include "extras/util/TransportMonitor.h" -#include "extras/util/RetryMonitor.h" -#include "extras/util/ReliableTransport.h" -#include "extras/util/Timer.h" -#include "extras/util/TimerDelegate.h" -#include "extras/util/Fault.h" -#include -#include -#include -#include -#include -#include - -// Select the OS thread implementation based on the build configuration. -#if defined(DMQ_THREAD_STDLIB) - #include "port/os/stdlib/StdlibThread.h" -#elif defined(DMQ_THREAD_WIN32) - #include "port/os/win32/Win32Thread.h" -#elif defined(DMQ_THREAD_POSIX) - #include "port/os/posix/PosixThread.h" -#elif defined(DMQ_THREAD_FREERTOS) - #include "port/os/freertos/FreeRTOSThread.h" -#elif defined(DMQ_THREAD_THREADX) - #include "port/os/threadx/ThreadXThread.h" -#elif defined(DMQ_THREAD_ZEPHYR) - #include "port/os/zephyr/ZephyrThread.h" -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - #include "port/os/cmsis-rtos2/CmsisRtos2Thread.h" -#elif defined(DMQ_THREAD_QT) - #include "port/os/qt/QtThread.h" -#endif - -namespace dmq::databus { - -/// Reliability tier for outgoing topics registered via NetworkNode::Send(). -enum class Reliability { - UNRELIABLE, ///< Raw transport send — no ACK, no retry. - RELIABLE, ///< Transport send with ACK and automatic retry (RetryMonitor stack). -}; - -/// Where an incoming topic registered via NetworkNode::Receive() is delivered. -enum class Delivery { - LOCAL, ///< This node's subscribers only (DataBus::AddIncomingTopic). The default; can't loop. - RELAY, ///< This node's subscribers, and forwarded out every link that Send()s the topic - ///< (DataBus::AddRelayTopic). For gateway nodes. Wire the topic one way: Send() it - ///< on the other link(s), not on the link it arrives on, or the originator gets - ///< it back (a duplicate, not a loop, as long as it receives the topic LOCAL). -}; - -namespace detail { -/// Registers an incoming topic on a participant with the requested delivery. -/// Shared by NetworkNode and other links with the same Receive() API. -template -void AddReceivedTopic(void* serializer, const dmq::xstring& topic, dmq::DelegateRemoteId remoteId, - Participant& participant, Delivery delivery) -{ - auto& ser = *static_cast*>(serializer); - if (delivery == Delivery::RELAY) - DataBus::AddRelayTopic(topic, remoteId, participant, ser); - else - DataBus::AddIncomingTopic(topic, remoteId, participant, ser); -} -} // namespace detail - -/// @brief Generic multi-peer DataBus network node. -/// -/// All member functions are safe to call before Start() or AddPeer(); registrations -/// are stored and applied when the relevant participant is created. -template -class NetworkNode { - using TransportMonitor = dmq::util::TransportMonitor; - using RetryMonitor = dmq::util::RetryMonitor; - using ReliableTransport = dmq::util::ReliableTransport; - -public: - /// Fired when a peer's unacked-message cap is exceeded (TransportMonitor::OnCapExceeded). - /// Subscribers receive: (peerName, count). - dmq::Signal OnPeerCapExceeded; - - /// Fired when TransportMonitor::Process() can't drain a peer's expired entries - /// fast enough in one pass. Subscribers receive: (peerName, remaining). - dmq::Signal OnPeerPendingExceeded; - - /// Fired when a RELIABLE message to a peer exhausts its retry budget without - /// being ACKed — the message is now permanently abandoned. - /// Subscribers receive: (peerName, remoteId, seqNum). - dmq::Signal OnDeliveryFailed; - - /// Fired on every per-attempt send status for a RELIABLE message to a peer - /// (TransportMonitor::OnSendStatus): SUCCESS when an ACK arrives, or TIMEOUT - /// on each retry attempt before the budget is exhausted. A message may report - /// TIMEOUT several times while still being retried before either succeeding - /// or finally firing OnDeliveryFailed once -- see OnDeliveryFailed for the - /// permanent-abandonment signal this is deliberately kept separate from. - /// Subscribers receive: (peerName, remoteId, seqNum, status). - dmq::Signal OnPeerSendStatus; - - NetworkNode() = default; - ~NetworkNode() { Stop(); } - - NetworkNode(const NetworkNode&) = delete; - NetworkNode& operator=(const NetworkNode&) = delete; - - /// @brief Open the inbound transport and start the receive thread. - /// - /// @param nodeName Human-readable name used for thread naming and logging. - /// @param listenPort Port this node receives all incoming traffic on. - /// @param watchdog Watchdog timeout for the receive thread (0 = disabled). - /// @param tickPeriod Interval between receive-loop polls. - /// @return true on success. - bool Start(const char* nodeName, - uint16_t listenPort, - dmq::Duration watchdog = std::chrono::seconds(30), - dmq::Duration tickPeriod = std::chrono::milliseconds(10)) - { - dmq::LockGuard lock(m_mutex); - if (m_running) return true; - - char threadName[64]; - snprintf(threadName, sizeof(threadName), "%s_NetworkThread", nodeName); - - // Listen on all interfaces so peers on other machines can reach this node. - // (LinuxUdpTransport binds the address it's given; the other UDP ports - // already bind INADDR_ANY for SUB and ignore it.) - if (m_recvTransport.Create(Transport::Type::SUB, "0.0.0.0", listenPort) != 0) { - printf("NetworkNode [%s]: ERROR - failed to open recv port %u\n", nodeName, listenPort); - return false; - } - m_recvTransport.SetRecvTimeout(std::chrono::milliseconds(1)); - // Allow the SUB socket to send ACKs back to senders of RELIABLE messages. - // The `else if (m_sendTransport)` gate in Receive() requires a non-null - // m_sendTransport; using self means ACKs go out via sendto on this socket. - m_recvTransport.SetSendTransport(&m_recvTransport); - - m_recvParticipant = dmq::xmake_shared(m_recvTransport); - - // Apply incoming topics registered before Start(). - for (size_t i = 0; i < m_inCount; ++i) - m_inTopics[i].adder(m_inTopics[i].serializer, - m_inTopics[i].topic, - m_inTopics[i].remoteId, - *m_recvParticipant, - m_inTopics[i].delivery); - - m_thread.emplace( - threadName, 100, dmq::os::FullPolicy::FAULT, dmq::DEFAULT_DISPATCH_TIMEOUT); - - m_running = true; - m_tickPeriod = tickPeriod; - - std::optional wd = (watchdog.count() > 0) - ? std::optional{watchdog} - : std::nullopt; - m_thread->CreateThread(wd); - - m_recvConn = m_recvTimer.OnExpired.Connect( - dmq::util::MakeTimerDelegate(this, &NetworkNode::ReceiverThread, *m_thread)); - m_recvTimer.Start(tickPeriod); - - return true; - } - - /// @brief Stop all transports and exit the receive thread. - void Stop() - { - { - dmq::LockGuard lock(m_mutex); - if (!m_running) return; - m_running = false; - - m_recvTimer.Stop(); - m_recvTransport.Close(); - } - - // Exit the receive thread with no lock held. ReceiverThread() is dispatched - // asynchronously via TimerDelegate, so a tick may already be queued on - // m_thread when Stop() is called; ExitThread() blocks (join()) until the - // thread's dispatch loop drains its queue, which includes running any - // already-queued ReceiverThread() tick to completion. That tick acquires - // m_mutex too, so holding it here while blocked in join() would deadlock. - if (m_thread) - m_thread->ExitThread(); - - // Disconnect only after ExitThread() above has drained m_thread's queue. - // Neither m_recvTimer.Stop() nor Disconnect() stops a tick that's already - // running, and a ProcessTimers() emit racing Stop() can still queue one. - // Draining first guarantees no ReceiverThread() call on `this` is left - // once Stop() returns, so the NetworkNode can be destroyed safely. - m_recvConn.Disconnect(); - - dmq::LockGuard lock(m_mutex); - for (size_t i = m_peerCount; i > 0; --i) { - RemoteNode& node = m_peers[i - 1]; - if (!node.active) continue; - DataBus::RemoveParticipant(node.reliableParticipant); - DataBus::RemoveParticipant(node.unreliableParticipant); - if (node.reliableParticipant) node.reliableParticipant->SetSendThread(nullptr); - if (node.unreliableParticipant) node.unreliableParticipant->SetSendThread(nullptr); - node.capConn.Disconnect(); - node.pendingConn.Disconnect(); - node.deliveryFailedConn.Disconnect(); - node.sendStatusConn.Disconnect(); - node.rawTransport.Close(); - node.active = false; - } - m_peerCount = 0; - } - - /// @brief Add a remote peer. - /// - /// Outgoing topics already registered via Send() are applied immediately. - /// May be called before or after Start(). - /// - /// @param name Peer name (for logging, up to 47 chars). - /// @param addr IP address of the peer. - /// @param port UDP port the peer listens on. - void AddPeer(const char* name, const char* addr, uint16_t port) - { - dmq::LockGuard lock(m_mutex); - DMQ_ASSERT_TRUE(m_peerCount < MaxPeers); - - RemoteNode& node = m_peers[m_peerCount]; - size_t nameLen = strlen(name); - if (nameLen >= sizeof(node.name)) nameLen = sizeof(node.name) - 1; - memcpy(node.name, name, nameLen); - node.name[nameLen] = '\0'; - - if (node.rawTransport.Create(Transport::Type::PUB, addr, port) != 0) { - printf("NetworkNode: ERROR - failed to connect to peer '%s' at %s:%u\n", name, addr, port); - return; - } - - // Wire the transport monitor so Send() calls TransportMonitor::Add(seqNum) - // and incoming ACKs call TransportMonitor::Remove(seqNum). Without this, - // m_pending stays empty, Process() never fires timeouts, and RetryMonitor - // entries are never erased. - node.rawTransport.SetTransportMonitor(&node.transportMonitor); - - // Allow Receive() to be called on the PUB socket so ReceiverThread can drain - // ACKs. Remote peers send ACKs to our PUB socket's OS-assigned ephemeral port - // (the source address they saw when the message arrived), not to our SUB listen - // port. Without this, Remove() is never called and m_pending fills to cap. - node.rawTransport.SetRecvTransport(&node.rawTransport); - - // Two-phase init: wire the reliability stack using stable member addresses. - // RemoteNode is stored by value in std::array — elements never relocate. - node.retryMonitor.Init(node.rawTransport, node.transportMonitor); - node.reliableTransport.Init(node.rawTransport, node.retryMonitor); - - dmq::xstring peerName(name); - node.capConn = node.transportMonitor.OnCapExceeded.Connect( - dmq::MakeDelegate([this, peerName](size_t n) { - printf("NetworkNode [%s]: cap exceeded (%zu unacked messages)\n", - peerName.c_str(), n); - this->OnPeerCapExceeded(peerName, n); - })); - node.pendingConn = node.transportMonitor.OnPendingExceeded.Connect( - dmq::MakeDelegate([this, peerName](size_t n) { - printf("NetworkNode [%s]: pending exceeded (%zu entries remain)\n", - peerName.c_str(), n); - this->OnPeerPendingExceeded(peerName, n); - })); - node.deliveryFailedConn = node.retryMonitor.OnDeliveryFailed.Connect( - dmq::MakeDelegate([this, peerName](dmq::DelegateRemoteId id, uint16_t seq) { - printf("NetworkNode [%s]: delivery failed id=%u seq=%u (retries exhausted)\n", - peerName.c_str(), id, seq); - this->OnDeliveryFailed(peerName, id, seq); - })); - node.sendStatusConn = node.transportMonitor.OnSendStatus.Connect( - dmq::MakeDelegate([this, peerName](dmq::DelegateRemoteId id, uint16_t seq, TransportMonitor::Status status) { - // Only TIMEOUT is print-worthy here -- SUCCESS fires on every - // acked RELIABLE message and would flood the log under normal load. - if (status == TransportMonitor::Status::TIMEOUT) { - printf("NetworkNode [%s]: send status TIMEOUT id=%u seq=%u (retry pending)\n", - peerName.c_str(), id, seq); - } - this->OnPeerSendStatus(peerName, id, seq, status); - })); - - node.reliableParticipant = dmq::xmake_shared(node.reliableTransport); - node.unreliableParticipant = dmq::xmake_shared(node.rawTransport); - - if (m_thread.has_value()) { - node.reliableParticipant->SetSendThread(&*m_thread); - node.unreliableParticipant->SetSendThread(&*m_thread); - } - - DataBus::AddParticipant(node.reliableParticipant); - DataBus::AddParticipant(node.unreliableParticipant); - - // Apply outgoing topics registered before this peer was added. - for (size_t i = 0; i < m_outCount; ++i) { - const OutgoingTopic& out = m_outTopics[i]; - if (out.reliability == Reliability::RELIABLE) - node.reliableParticipant->AddRemoteTopic(out.topic, out.remoteId); - else - node.unreliableParticipant->AddRemoteTopic(out.topic, out.remoteId); - } - - node.active = true; - m_peerCount++; - } - - /// @brief Register a topic this node publishes to all peers. - /// - /// Registers the serializer with DataBus and maps the topic to the correct - /// reliability-tier participant on every existing and future peer. - /// - /// @param topic DataBus topic string. - /// @param remoteId Wire ID embedded in the serialized frame. - /// @param serializer Serializer instance for type T. - /// @param rel Reliability tier (default UNRELIABLE). - template - void Send(const dmq::xstring& topic, - dmq::DelegateRemoteId remoteId, - dmq::ISerializer& serializer, - Reliability rel = Reliability::UNRELIABLE) - { - dmq::LockGuard lock(m_mutex); - DMQ_ASSERT_TRUE(m_outCount < MaxTopics); - DataBus::RegisterSerializer(topic, serializer); - m_outTopics[m_outCount++] = {topic, remoteId, rel}; - - // Apply to peers already added. - for (size_t i = 0; i < m_peerCount; ++i) { - RemoteNode& node = m_peers[i]; - if (!node.active) continue; - if (rel == Reliability::RELIABLE) - node.reliableParticipant->AddRemoteTopic(topic, remoteId); - else - node.unreliableParticipant->AddRemoteTopic(topic, remoteId); - } - } - - /// @brief Register a topic this node receives from the network. - /// - /// Registers an incoming topic on the receive-side participant. May be called - /// before or after Start(); applied immediately if Start() has already run. - /// - /// @param topic DataBus topic string. - /// @param remoteId Wire ID embedded in the serialized frame. - /// @param serializer Serializer instance for type T. - /// @param delivery LOCAL (default): this node's subscribers only. RELAY: also - /// forwarded out every link that Send()s the topic, e.g. a - /// gateway passing Ethernet commands on to a serial MCU. See Delivery. - template - void Receive(const dmq::xstring& topic, - dmq::DelegateRemoteId remoteId, - dmq::ISerializer& serializer, - Delivery delivery = Delivery::LOCAL) - { - dmq::LockGuard lock(m_mutex); - DMQ_ASSERT_TRUE(m_inCount < MaxTopics); - - // Store a type-erased adder so it can be replayed when Start() creates the participant. - m_inTopics[m_inCount++] = { - topic, remoteId, static_cast(&serializer), - &detail::AddReceivedTopic, delivery - }; - - // Apply immediately if Start() has already run. - if (m_recvParticipant) - detail::AddReceivedTopic(&serializer, topic, remoteId, *m_recvParticipant, delivery); - } - -private: - void ReceiverThread() - { - dmq::LockGuard lock(m_mutex); - // Override via DMQ_NETWORK_NODE_MAX_WORK in delegatemqconfig.h. - constexpr int MAX_WORK = dmq::NETWORK_NODE_MAX_WORK; - - if (m_recvParticipant) { - for (int i = 0; i < MAX_WORK; ++i) - if (m_recvParticipant->ProcessIncoming() != 0) break; - } - - // Drain ACKs that arrived on each peer's PUB socket (ephemeral source port). - // Remote peers send ACKs to the source address they received from, which is - // our PUB socket's OS-assigned port — not our SUB listen port. Receive() on - // the PUB socket calls TransportMonitor::Remove(seqNum) when an ACK arrives, - // firing SUCCESS so RetryMonitor erases the entry. The 2 ms recv timeout on - // PUB sockets keeps each poll fast when there is nothing to receive. - for (size_t i = 0; i < m_peerCount; ++i) { - if (!m_peers[i].active) continue; - for (int k = 0; k < MAX_WORK; ++k) { - dmq::transport::DmqHeader ackHeader; - dmq::xstringstream ackStream(std::ios::in | std::ios::out | std::ios::binary); - if (m_peers[i].rawTransport.Receive(ackStream, ackHeader) != 0) break; - } - } - - // Throttled: run TransportMonitor::Process() ~10 times per second. - auto now = dmq::Clock::now(); - if (now - m_lastMonitorCheck >= std::chrono::milliseconds(100)) { - for (size_t i = 0; i < m_peerCount; ++i) { - if (m_peers[i].active) - m_peers[i].transportMonitor.Process(); - } - m_lastMonitorCheck = now; - } - } - - // ----------------------------------------------------------------------- - // RemoteNode — fully by-value storage; no heap for transport objects. - // - // std::array guarantees elements are never relocated after construction, - // so Init() references between sibling members remain valid for the - // lifetime of this NetworkNode: - // retryMonitor refs rawTransport + transportMonitor - // reliableTransport refs rawTransport + retryMonitor - // ----------------------------------------------------------------------- - struct RemoteNode { - Transport rawTransport; - TransportMonitor transportMonitor; - RetryMonitor retryMonitor; // Init(rawTransport, transportMonitor) - ReliableTransport reliableTransport; // Init(rawTransport, retryMonitor) - dmq::ScopedConnection capConn; - dmq::ScopedConnection pendingConn; - dmq::ScopedConnection deliveryFailedConn; - dmq::ScopedConnection sendStatusConn; - std::shared_ptr reliableParticipant; // xmake_shared on construction - std::shared_ptr unreliableParticipant; // xmake_shared on construction - bool active = false; - char name[48] = {}; - }; - - // Type-erased incoming-topic record. Avoids storing template arguments past - // the Receive() call site while preserving type-safe AddIncomingTopic. - using TopicAdder = void(*)(void*, const dmq::xstring&, dmq::DelegateRemoteId, Participant&, Delivery); - - struct IncomingTopic { - dmq::xstring topic; - dmq::DelegateRemoteId remoteId = 0; - void* serializer = nullptr; - TopicAdder adder = nullptr; - Delivery delivery = Delivery::LOCAL; - }; - - struct OutgoingTopic { - dmq::xstring topic; - dmq::DelegateRemoteId remoteId = 0; - Reliability reliability = Reliability::UNRELIABLE; - }; - - // Inbound path — one participant handles all incoming traffic on listenPort. - Transport m_recvTransport; - std::shared_ptr m_recvParticipant; - - // Peer table — fixed-size; no heap for transport or reliability-stack objects. - std::array m_peers{}; - size_t m_peerCount = 0; - - // Topic tables — fixed-size. - std::array m_inTopics{}; - size_t m_inCount = 0; - std::array m_outTopics{}; - size_t m_outCount = 0; - - // Receive thread. Delay construction until Start() via std::optional to - // avoid heap allocation while allowing runtime thread naming. - std::optional m_thread; - dmq::util::Timer m_recvTimer; - dmq::ScopedConnection m_recvConn; - dmq::Duration m_tickPeriod{}; - dmq::TimePoint m_lastMonitorCheck{}; - bool m_running = false; - mutable dmq::RecursiveMutex m_mutex; -}; - -} // namespace dmq::databus - -#endif // DMQ_NETWORK_NODE_H diff --git a/DelegateMQ/extras/databus/Participant.h b/DelegateMQ/extras/databus/Participant.h deleted file mode 100644 index 2ebb8a0..0000000 --- a/DelegateMQ/extras/databus/Participant.h +++ /dev/null @@ -1,421 +0,0 @@ -#ifndef DMQ_PARTICIPANT_H -#define DMQ_PARTICIPANT_H - -#include "delegate/DelegateRemote.h" -#include "delegate/DelegateAsync.h" -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "extras/dispatcher/RemoteChannel.h" -#include "extras/util/Fault.h" -#include -#include -#include -#include -#include - -namespace dmq::databus { - -// A Participant represents a remote node in the DataBus network. -// It manages the transport and the remote channels for different signatures. -// -// LIFETIME NOTE: This class assumes that the ITransport object passed to the constructor -// will outlive the Participant instance. -class Participant { - XALLOCATOR - friend class DataBus; -public: - Participant(dmq::transport::ITransport& transport) : m_transport(&transport) {} - - // Set a thread to serialize all outgoing sends. - // When set, Send() posts the channel invocation to this thread rather than - // executing inline on the caller's thread. This provides two benefits: - // 1. Thread safety: concurrent Publish() calls from multiple threads are - // safe — each send is queued rather than racing on the shared stream. - // 2. Non-blocking callers: blocking I/O in the transport cannot stall - // unrelated publishing threads. - // Without a send thread, concurrent calls to Send() for the same remote ID - // are a data race on the channel's internal stream buffer. - void SetSendThread(dmq::IThread* thread) { m_sendThread = thread; } - - /// @brief How long a received sequence number counts toward duplicate - /// detection. Defaults to dmq::SEQ_HISTORY_EXPIRY (DMQ_SEQ_HISTORY_EXPIRY_MS). - /// Set it to cover the sender's retry window if that differs from the default. - void SetSeqHistoryExpiry(dmq::Duration expiry) { - dmq::LockGuard lock(m_mutex); - m_seqHistoryExpiry = expiry; - } - - /// @brief Map a topic string to a remote ID for outbound sends to this - /// participant. - /// @details When local `DataBus::Publish()` sends to `topic`, it is - /// serialized and sent to this participant using `remoteId` on the wire. - /// Required for the sending side of remote distribution — see - /// `docs/DATABUS.md`'s "Setup Checklist". - /// @param topic Topic string to map. - /// @param remoteId Wire identifier this topic is sent as. Must match the - /// ID the receiving node registers via - /// `DataBus::AddIncomingTopic()` for the same topic. - void AddRemoteTopic(const dmq::xstring& topic, dmq::DelegateRemoteId remoteId) { - dmq::LockGuard lock(m_mutex); - m_topicToRemoteId[topic] = remoteId; - } - - // Enable or disable continuous error mode (disables error latching). -private: - void EnableContinuousErrors(bool enable) { - m_continuousErrors = enable; - } -public: - - // Subscribe to technical errors (serialization/dispatch) for this participant. - [[nodiscard]] dmq::ScopedConnection SubscribeError(std::function func) { - return m_errorSignal.Connect(dmq::MakeDelegate(std::move(func))); - } - - // Process incoming data from the transport. - // Must not be called concurrently — m_receiveMutex serializes the transport read. - // @return The result code from ITransport::Receive. - int ProcessIncoming() { - dmq::transport::DmqHeader header; - dmq::xstringstream inputStream(std::ios::in | std::ios::out | std::ios::binary); - - int result; - { - // Serialize access to the transport read - dmq::LockGuard receiveLock(m_receiveMutex); - result = m_transport->Receive(inputStream, header); - } - - if (result == 0) { - // Validate header marker and protocol version - if (!header.IsValid()) { - OnChannelError(dmq::INVALID_REMOTE_ID, dmq::DelegateError::ERR_TRANSPORT_RECEIVE, 0); - return -1; // Protocol error - } - - dmq::DelegateRemoteId id = header.GetId(); - uint16_t seqNum = header.GetSeqNum(); - - // An ACK was already handled inside the transport (it cleared the - // pending entry in the transport monitor). It has no channel, so - // it isn't an ERR_NO_DISPATCHER. - if (id == dmq::ACK_REMOTE_ID) - return 0; - - dmq::IRemoteInvoker* invoker = nullptr; - std::shared_ptr channelLifetime; // keeps channel alive across lock gap - { - dmq::LockGuard lock(m_mutex); - auto it = m_channels.find(id); - if (it != m_channels.end()) { - // Filter out duplicate messages (retries) - if (id != dmq::ACK_REMOTE_ID && - m_history[HistoryKey(header.GetNodeId(), id)].is_duplicate(seqNum, dmq::Clock::now(), m_seqHistoryExpiry)) { - return 0; // Silently drop duplicate - } - channelLifetime = it->second.channel; - invoker = it->second.invoker; - } - } - - // Invoke outside the lock to prevent deadlocks and allow re-entry - if (invoker) { - invoker->Invoke(inputStream); - } else { - OnChannelError(id, dmq::DelegateError::ERR_NO_DISPATCHER, 0); - } - } - return result; - } - - // Send data for a topic. - // If a send thread was set via SetSendThread(), the channel invocation is - // dispatched asynchronously to that thread. Otherwise it executes inline. - template - bool DispatchIfInterested(const dmq::xstring& topic, const T& data, dmq::ISerializer* serializer) { - std::shared_ptr> channel; - bool typeMismatch = false; - dmq::DelegateRemoteId remoteId = 0; - - { - dmq::LockGuard lock(m_mutex); - auto it = m_topicToRemoteId.find(topic); - if (it != m_topicToRemoteId.end()) { - if (!serializer) { - return true; - } - remoteId = it->second; - channel = GetOrCreateChannelLocked(remoteId, *serializer, typeMismatch); - } else { - return false; - } - } - - if (typeMismatch) { - OnChannelError(remoteId, dmq::DelegateError::ERR_TYPE_MISMATCH, 0); - DMQ_ASSERT(); - return true; - } - - if (channel) { - if (m_sendThread) { - // Static function, not a lambda (no capture to allocate) and not - // a member (the queued message must not hold a raw `this`; the - // Participant may be destroyed before the send thread runs it). - // The channel shared_ptr keeps the channel alive until then. - (void)dmq::MakeDelegate(&Participant::AsyncSend, *m_sendThread).AsyncInvoke(channel, data); - } else { - (*channel)(data); - } - } - return true; - } - - template - void Send(const dmq::xstring& topic, const T& data, dmq::ISerializer& serializer) { - DispatchIfInterested(topic, data, &serializer); - } - - /// @brief Internal helper to execute a remote send on a background thread. - /// @details Static so the queued message holds no `this`: the channel - /// shared_ptr is all it needs, and the Participant may be gone by then. - template - static void AsyncSend(std::shared_ptr> channel, T data) { - if (channel) { - (*channel)(data); - } - } - - /// @brief Register a local handler invoked when data arrives from this - /// participant for `remoteId`, using a `std::function`. - /// @details Required for the receiving side of remote distribution — see - /// `docs/DATABUS.md`'s "Setup Checklist". Creates the participant's - /// `RemoteChannel` for `remoteId` if one doesn't already exist. - /// @tparam T Message type this handler expects. Must match the - /// type the sending node publishes as `remoteId`, or - /// this reports ERR_TYPE_MISMATCH via - /// `Participant::SubscribeError`/`DataBus::SubscribeError` - /// and asserts. - /// @param remoteId Wire identifier to handle incoming data for. - /// @param serializer Deserializes the incoming wire bytes into a `T`. - /// @param func Called with each deserialized `T`. - template - void RegisterHandler(dmq::DelegateRemoteId remoteId, dmq::ISerializer& serializer, std::function func) { - bool typeMismatch = false; - { - dmq::LockGuard lock(m_mutex); - auto channel = GetOrCreateChannelLocked(remoteId, serializer, typeMismatch); - if (channel) { - // Use Bind() to register the callback for incoming calls. - channel->Bind(func, remoteId); - } - } - if (typeMismatch) { - OnChannelError(remoteId, dmq::DelegateError::ERR_TYPE_MISMATCH, 0); - DMQ_ASSERT(); - } - } - - /// @brief Register a local handler invoked when data arrives from this - /// participant for `remoteId`, using a raw lambda or functor. - /// @details Same behavior as the `std::function` overload above, just - /// without the `std::function` wrapping overhead for a plain callable. - /// @tparam T Message type this handler expects. Must match the - /// type the sending node publishes as `remoteId`, or - /// this reports ERR_TYPE_MISMATCH via - /// `Participant::SubscribeError`/`DataBus::SubscribeError` - /// and asserts. - /// @tparam F Callable type, deduced from `func`. Must be invocable - /// as `void(T)`. - /// @param remoteId Wire identifier to handle incoming data for. - /// @param serializer Deserializes the incoming wire bytes into a `T`. - /// @param func Called with each deserialized `T`. - template ::value>> - void RegisterHandler(dmq::DelegateRemoteId remoteId, dmq::ISerializer& serializer, F&& func) { - bool typeMismatch = false; - { - dmq::LockGuard lock(m_mutex); - auto channel = GetOrCreateChannelLocked(remoteId, serializer, typeMismatch); - if (channel) { - // Use Bind() to register the callback for incoming calls. - channel->Bind(std::forward(func), remoteId); - } - } - if (typeMismatch) { - OnChannelError(remoteId, dmq::DelegateError::ERR_TYPE_MISMATCH, 0); - DMQ_ASSERT(); - } - } - -private: - // Get the remote ID for a topic. - bool GetRemoteId(const dmq::xstring& topic, dmq::DelegateRemoteId& remoteId) { - dmq::LockGuard lock(m_mutex); - auto it = m_topicToRemoteId.find(topic); - if (it != m_topicToRemoteId.end()) { - remoteId = it->second; - return true; - } - return false; - } - - // Get the topic name for a remote ID (error path only — linear scan is fine). - bool GetTopicName(dmq::DelegateRemoteId remoteId, dmq::xstring& topic) { - dmq::LockGuard lock(m_mutex); - for (auto& [t, id] : m_topicToRemoteId) { - if (id == remoteId) { topic = t; return true; } - } - return false; - } - - template - void AttachErrorHandler(dmq::RemoteChannel* channel) { - channel->SetErrorHandler(dmq::MakeDelegate(this, &Participant::OnChannelError)); - } - - // Type-instantiated but non-templated-TYPE deleter: &DeleteRemoteChannel decays - // to the same void(*)(void*) regardless of T, so the shared_ptr control block - // built from it in GetOrCreateChannelLocked below is not templated on T either. - template - static void DeleteRemoteChannel(void* p) { - delete static_cast*>(p); - } - - void OnChannelError(dmq::DelegateRemoteId id, dmq::DelegateError error, dmq::DelegateErrorAux) { - if (error == dmq::DelegateError::SUCCESS) return; - bool shouldFire = false; - dmq::xstring topic; - { - dmq::LockGuard lock(m_mutex); - for (auto& [t, rid] : m_topicToRemoteId) { - if (rid == id) { topic = t; break; } - } - if (topic.empty()) { - // xostringstream keeps this portable: under DMQ_ALLOCATOR, xstring and - // std::string are different types, so std::to_string concatenation - // would not compile. - dmq::xostringstream os; - os << "UnknownRemoteId:" << id; - topic = os.str(); - } - uint16_t bit = uint16_t(1u << static_cast(error)); - auto& bits = m_reportedErrors[topic]; - if (!(bits & bit)) { - bits |= bit; - shouldFire = true; - } else if (m_continuousErrors) { - shouldFire = true; - } - } - if (shouldFire) - m_errorSignal(topic, error); - } - - void ResetErrors() { - dmq::LockGuard lock(m_mutex); - m_reportedErrors.clear(); - } - - struct ChannelInvoker { - std::shared_ptr channel; - dmq::IRemoteInvoker* invoker = nullptr; - }; - - template - std::shared_ptr> GetOrCreateChannelLocked(dmq::DelegateRemoteId remoteId, dmq::ISerializer& serializer, bool& outTypeMismatch) { - std::shared_ptr> channel; - outTypeMismatch = false; - - auto it = m_channels.find(remoteId); - if (it != m_channels.end()) { - // Type safety: catch remoteId reused with a different T - auto itType = m_channelTypes.find(remoteId); - if (itType != m_channelTypes.end()) { - if (itType->second != std::type_index(typeid(T))) { - outTypeMismatch = true; - return nullptr; - } - } - channel = std::static_pointer_cast>(it->second.channel); - } else { - auto* raw = new dmq::RemoteChannel(*m_transport, serializer); - - // Establish the remote ID for sending via operator(). - raw->SetRemoteId(remoteId); - - // Ensure error handler is attached to the new channel - AttachErrorHandler(raw); - - // Erase to void* BEFORE constructing the shared_ptr, so the control block's - // deduced pointer type is void (non-templated) rather than - // RemoteChannel* -- this is what lets the control block be shared - // across every distinct T instead of duplicated per signature. - std::shared_ptr channelVoid(static_cast(raw), &DeleteRemoteChannel, ::dmq::stl_allocator()); - channel = std::static_pointer_cast>(channelVoid); - - m_channels[remoteId] = { channelVoid, raw->GetEndpoint() }; - m_channelTypes.emplace(remoteId, std::type_index(typeid(T))); - } - - return channel; - } - - dmq::transport::ITransport* m_transport; - dmq::IThread* m_sendThread = nullptr; - dmq::Duration m_seqHistoryExpiry = dmq::SEQ_HISTORY_EXPIRY; - bool m_continuousErrors = false; - dmq::RecursiveMutex m_mutex; - dmq::Mutex m_receiveMutex; - dmq::xmap m_topicToRemoteId; - dmq::xmap m_channels; - dmq::xmap m_channelTypes; - dmq::xmap m_reportedErrors; - dmq::Signal m_errorSignal; - - // --- Duplicate Filtering --- - // Retries reuse the original sequence number, so a recently seen number from - // the same sender and remote ID is a duplicate. Sequence numbers are per - // sender, so history is kept per (sender node ID, remote ID); senders that - // leave their node ID unset (0) share one history per remote ID. - // Entries expire after m_seqHistoryExpiry, which covers the sender's whole - // retry window: an older match is a restarted sender reusing the number, - // not a retry. - static uint32_t HistoryKey(uint8_t nodeId, dmq::DelegateRemoteId id) { - return (static_cast(nodeId) << 16) | id; - } - - struct SeqHistory { - static constexpr size_t SIZE = DMQ_SEQ_HISTORY_SIZE; - std::array buffer; - std::array received; - std::array valid; - size_t head = 0; - - SeqHistory() { valid.fill(false); } - - bool is_duplicate(uint16_t seq, dmq::TimePoint now, dmq::Duration expiry) { - for (size_t i = 0; i < SIZE; ++i) { - if (valid[i] && buffer[i] == seq) { - if (now - received[i] < expiry) - return true; - // Expired: a new message reusing the number. Refresh this - // slot rather than take a second one for the same number. - received[i] = now; - return false; - } - } - buffer[head] = seq; - received[head] = now; - valid[head] = true; - head = (head + 1) % SIZE; - return false; - } - }; - dmq::xmap m_history; -}; - -} // namespace dmq::databus - - -#endif // DMQ_PARTICIPANT_H diff --git a/DelegateMQ/extras/databus/README.md b/DelegateMQ/extras/databus/README.md deleted file mode 100644 index 73cfb66..0000000 --- a/DelegateMQ/extras/databus/README.md +++ /dev/null @@ -1,201 +0,0 @@ -# DataBus - -The `dmq::databus::DataBus` is a central registry for topic-based communication within DelegateMQ. It provides a flexible publish-subscribe (Pub/Sub) architecture that decouples data producers from consumers. - -## DataBus vs. RemoteDispatcher — Data Distribution vs. Remote Function Invoke - -DelegateMQ has two distinct patterns for talking across threads/processes/machines. Picking the wrong one for the job shows up as awkward code, not a compile error, so it's worth knowing which is which before starting: - -| | **DataBus** (this directory) | **RemoteDispatcher** ([`extras/rpc`](../rpc/README.md)) | -|---|---|---| -| Pattern | Publish/subscribe (data distribution) | Point-to-point RPC (remote function invoke) | -| Addressing | Topic string, many-to-many | Remote ID → one specific registered endpoint | -| Who receives | Any number of subscribers (0, 1, or many) — the publisher doesn't know or care who | Exactly one endpoint per remote ID | -| Call semantics | `Publish()` is always fire-and-forget from the caller's side; delivery outcome (if any) arrives later via signals (`OnPeerSendStatus`, `OnDeliveryFailed`) | `RemoteInvokeWait()` blocks the caller until the remote ACKs or times out, returning success/failure directly — plus a fire-and-forget mode too | -| How you use it | Compose: hold an `ITransport&` (`Participant`), or instantiate `NetworkNode` — no subclassing required | Compose: hold a `dmq::rpc::RemoteDispatcher` as a member (`NetworkMgr`), connect to its `OnError`/`OnStatus`/`OnDeliveryFailed` Signals — no subclassing required | -| Reliability opt-in | Per-message — pass `Reliability::RELIABLE` or `UNRELIABLE` to `Send()` | Per-connection — the owning class decides once whether to wrap its transport in `ReliableTransport` | -| Multi-peer topology | Built in — `NetworkNode` manages any number of peers | One connection per `RemoteDispatcher` instance; the app manages multiple peers itself if it needs more than one | -| Typical use | Sensor data, telemetry, status broadcasts, state that should reach whoever's currently interested | Commands, remote function calls, request/response where the caller needs to know the call landed | - -**Rule of thumb:** if you're asking "who needs to know this happened?" reach for DataBus. If you're asking "did that specific call succeed?" reach for RemoteDispatcher. - -## Quickstart - -Three steps to send data between components: - -**1. Define a message type** -```cpp -// Any serializable struct (the Cellutron/Pumptron examples derive from their own -// MessageBase to add sequence numbers) -struct TemperatureMsg : public serialize::I { - float celsius = 0.0f; - std::ostream& write(serialize& ms, std::ostream& os) override { return ms.write(os, celsius); } - std::istream& read (serialize& ms, std::istream& is) override { return ms.read (is, celsius); } -}; -``` - -**2. Subscribe** -```cpp -// Connection owns the subscription — must stay in scope while callbacks are wanted -auto conn = dmq::databus::DataBus::Subscribe( - "sensor/temperature", - [](const TemperatureMsg& msg) { - printf("Temp: %.1f C\n", msg.celsius); - }); -``` - -**3. Publish** -```cpp -TemperatureMsg msg; -msg.celsius = 36.6f; -dmq::databus::DataBus::Publish("sensor/temperature", msg); -// → subscriber lambda fires immediately on the calling thread -``` - -> **Connection lifetime**: `Subscribe` returns a `dmq::ScopedConnection`. Letting it go out of scope silently unsubscribes — store it in a member variable. - -To dispatch to a specific thread instead of the caller's thread: -```cpp -auto conn = dmq::databus::DataBus::Subscribe( - "sensor/temperature", - dmq::MakeDelegate(this, &MySensor::OnTemp), - &m_workerThread); // callback executes on m_workerThread, not the publisher's thread -``` - -To span multiple processes over a network, see [Multi-Process Quickstart — `NetworkNode`](#multi-process-quickstart--networknode) below. - ---- - -## Features - -- **Topic-Based Communication**: Components interact via named string topics rather than direct object references. -- **Thread Dispatching**: Subscribers can specify an `dmq::IThread` to have their callbacks executed on a specific thread. -- **Quality of Service (QoS)**: Supports Last Value Cache (LVC) to provide the most recent data to new subscribers immediately upon connection. -- **Filtering**: `SubscribeFilter` allows subscribers to receive only the data that matches a specific predicate. -- **Remote Distribution**: `dmq::databus::Participant` integration allows the `dmq::databus::DataBus` to span multiple physical nodes over any supported transport (UDP, TCP, ZeroMQ, etc.). -- **Monitoring & Spying**: The `Monitor` API allows for global observation of all bus traffic, useful for logging, debugging, or UI dashboards. -- **Type Safety**: Built on C++ templates to ensure type-safe data transmission. - -## Basic Usage - -### Subscribing to a Topic - -```cpp -// Simple subscription on the current thread -auto conn = dmq::databus::DataBus::Subscribe("Temperature", [](const int& value) { - std::cout << "Temp changed: " << value << std::endl; -}); - -// Subscription dispatched to a specific worker thread -auto conn2 = dmq::databus::DataBus::Subscribe("Temperature", - dmq::MakeDelegate(&myObj, &MyClass::OnTempChange), &workerThread); -``` - -### Publishing to a Topic - -```cpp -dmq::databus::DataBus::Publish("Temperature", 25); -``` - ---- - -## Multi-Process Quickstart — `NetworkNode` - -`dmq::databus::NetworkNode` is a ready-made multi-peer network layer. -It handles transport setup, Participant creation, reliability stacking, and the -receive-loop thread. A new user writes only a `SetupNetwork()` function. - -### Minimal two-node example - -**`shared/Topics.h`** — shared between all nodes: -```cpp -#include "DelegateMQ.h" -#include "messages/TemperatureMsg.h" -#include "messages/AlarmMsg.h" - -namespace myapp { - // Remote IDs — unique per message type, consistent across nodes - static constexpr dmq::DelegateRemoteId RID_TEMPERATURE = 1; - static constexpr dmq::DelegateRemoteId RID_ALARM = 2; - - namespace topics { - static constexpr const char* TEMPERATURE = "sensor/temperature"; - static constexpr const char* ALARM = "sys/alarm"; - } - - // Serializer instances (defined in one .cpp, extern everywhere else) - extern dmq::serialization::serializer::Serializer serTemp; - extern dmq::serialization::serializer::Serializer serAlarm; -} -``` - -**`node_a/System.cpp`** — the sensor node (publishes temperature, receives alarms): -```cpp -#include "extras/databus/NetworkNode.h" -#include "port/transport/win32-udp/Win32UdpTransport.h" // or LinuxUdpTransport -#include "Topics.h" - -using Network = dmq::databus::NetworkNode; -static Network g_net; - -void SetupNetwork() { - g_net.Start("SensorNode", /*listenPort=*/6000); - - g_net.Receive(myapp::topics::ALARM, myapp::RID_ALARM, myapp::serAlarm); - - g_net.AddPeer("DisplayNode", "127.0.0.1", /*udpPort=*/6001); - - g_net.Send(myapp::topics::TEMPERATURE, myapp::RID_TEMPERATURE, - myapp::serTemp); -} - -// From here: DataBus::Publish(topics::TEMPERATURE, reading) routes -// automatically over the network to DisplayNode. -``` - -**`node_b/System.cpp`** — the display node (receives temperature, publishes alarms): -```cpp -void SetupNetwork() { - g_net.Start("DisplayNode", /*listenPort=*/6001); - - g_net.Receive(myapp::topics::TEMPERATURE, myapp::RID_TEMPERATURE, - myapp::serTemp); - - g_net.AddPeer("SensorNode", "127.0.0.1", /*udpPort=*/6000); - - g_net.Send(myapp::topics::ALARM, myapp::RID_ALARM, myapp::serAlarm, - dmq::databus::Reliability::RELIABLE); // ACK + retry -} -``` - -### Key points - -- **Order-independent**: `Receive()` and `Send()` may be called before or after `Start()` / `AddPeer()`. Registrations are stored and applied retroactively. -- **Reliability tiers**: `Reliability::UNRELIABLE` (default) sends raw UDP; `Reliability::RELIABLE` adds ACK + automatic retry via `RetryMonitor`. -- **Transport-agnostic**: Pass any `ITransport`-derived type as the template argument — `Win32UdpTransport`, `LinuxUdpTransport`, `ZephyrUdpTransport`, etc. -- **Local delivery by default**: a topic registered with `Receive()` reaches this node's subscribers only. Pass `Delivery::RELAY` (`Receive(topic, id, ser, Delivery::RELAY)`) on a gateway node to also forward it out every other link that `Send()`s it. See [Relay Nodes](../../../../docs/DATABUS.md#relay-nodes). -- **Fixed allocation**: `MaxPeers` and `MaxTopics` template parameters control pre-allocated capacity. No heap for transport objects (`RemoteNode` members are by-value in `std::array`). -- **Participant budget**: each peer registers two participants with the DataBus (reliable and unreliable), and every link in the process draws from the same `dmq::MAX_PARTICIPANTS` (`DMQ_MAX_PARTICIPANTS`, default 8). The defaults already meet: 4 peers × 2 = 8. A process with more links needs a larger `DMQ_MAX_PARTICIPANTS`; going over reports `ERR_CAPACITY_EXCEEDED` and calls `FaultHandler`. -- **`Participant` allocation**: Uses `xmake_shared` — fixed-block allocator on embedded targets. -- **Error & status signals**: `OnDeliveryFailed(peerName, remoteId, seqNum)` fires once when a RELIABLE message exhausts its retry budget; `OnPeerSendStatus(peerName, remoteId, seqNum, status)` fires on every per-attempt outcome (SUCCESS or TIMEOUT) leading up to that, so an app can tell "still retrying" apart from "permanently abandoned"; `OnPeerCapExceeded`/`OnPeerPendingExceeded(peerName, count)` are backpressure health signals. None of these overlap `DataBus::SubscribeError` — see [Error & Status Reporting](../../../../docs/DATABUS.md#error--status-reporting) in the full DataBus doc for the complete picture (including `DelegateError` codes) and usage examples. - -### Template parameters - -```cpp -template // maximum Send() or Receive() calls each -class NetworkNode; -``` - -`dmq::NETWORK_NODE_MAX_PEERS` (default 4) and `dmq::NETWORK_NODE_MAX_TOPICS` (default 16) come from `DMQ_NETWORK_NODE_MAX_PEERS` / `DMQ_NETWORK_NODE_MAX_TOPICS` in `DelegateMQConfig_Default.h` — override there to change the default for all instantiations, or pass explicit template arguments to override per-instantiation (e.g. `NetworkNode`). - ---- - -For the range of network topologies `NetworkNode` supports (star, mesh, broadcast/multicast, heterogeneous-transport gateways, broker-mediated, etc.), see [Topologies](../../../../docs/DATABUS.md#topologies) in the full DataBus doc. - ---- - -## Internal Mechanics - -The `dmq::databus::DataBus` utilizes DelegateMQ's `dmq::MulticastDelegate` system internally. When you `Publish`, the bus identifies all local and remote subscribers for that topic and invokes them. Remote subscribers are handled via `dmq::IDispatcher` and `dmq::transport::ITransport` layers, making the network boundary transparent to the application logic. diff --git a/DelegateMQ/extras/databus/SpyPacket.h b/DelegateMQ/extras/databus/SpyPacket.h deleted file mode 100644 index d127fce..0000000 --- a/DelegateMQ/extras/databus/SpyPacket.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef DMQ_SPY_PACKET_H -#define DMQ_SPY_PACKET_H - -#include "delegate/DelegateOpt.h" -#include "port/serialize/serialize/msg_serialize.h" - -namespace dmq::databus { - -/// @brief Standardized packet containing bus traffic metadata. -/// @details This struct is passed to DataBus::Monitor subscribers and is -/// designed to be serialized for transmission to external diagnostic tools. -/// -/// The timestamp_us field uses dmq::Clock::now(), which typically provides -/// monotonic time since boot. -struct SpyPacket : public ::serialize::I { - XALLOCATOR - SpyPacket() = default; - virtual ~SpyPacket() = default; - SpyPacket(const dmq::xstring& t, const dmq::xstring& v, uint64_t ts, const dmq::xstring& id = "") - : topic(t), value(v), timestamp_us(ts), nodeId(id) {} - - dmq::xstring topic; ///< The name of the data topic. - dmq::xstring value; ///< Stringified representation of the data (or "?" if no stringifier registered). - uint64_t timestamp_us = 0; ///< Microseconds (usually since boot) when the message was published. - dmq::xstring nodeId; ///< Unique identifier for the sending node. - - std::ostream& write(::serialize& ms, std::ostream& os) override { - ms.write(os, topic); - ms.write(os, value); - ms.write(os, timestamp_us); - return ms.write(os, nodeId); - } - - std::istream& read(::serialize& ms, std::istream& is) override { - ms.read(is, topic); - ms.read(is, value); - ms.read(is, timestamp_us); - return ms.read(is, nodeId); - } -}; -} // namespace dmq::databus - - -#endif // DMQ_SPY_PACKET_H diff --git a/DelegateMQ/extras/dispatcher/Dispatcher.h b/DelegateMQ/extras/dispatcher/Dispatcher.h deleted file mode 100644 index 327c7b7..0000000 --- a/DelegateMQ/extras/dispatcher/Dispatcher.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef DISPATCHER_H -#define DISPATCHER_H - -/// @file Dispatcher.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief The bridge between the serialization layer and the physical transport layer. -/// -/// @details -/// The `Dispatcher` class is responsible for packaging serialized function arguments -/// into a valid DelegateMQ message and handing it off to the transport. -/// -/// **Key Responsibilities:** -/// 1. **Message Construction:** Creates the protocol header (`DmqHeader`) containing -/// the Remote ID and a monotonic Sequence Number. -/// 2. **Stream Management:** Validates that the output stream is compatible -/// (expects `xostringstream`). -/// 3. **Dispatch:** Forwards the header and the serialized payload (stream) to the -/// registered `ITransport::Send()` method. -/// -/// **Usage:** -/// This class is typically used internally by `DelegateRemote` to finalize a remote -/// procedure call before transmission. - -#include "delegate/IDispatcher.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransport.h" -#include -#include - -namespace dmq { - -/// @brief Dispatcher sends data to the transport for transmission to the endpoint. -class Dispatcher : public dmq::IDispatcher -{ - XALLOCATOR -public: - Dispatcher() = default; - ~Dispatcher() override = default; - - void SetTransport(transport::ITransport* transport) - { - m_transport = transport; - } - - // Send argument data to the transport - int Dispatch(dmq::xostringstream& os, dmq::DelegateRemoteId id, uint16_t* outSeqNum = nullptr) override - { - dmq::xostringstream* ss = &os; - - if (m_transport) - { - uint16_t seq = m_seqNum.fetch_add(1); - if (outSeqNum) *outSeqNum = seq; - transport::DmqHeader header(id, seq); - int err = m_transport->Send(*ss, header); - - // Reset the stream content and error state for the next use. - // This prevents the stream from growing indefinitely. - ss->str(dmq::xstring()); - ss->clear(); - ss->seekp(0); - - LOG_INFO("Dispatcher::Dispatch id={} seqNum={} err={}", header.GetId(), header.GetSeqNum(), err); - return err; - } - return -1; - } - -private: - transport::ITransport* m_transport = nullptr; - inline static std::atomic m_seqNum{0}; -}; - -} // namespace dmq - - -#endif \ No newline at end of file diff --git a/DelegateMQ/extras/dispatcher/README.md b/DelegateMQ/extras/dispatcher/README.md deleted file mode 100644 index 38ad4dc..0000000 --- a/DelegateMQ/extras/dispatcher/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# Dispatcher Layer - -This directory contains the dispatch logic for **DelegateMQ**, serving as the critical bridge between the high-level serialization layer and the low-level physical transport. - -## Overview - -The `dmq::Dispatcher` is responsible for taking the serialized payload (function arguments) and preparing it for transmission over the network or IPC link. It decouples the "what" (serialized data) from the "how" (transport mechanism). - -## Key Components - -* **`Dispatcher.h`**: The concrete implementation of the `dmq::IDispatcher` interface. -* **`RemoteChannel.h`**: An aggregator that owns a `dmq::Dispatcher`, an `dmq::xostringstream` (serialization buffer), and borrows an `dmq::ISerializer` for a single function signature. Use `dmq::RemoteChannel` to configure `dmq::DelegateMemberRemote` endpoints without manually wiring each component. - -### Responsibilities - -#### dmq::Dispatcher -1. **Protocol Framing**: It constructs the `dmq::transport::DmqHeader` for every message, assigning the correct **Remote ID** and generating a monotonic **Sequence Number**. -2. **Stream Validation**: It ensures the output stream (`dmq::xostringstream`) contains valid data before transmission. -3. **Transport Handoff**: It forwards the framed message (Header + Payload) to the registered `dmq::transport::ITransport` instance for physical transmission. - -#### dmq::RemoteChannel -`dmq::RemoteChannel` owns a `dmq::DelegateFunctionRemote` internally and handles all wiring automatically. Call `Bind()` once to configure the channel (for receiving), or pass the ID to the constructor (for sending), then invoke it with `operator()`. - -```cpp -// Create one channel per message signature -dmq::RemoteChannel alarmChannel(transport, alarmSerializer); - -// Bind a member function and remote ID — channel owns the delegate internally -alarmChannel.Bind(this, &MyClass::ForwardAlarm, ALARM_MSG_ID); - -// Optionally register an error handler -alarmChannel.SetErrorHandler(dmq::MakeDelegate(this, &MyClass::OnError)); - -// Register the receive endpoint with the dmq::rpc::RemoteDispatcher -dispatcher.RegisterEndpoint(ALARM_MSG_ID, alarmChannel); - -// Invoke (fire-and-forget) -AlarmMsg msg; AlarmNote note; -alarmChannel(msg, note); - -// Or invoke with blocking wait -bool ok = dispatcher.RemoteInvokeWait(alarmChannel, msg, note); -``` - -Key accessors: -- `Bind(obj, func, id)` — binds a member function and configures all internal plumbing. -- `operator()(args...)` — invokes (sends) the remote message. -- `GetEndpoint()` — returns `dmq::IRemoteInvoker*` for `RemoteDispatcher::RegisterEndpoint()`. -- `GetError()` / `GetRemoteId()` — query last error and remote ID. -- `SetErrorHandler(delegate)` — register an error notification callback. - -> **Legacy accessors** (`GetDispatcher()`, `GetSerializer()`, `GetStream()`) remain available for code that manually wires a `dmq::DelegateMemberRemote`. diff --git a/DelegateMQ/extras/dispatcher/RemoteChannel.h b/DelegateMQ/extras/dispatcher/RemoteChannel.h deleted file mode 100644 index 1b4498e..0000000 --- a/DelegateMQ/extras/dispatcher/RemoteChannel.h +++ /dev/null @@ -1,391 +0,0 @@ -#ifndef REMOTE_CHANNEL_H -#define REMOTE_CHANNEL_H - -/// @file RemoteChannel.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Aggregates transport, serializer, dispatcher, and stream into a single -/// object, mirroring how `IThread`/`Thread` hides async delegate wiring. -/// -/// @details -/// Setting up a remote delegate currently requires three separate objects: -/// @code -/// Dispatcher dispatcher; -/// dispatcher.SetTransport(&transport); -/// Serializer serializer; -/// dmq::xostringstream stream(std::ios::in | std::ios::out | std::ios::binary); -/// -/// DelegateFreeRemote remote(REMOTE_ID); -/// remote.SetSerializer(&serializer); -/// remote.SetDispatcher(&dispatcher); -/// remote.SetStream(&stream); -/// @endcode -/// -/// `RemoteChannel` collapses this into one setup object: -/// @code -/// MyTransport transport; -/// Serializer serializer; -/// RemoteChannel channel(transport, serializer); -/// -/// // Mirrors the async pattern exactly: -/// auto async = MakeDelegate(&MyFunc, thread); // async -/// auto remote = MakeDelegate(&MyFunc, REMOTE_ID, channel); // remote -/// @endcode -/// -/// @tparam Sig The function signature (e.g. `void(int, float)`) that matches both -/// the serializer and the remote delegates that use this channel. One channel -/// instance is required per distinct function signature. - -#include "Dispatcher.h" -#include "delegate/DelegateRemote.h" -#include "delegate/Signal.h" -#include "port/transport/common/ITransport.h" - -namespace dmq { - -template -class RemoteChannel; // Not defined - -/// @brief Aggregates dispatcher, stream, serializer, and delegate binding for a single -/// function signature. The canonical way to configure a remote endpoint. -/// -/// @details `RemoteChannel` is the single object a user needs to declare per message -/// signature. It owns the `Dispatcher`, the serialization stream, and the internal -/// `DelegateFunctionRemote` that handles both sending and receiving. -/// -/// **Receive-side usage (preferred):** -/// @code -/// // Declare per signature — one channel replaces channel + separate delegate -/// std::optional> m_alarmChannel; -/// -/// // In Create(): -/// m_alarmChannel.emplace(GetRecvTransport(), m_alarmSer); -/// m_alarmChannel->Bind(this, &MyClass::OnAlarm, ALARM_ID); -/// m_alarmChannel->SetErrorHandler(MakeDelegate(this, &MyClass::OnError)); -/// RegisterEndpoint(ALARM_ID, m_alarmChannel->GetEndpoint()); -/// @endcode -/// -/// **Send-side usage — no Bind() required:** -/// @code -/// m_alarmChannel.emplace(GetSendTransport(), m_alarmSer, ALARM_ID); -/// -/// // Send (fire-and-forget): -/// (*m_alarmChannel)(msg); -/// -/// // Send (blocking wait): -/// RemoteInvokeWait(*m_alarmChannel, msg); -/// @endcode -/// -/// **Legacy MakeDelegate pattern (still supported):** -/// @code -/// auto d = MakeDelegate(&MyFunc, REMOTE_ID, channel); -/// @endcode -/// -/// `RemoteChannel` is non-copyable because it owns mutable stream state and the internal -/// delegate holds raw pointers into the channel. -/// -/// @tparam RetType The return type of the remote function. -/// @tparam Args The argument types of the remote function. -template -class RemoteChannel -{ - XALLOCATOR -public: - /// @brief Construct a RemoteChannel. - /// @details A send-only channel needs no `Bind()` — pass the remote ID here and - /// invoke the channel directly. The receive side must invoke `Bind()` to attach the - /// target function invoked on message arrival (`Bind()` overwrites the ID with the - /// same value). - /// @param[in] transport The transport used to send serialized data. Caller owns it. - /// @param[in] serializer The serializer matching the delegate signature. Caller owns it. - /// @param[in] id The remote delegate identifier shared with the receiver. - /// Optional for receive channels where `Bind()` supplies the ID. - RemoteChannel(transport::ITransport& transport, dmq::ISerializer& serializer, - DelegateRemoteId id = INVALID_REMOTE_ID) - : m_stream(std::ios::in | std::ios::out | std::ios::binary) - , m_serializer(&serializer) - { - m_dispatcher.SetTransport(&transport); - m_delegate.SetRemoteId(id); - m_delegate.SetDispatcher(&m_dispatcher); - m_delegate.SetSerializer(m_serializer); - m_delegate.SetStream(&m_stream); - m_delegate.SetSendMutex(&m_sendMutex); - } - - ~RemoteChannel() = default; - - // Non-copyable: owns stream state and internal delegate holds raw pointers into this object. - RemoteChannel(const RemoteChannel&) = delete; - RemoteChannel& operator=(const RemoteChannel&) = delete; - - // ----------------------------------------------------------------------- - // Delegate binding — preferred user-facing API (Item 2 / Item 4) - // ----------------------------------------------------------------------- - - /// @brief Bind a non-const member function as the receive-side handler. - /// @details Wires the internal delegate (dispatcher, serializer, stream) and sets - /// the target function in one call. Call this once in your Create()/Initialize(). - /// @param[in] object Raw pointer to the target object. - /// @param[in] func The non-const member function to call on receive. - /// @param[in] id The remote delegate identifier shared with the sender. - template - void Bind(TClass* object, RetType(TClass::* func)(Args...), DelegateRemoteId id) { - m_delegate.Bind([object, func](Args... args) -> RetType { - return (object->*func)(args...); - }, id); - ReconnectDelegate(); - } - - /// @brief Bind a const member function as the receive-side handler. - template - void Bind(const TClass* object, RetType(TClass::* func)(Args...) const, DelegateRemoteId id) { - m_delegate.Bind([object, func](Args... args) -> RetType { - return (object->*func)(args...); - }, id); - ReconnectDelegate(); - } - - /// @brief Bind a `std::function` as the receive-side handler. - void Bind(std::function func, DelegateRemoteId id) { - m_delegate.Bind(func, id); - ReconnectDelegate(); - } - - /// @brief Bind a raw lambda or functor as the receive-side handler. - template ::value>> - void Bind(F&& func, DelegateRemoteId id) { - m_delegate.Bind(std::forward(func), id); - ReconnectDelegate(); - } - - /// @brief Invoke the channel (fire-and-forget send). - /// @pre A remote ID is set: passed to the constructor, or set by SetRemoteId() or - /// Bind(). A send-only channel needs no Bind(). - /// Thread-safe: the internal delegate holds `m_sendMutex` while it sends. - void operator()(Args... args) { - m_delegate(std::forward(args)...); - } - - /// @brief Register an error handler delegate. - template - void SetErrorHandler(Handler&& handler) { - m_delegate.SetErrorHandler(std::forward(handler)); - } - - /// @brief Set the remote ID for outbound messages. - /// @param[in] id The remote delegate identifier. - void SetRemoteId(DelegateRemoteId id) noexcept { m_delegate.SetRemoteId(id); } - - /// @brief The remote ID set by the most recent Bind() or SetRemoteId() call. - DelegateRemoteId GetRemoteId() noexcept { return m_delegate.GetRemoteId(); } - - /// @brief The error status of the most recent invocation. - DelegateError GetError() noexcept { return m_delegate.GetError(); } - - /// @brief The sequence number assigned to the most recent send. - uint16_t GetLastSeqNum() const noexcept { return m_delegate.GetLastSeqNum(); } - - /// @brief Returns the internal delegate as an IRemoteInvoker* for RegisterEndpoint(). - IRemoteInvoker* GetEndpoint() noexcept { return &m_delegate; } - -private: - template - friend auto MakeDelegate(R(*)(A...), DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(C*, R(C::*)(A...), DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(C*, R(C::*)(A...) const, DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(const C*, R(C::*)(A...) const, DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(std::shared_ptr, R(C::*)(A...), DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(std::shared_ptr, R(C::*)(A...) const, DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(std::function, DelegateRemoteId, RemoteChannel&); - - template - friend auto MakeDelegate(F_&&, DelegateRemoteId, RemoteChannel&); - - /// @internal Used by MakeDelegate overloads. Prefer Bind() in application code. - dmq::IDispatcher* GetDispatcher() noexcept { return &m_dispatcher; } - - /// @internal Used by MakeDelegate overloads. Prefer Bind() in application code. - dmq::ISerializer* GetSerializer() noexcept { return m_serializer; } - - /// @internal Used by MakeDelegate overloads. Prefer Bind() in application code. - dmq::xostringstream& GetStream() noexcept { return m_stream; } - - /// @internal Used by MakeDelegate overloads. Every delegate sharing `m_stream` - /// must hold this mutex while it sends. - dmq::Mutex& GetSendMutex() noexcept { return m_sendMutex; } - -private: - void ReconnectDelegate() { - m_delegate.SetDispatcher(&m_dispatcher); - m_delegate.SetSerializer(m_serializer); - m_delegate.SetStream(&m_stream); - m_delegate.SetSendMutex(&m_sendMutex); - } - - /// Guards `m_stream` (and the dispatcher) for the channel's own delegate and - /// every delegate made from it by MakeDelegate(). - dmq::Mutex m_sendMutex; - Dispatcher m_dispatcher; - dmq::xostringstream m_stream; - dmq::ISerializer* m_serializer = nullptr; - DelegateFunctionRemote m_delegate; -}; - -/// @brief C++17 deduction guide — lets the compiler deduce `Sig` from the serializer type. -/// @details Enables `RemoteChannel channel(transport, serializer)` and -/// `RemoteChannel channel(transport, serializer, id)` without an explicit template argument. -template -RemoteChannel(transport::ITransport&, dmq::ISerializer&, DelegateRemoteId = INVALID_REMOTE_ID) -> RemoteChannel; - -// ---- MakeDelegate overloads for RemoteChannel ---------------------------------- -// -// These mirror the MakeDelegate(func, thread) async overloads exactly, but accept -// a RemoteChannel instead of an IThread, wiring up serializer, dispatcher, and -// stream in one step. - -/// @brief Creates a remote delegate bound to a free function via a RemoteChannel. -/// @param[in] func The free function to bind. -/// @param[in] id The remote delegate identifier shared with the receiver. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateFreeRemote` ready to invoke remotely. -template -auto MakeDelegate(RetType(*func)(Args...), DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateFreeRemote d(func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a non-const member function via a RemoteChannel. -/// @param[in] object Raw pointer to the target object instance. -/// @param[in] func The non-const member function to bind. -/// @param[in] id The remote delegate identifier. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateMemberRemote`. -template -auto MakeDelegate(TClass* object, RetType(TClass::* func)(Args...), DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateMemberRemote d(object, func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a const member function via a RemoteChannel. -/// @param[in] object Raw pointer to the target object instance. -/// @param[in] func The const member function to bind. -/// @param[in] id The remote delegate identifier. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateMemberRemote`. -template -auto MakeDelegate(TClass* object, RetType(TClass::* func)(Args...) const, DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateMemberRemote d(object, func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a const member function on a const object. -/// @param[in] object Raw const pointer to the target object instance. -/// @param[in] func The const member function to bind. -/// @param[in] id The remote delegate identifier. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateMemberRemote`. -template -auto MakeDelegate(const TClass* object, RetType(TClass::* func)(Args...) const, DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateMemberRemote d(object, func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a non-const member function via shared_ptr. -/// @param[in] object Shared pointer to the target object instance. -/// @param[in] func The non-const member function to bind. -/// @param[in] id The remote delegate identifier. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateMemberRemote`. -template -auto MakeDelegate(std::shared_ptr object, RetType(TClass::* func)(Args...), DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateMemberRemote d(object, func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a const member function via shared_ptr. -/// @param[in] object Shared pointer to the target object instance. -/// @param[in] func The const member function to bind. -/// @param[in] id The remote delegate identifier. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateMemberRemote`. -template -auto MakeDelegate(std::shared_ptr object, RetType(TClass::* func)(Args...) const, DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateMemberRemote d(object, func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a `std::function` via a RemoteChannel. -/// @param[in] func The `std::function` to bind. -/// @param[in] id The remote delegate identifier. -/// @param[in] channel The channel that provides dispatcher, serializer, and stream. -/// @return A fully configured `DelegateFunctionRemote`. -template -auto MakeDelegate(std::function func, DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateFunctionRemote d(func, id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -/// @brief Creates a remote delegate bound to a raw lambda or functor via a RemoteChannel. -template ::value>> -auto MakeDelegate(F&& func, DelegateRemoteId id, RemoteChannel& channel) -{ - DelegateFunctionRemote d(std::forward(func), id); - d.SetDispatcher(channel.GetDispatcher()); - d.SetSerializer(channel.GetSerializer()); - d.SetStream(&channel.GetStream()); - d.SetSendMutex(&channel.GetSendMutex()); - return d; -} - -} // namespace dmq - -#endif // REMOTE_CHANNEL_H diff --git a/DelegateMQ/extras/rpc/README.md b/DelegateMQ/extras/rpc/README.md deleted file mode 100644 index d929f8c..0000000 --- a/DelegateMQ/extras/rpc/README.md +++ /dev/null @@ -1,81 +0,0 @@ -# RPC Layer - -This directory contains **DelegateMQ**'s point-to-point RPC pattern: synchronous or fire-and-forget calls to a specific remote endpoint, as opposed to the topic-based publish/subscribe pattern in [`extras/databus`](../databus/README.md). - -## RemoteDispatcher vs. DataBus — Remote Function Invoke vs. Data Distribution - -DelegateMQ has two distinct patterns for talking across threads/processes/machines. Picking the wrong one for the job shows up as awkward code, not a compile error, so it's worth knowing which is which before starting: - -| | **RemoteDispatcher** (this directory) | **DataBus** ([`extras/databus`](../databus/README.md)) | -|---|---|---| -| Pattern | Point-to-point RPC (remote function invoke) | Publish/subscribe (data distribution) | -| Addressing | Remote ID → one specific registered endpoint | Topic string, many-to-many | -| Who receives | Exactly one endpoint per remote ID | Any number of subscribers (0, 1, or many) — the publisher doesn't know or care who | -| Call semantics | `RemoteInvokeWait()` blocks the caller until the remote ACKs or times out, returning success/failure directly — plus a fire-and-forget mode too | `Publish()` is always fire-and-forget from the caller's side; delivery outcome (if any) arrives later via `NetworkNode` signals (`OnPeerSendStatus`, `OnDeliveryFailed`) | -| How you use it | Compose: hold a `dmq::rpc::RemoteDispatcher` as a member (`NetworkMgr`), connect to its `OnError`/`OnStatus`/`OnDeliveryFailed` Signals — no subclassing required | Compose: hold an `ITransport&` (`Participant`), or instantiate `NetworkNode` — no subclassing required | -| Reliability opt-in | Per-connection — the owning class decides once whether to wrap its transport in `ReliableTransport` | Per-message — pass `Reliability::RELIABLE` or `UNRELIABLE` to `Send()` | -| Multi-peer topology | One connection per `RemoteDispatcher` instance; the app manages multiple peers itself if it needs more than one | Built in — `NetworkNode` manages any number of peers | -| Typical use | Commands, remote function calls, request/response where the caller needs to know the call landed | Sensor data, telemetry, status broadcasts, state that should reach whoever's currently interested | - -**Rule of thumb:** if you're asking "did that specific call succeed?" reach for RemoteDispatcher. If you're asking "who needs to know this happened?" reach for DataBus. - -## Overview - -`dmq::rpc::RemoteDispatcher` is designed to be held as a member (composition, not inheritance — matching `extras/databus`'s `Participant`/`NetworkNode` shape), and it owns the network thread and reliability plumbing ([`TransportMonitor`](../util/TransportMonitor.h), shared with `extras/databus`, not duplicated here) but never constructs or knows the concrete transport type. The owning, application-specific manager owns its own transport (e.g. `Win32UdpTransport`, `ZeroMqTransport`), optionally wraps it in [`ReliableTransport`](../util/ReliableTransport.h)+[`RetryMonitor`](../util/RetryMonitor.h) for ACK/retry reliability, and hands the result to `Attach()`. `RemoteDispatcher` only ever sees `dmq::transport::ITransport`, so it works with any transport that implements it — not a fixed list — and carries no per-transport branching itself. - -```cpp -class NetworkMgr -{ -public: - NetworkMgr() { - // ITransport has no Close(); SetCloseHandler() supplies the callback - // that closes whatever concrete transport(s) this class owns. Called - // by m_dispatcher.Stop() before the receive thread is joined. - m_dispatcher.SetCloseHandler(MakeDelegate(this, &NetworkMgr::CloseTransports)); - } - - int Create() { - // Construct and open the concrete transport, then hand it up. Wrap in - // ReliableTransport first if this transport needs ACK/retry reliability. - m_transport.Create(...); - m_dispatcher.Attach(m_transport, m_transport); - - m_alarmChannel.emplace(m_dispatcher.GetSendTransport(), m_alarmSer); - m_alarmChannel->Bind(this, &NetworkMgr::OnAlarm, ALARM_MSG_ID); - m_dispatcher.RegisterEndpoint(ALARM_MSG_ID, m_alarmChannel->GetEndpoint()); - return 0; - } - - // Fire-and-forget - void SendAlarm(AlarmMsg& msg) { (*m_alarmChannel)(msg); } - - // Blocking: waits for ACK or timeout, returns success/failure - bool SendCommandWait(CommandMsg& msg) { - return m_dispatcher.RemoteInvokeWait(*m_commandChannel, msg); - } - -private: - void CloseTransports() { m_transport.Close(); } - void OnAlarm(AlarmMsg& msg) { /* handle incoming alarm */ } - - // Composed, not inherited. - dmq::rpc::RemoteDispatcher m_dispatcher; - dmq::transport::SomeTransport m_transport; - dmq::serialization::serializer::Serializer m_alarmSer; - std::optional> m_alarmChannel; - std::optional> m_commandChannel; -}; -``` - -## Key Components - -* **`dmq::rpc::RemoteDispatcher.h`**: Manages the internal network thread and marshals calls onto it automatically. `RemoteInvokeWait()` blocks the caller until the message's final outcome — the one capability `DataBus::Publish()` (inherently async/fire-and-forget) doesn't provide. `true` means the remote ACKed it. With a RetryMonitor attached (`AttachRetryMonitor()`), a timeout means a retry follows, so the call waits through the retries and `false` means they ran out; without one, the first timeout returns `false`. The wait is bounded by `GetInvokeWaitLimit()` (9.4 s with the defaults); `RemoteInvokeWaitFor(channel, timeout, args...)` sets a shorter limit, in which case `false` can also mean "not ACKed yet" while retries continue. - * `Attach(sendTransport, recvTransport)` — call once (typically from the owning class's `Create()`, after its own transport member exists) to hand `RemoteDispatcher` the `ITransport&` it sends/receives through. - * `AttachRetryMonitor(retryMonitor)` — call once, after `Attach()`, only if the owning class layered `RetryMonitor`/`ReliableTransport` on top of its transport. Skip it for a self-reliable transport (e.g. ZeroMQ) that has no `RetryMonitor`. - * `SetCloseHandler(handler)` — supply a delegate that closes the concrete transport(s) the owning class owns; `ITransport` itself has no `Close()`. Called by `Stop()` before the receive thread is joined. Optional: if never set, this is a no-op. - * `GetThread()` / `GetTransportMonitor()` / `GetSendTransport()` — public accessors an owning class needs to marshal calls onto the network thread, wire a transport's `TransportMonitor`, and construct `RemoteChannel`s against the send transport. -* **`extras/dispatcher/RemoteChannel.h`**: The recommended way to configure a remote endpoint — aggregates the dispatcher, stream, serializer, and delegate binding for one message signature into a single object. `Bind()` registers the receive-side handler; `GetEndpoint()` returns the `IRemoteInvoker*` to pass to `RegisterEndpoint()`. See [`extras/dispatcher/README.md`](../dispatcher/README.md). - -## Transport Support - -Any transport implementing `dmq::transport::ITransport` works — `RemoteDispatcher` never constructs or names a concrete transport type itself, so there's no per-transport list to extend. This is also what `extras/databus`'s `Participant` already does generically; `RemoteDispatcher` now follows the same shape rather than the old `NetworkEngine`'s fixed `#if`/`#elif` chain over five transports. diff --git a/DelegateMQ/extras/rpc/RemoteDispatcher.cpp b/DelegateMQ/extras/rpc/RemoteDispatcher.cpp deleted file mode 100644 index c18e175..0000000 --- a/DelegateMQ/extras/rpc/RemoteDispatcher.cpp +++ /dev/null @@ -1,217 +0,0 @@ -// Needs a real thread port (DMQ_HAS_THREADING) and compiles to nothing on bare -// metal, so every DelegateMQ source file can be added to a build (see -// src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_HAS_THREADING) - -#include "RemoteDispatcher.h" -#include "extras/util/TimerDelegate.h" - -namespace dmq::rpc { - -using namespace dmq; -using namespace dmq::transport; -using dmq::util::TransportMonitor; -using dmq::util::RetryMonitor; - -RemoteDispatcher::RemoteDispatcher(dmq::Duration ackTimeout) - : m_thread("RemoteDispatcher", 25, dmq::os::FullPolicy::DROP) - , m_transportMonitor(ackTimeout) - , m_recvThread("NetworkRecv") -{ - m_statusConn = m_transportMonitor.OnSendStatus.Connect(dmq::MakeDelegate(this, &RemoteDispatcher::InternalStatusHandler)); - m_thread.CreateThread(); -} - -RemoteDispatcher::~RemoteDispatcher() -{ - Stop(); - m_thread.ExitThread(); -} - -void RemoteDispatcher::Attach(dmq::transport::ITransport& sendTransport, dmq::transport::ITransport& recvTransport) -{ - DMQ_ASSERT_TRUE(m_txTransport == nullptr && m_rxTransport == nullptr); // Attach() called more than once - m_txTransport = &sendTransport; - m_rxTransport = &recvTransport; - m_dispatcher.SetTransport(&sendTransport); -} - -void RemoteDispatcher::AttachRetryMonitor(RetryMonitor& retryMonitor) -{ - m_retryMonitor = &retryMonitor; - m_deliveryFailedConn = retryMonitor.OnDeliveryFailed.Connect(dmq::MakeDelegate(this, &RemoteDispatcher::InternalDeliveryFailedHandler)); -} - -dmq::Duration RemoteDispatcher::GetInvokeWaitLimit() const -{ - const dmq::Duration ack = m_transportMonitor.GetTimeout(); - int retries = m_retryMonitor ? m_retryMonitor->GetMaxRetries() : 0; - if (retries < 0) - retries = 0; - // Each attempt's TIMEOUT is seen up to one poll interval after it expires; - // half an ACK timeout on top is scheduling slack. - return (ack + TIMEOUT_POLL_INTERVAL) * (retries + 1) + ack / 2; -} - -dmq::transport::ITransport& RemoteDispatcher::GetSendTransport() -{ - DMQ_ASSERT_TRUE(m_txTransport != nullptr); // Attach() must be called first - return *m_txTransport; -} - -void RemoteDispatcher::Start() -{ - // Blocking marshal (matches Stop()'s own self-marshal below): a caller on - // another thread must see m_recvThread fully created before Start() - // returns, or a Start()-then-Stop() sequence from that same thread races - // Stop()'s direct (non-marshaled) m_recvThread.ExitThread() call against - // this method's own CreateThread() still running asynchronously on - // m_thread -- caught by ThreadSanitizer as a data race on StdlibThread's - // internal std::optional. - if (!m_thread.IsCurrentThread()) - return dmq::MakeDelegate(this, &RemoteDispatcher::Start, m_thread, dmq::WAIT_INFINITE)(); - - DMQ_ASSERT_TRUE(m_txTransport != nullptr && m_rxTransport != nullptr); // Attach() must be called first - - if (!m_recvThreadCreated) - { - m_recvThreadCreated = true; - m_recvThread.CreateThread(); - - // Post the "RecvThread" loop to run on this new thread. - dmq::MakeDelegate(this, &RemoteDispatcher::RecvThread, m_recvThread).AsyncInvoke(); - } - - m_timeoutTimerConn = m_timeoutTimer.OnExpired.Connect(dmq::util::MakeTimerDelegate(this, &RemoteDispatcher::Timeout, m_thread)); - m_timeoutTimer.Start(TIMEOUT_POLL_INTERVAL); -} - -void RemoteDispatcher::Stop() -{ - if (!m_thread.IsCurrentThread()) { - if (m_recvThreadExit) return; - - // 1. Signal exit flag FIRST so RecvThread knows it should terminate - m_recvThreadExit = true; - - // 2. Close transports to unblock any pending Receive() calls. - // This is necessary because some transports (like sockets) are blocking - // and won't return until a message arrives or the resource is closed. - // ITransport has no Close() of its own -- the owning class supplies a - // handler via SetCloseHandler() to close whichever concrete - // transport(s) it owns. Optional: if never set, this is a no-op. - if (m_closeHandler) - m_closeHandler(); - - // 3. Exit/Join the receive thread. - m_recvThread.ExitThread(); - - // 4. Marshal the rest of the cleanup to the Network Thread. - return dmq::MakeDelegate(this, &RemoteDispatcher::Stop, m_thread, dmq::WAIT_INFINITE)(); - } - m_timeoutTimer.Stop(); - m_timeoutTimerConn.Disconnect(); - m_statusConn.Disconnect(); - m_deliveryFailedConn.Disconnect(); -} - -void RemoteDispatcher::RegisterEndpoint(dmq::DelegateRemoteId id, dmq::IRemoteInvoker* endpoint) -{ - // Thread Safety: Ensure this runs on the Network Thread to avoid - // racing with 'Incoming()' which reads this map. - if (!m_thread.IsCurrentThread()) - { - // Marshal the call to the Network Thread. Cast disambiguates the overload - // set now that RegisterEndpoint() has a templated RemoteChannel sibling. - using RegisterEndpointFn = void (RemoteDispatcher::*)(dmq::DelegateRemoteId, dmq::IRemoteInvoker*); - dmq::MakeDelegate(this, static_cast(&RemoteDispatcher::RegisterEndpoint), m_thread, dmq::WAIT_INFINITE)(id, endpoint); - return; - } - - // Actual insertion (Safe because we are now on the correct thread) - m_receiveIdMap[id] = endpoint; -} - -//------------------------------------------------------------------------------ -// RecvThread -//------------------------------------------------------------------------------ -/// @brief The main loop for the background receive thread. -void RemoteDispatcher::RecvThread() -{ - // Timeout for enqueuing the message to the main thread. - static const std::chrono::milliseconds INVOKE_TIMEOUT(1000); - - std::shared_ptr arg_data; - - while (!m_recvThreadExit) - { - DmqHeader header; - - // Only allocate a new stream if we dispatched the previous one - if (!arg_data) { - arg_data = dmq::xmake_shared(std::ios::in | std::ios::out | std::ios::binary); - } else { - // Reuse the existing stream: clear error flags and empty its contents - arg_data->clear(); - arg_data->str(dmq::xstring()); - } - - // Block reading from the physical transport - int error = m_rxTransport->Receive(*arg_data, header); - - if (!error && !arg_data->str().empty() && !m_recvThreadExit) - { - // Dispatch processing to the main RemoteDispatcher thread. - // Passes ownership of the data stream via shared_ptr (no deep copy). - dmq::MakeDelegate(this, &RemoteDispatcher::Incoming, m_thread, INVOKE_TIMEOUT).AsyncInvoke(header, arg_data); - - // Release our local reference so a new one is allocated next iteration - arg_data.reset(); - } - else if (error < 0 && !m_recvThreadExit) - { - // Negative is a genuine transport fault (bad frame, socket error); - // ITransport::RECEIVE_NO_DATA (a receive timeout) is not reported. - // The m_recvThreadExit guard excludes the one expected non-fault - // case: Stop() closing the socket to unblock this call. - InternalErrorHandler(dmq::INVALID_REMOTE_ID, dmq::DelegateError::ERR_TRANSPORT_RECEIVE, error); - } - } -} - -//------------------------------------------------------------------------------ -// Incoming -//------------------------------------------------------------------------------ -/// @brief Handles incoming messages on the main Network Thread. -void RemoteDispatcher::Incoming(DmqHeader& header, std::shared_ptr arg_data) -{ - // Filter out ACKs; we only dispatch application data here. - if (header.GetId() != dmq::ACK_REMOTE_ID) { - // Find the registered endpoint for this Message ID - auto it = m_receiveIdMap.find(header.GetId()); - - // If found and valid, let the endpoint handle deserialization and execution - if (it != m_receiveIdMap.end() && it->second) { - it->second->Invoke(*arg_data); - } - } -} - -void RemoteDispatcher::Timeout() { m_transportMonitor.Process(); } - -void RemoteDispatcher::InternalErrorHandler(dmq::DelegateRemoteId id, dmq::DelegateError error, dmq::DelegateErrorAux aux) { - OnError(id, error, aux); -} - -void RemoteDispatcher::InternalStatusHandler(dmq::DelegateRemoteId id, uint16_t seq, TransportMonitor::Status status) { - OnStatus(id, seq, status); -} - -void RemoteDispatcher::InternalDeliveryFailedHandler(dmq::DelegateRemoteId id, uint16_t seqNum) { - OnDeliveryFailed(id, seqNum); -} - -} // namespace dmq::rpc - -#endif // DMQ_HAS_THREADING diff --git a/DelegateMQ/extras/rpc/RemoteDispatcher.h b/DelegateMQ/extras/rpc/RemoteDispatcher.h deleted file mode 100644 index 6dbed45..0000000 --- a/DelegateMQ/extras/rpc/RemoteDispatcher.h +++ /dev/null @@ -1,488 +0,0 @@ -/// @file RemoteDispatcher.h -/// @brief Base class for point-to-point RPC over any dmq::transport::ITransport, -/// handling threading and synchronization generically. -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. - -#ifndef REMOTE_DISPATCHER_H -#define REMOTE_DISPATCHER_H - -#include "delegate/DelegateAsync.h" -#include "delegate/DelegateAsyncWait.h" -#include "delegate/Semaphore.h" -#include "delegate/Signal.h" -#include "delegate/UnicastDelegate.h" -#include "extras/rpc/RemoteEndpoint.h" -#include "extras/util/TransportMonitor.h" -#include "extras/util/RetryMonitor.h" -#include "extras/dispatcher/RemoteChannel.h" -#include "port/transport/common/ITransport.h" -#include -#include -#include - -#if defined(DMQ_THREAD_STDLIB) - #include "port/os/stdlib/StdlibThread.h" -#elif defined(DMQ_THREAD_WIN32) - #include "port/os/win32/Win32Thread.h" -#elif defined(DMQ_THREAD_POSIX) - #include "port/os/posix/PosixThread.h" -#elif defined(DMQ_THREAD_FREERTOS) - #include "port/os/freertos/FreeRTOSThread.h" -#elif defined(DMQ_THREAD_THREADX) - #include "port/os/threadx/ThreadXThread.h" -#elif defined(DMQ_THREAD_ZEPHYR) - #include "port/os/zephyr/ZephyrThread.h" -#elif defined(DMQ_THREAD_CMSIS_RTOS2) - #include "port/os/cmsis-rtos2/CmsisRtos2Thread.h" -#endif - -namespace dmq::rpc { - -// TransportMonitor/RetryMonitor/Timer live in dmq::util (shared reliability -// plumbing with extras/databus, not duplicated here) -- pulled in by name -// rather than `using namespace dmq::util;` so this header doesn't leak all of -// dmq::util into anyone who later reopens namespace dmq::rpc themselves. -using dmq::util::TransportMonitor; -using dmq::util::RetryMonitor; -using dmq::util::Timer; - -/// @brief Base class for handling point-to-point RPC transport, threading, and -/// synchronization. -/// -/// @details RemoteDispatcher encapsulates the "plumbing" of point-to-point remote -/// calls -- transport dispatch, the receive thread, ACK/timeout bookkeeping -- -/// entirely behind `dmq::transport::ITransport`. It never constructs or knows -/// the concrete transport type: an owning class constructs its own transport -/// (Win32UdpTransport, ZeroMqTransport, ...), optionally wraps it in -/// ReliableTransport for ACK/retry reliability, and hands the result to -/// Attach(). This works with any transport that implements ITransport, not a -/// fixed list, and keeps this class itself free of per-transport branching. -/// -/// **Key Responsibilities:** -/// * **Lifecycle Management:** Controls the startup and shutdown of the -/// receiver thread. -/// * **Thread Synchronization:** Marshals all outgoing network calls to a -/// dedicated network thread to ensure thread safety and prevent blocking -/// the caller's UI or logic threads. -/// * **Message Routing:** Maps incoming data (by ID) to specific -/// `DelegateMemberRemote` instances via `RegisterEndpoint`. -/// * **Reliability:** Integrates with `TransportMonitor` to handle -/// Acknowledgments (ACKs) and retransmissions/timeouts. -/// -/// @note Designed to be held as a member (composition), not inherited from -- -/// matching `extras/databus`'s Participant/NetworkNode shape. Status is -/// reported via public Signal members (OnError/OnStatus/OnDeliveryFailed -/// below); transport lifecycle (constructing/closing the concrete transport) -/// is wired through Attach()/SetCloseHandler(). An owning class never needs -/// to subclass RemoteDispatcher just to plug into it. -class RemoteDispatcher -{ -public: - /// @param ackTimeout How long a sent message waits for its ACK before - /// TIMEOUT (the internal TransportMonitor's timeout). Defaults to - /// dmq::TRANSPORT_MONITOR_TIMEOUT (DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC). - explicit RemoteDispatcher(dmq::Duration ackTimeout = dmq::TRANSPORT_MONITOR_TIMEOUT); - ~RemoteDispatcher(); - - RemoteDispatcher(const RemoteDispatcher&) = delete; - RemoteDispatcher& operator=(const RemoteDispatcher&) = delete; - - /// @brief Fires when a channel/endpoint reports a technical error - /// (serialization failure, type mismatch, etc.) via SetErrorHandler(). - dmq::Signal OnError; - - /// @brief Fires on every send-status update from the internal - /// TransportMonitor (e.g. TIMEOUT while a RELIABLE message is still - /// being retried, or SUCCESS on ACK). Not the same as OnDeliveryFailed: - /// a message can report TIMEOUT several times while still retrying - /// before either succeeding or finally exhausting its retry budget. - dmq::Signal OnStatus; - - /// @brief Fires when a RELIABLE message exhausts its retry budget - /// without being ACKed (RetryMonitor::OnDeliveryFailed). Only fires if - /// the derived class called AttachRetryMonitor(). - dmq::Signal OnDeliveryFailed; - - /// @brief Attach the transport(s) this engine sends/receives through. - /// @details Call exactly once, after the owning class's own transport - /// member(s) are constructed and before Start()/any send -- e.g. from the - /// owning class's constructor body or a separate Create()-style init - /// method. The owning class retains ownership; sendTransport/recvTransport - /// must outlive this object. Pass a decorator (e.g. a ReliableTransport - /// wrapping a raw one) as sendTransport to add ACK/retry reliability on - /// top of an unreliable transport -- RemoteDispatcher only ever sees the - /// ITransport interface, so it neither knows nor cares. - /// @param sendTransport Transport used for outgoing sends; also the - /// transport GetSendTransport() returns for - /// constructing RemoteChannel instances against. - /// @param recvTransport Transport used for the blocking receive loop. - void Attach(dmq::transport::ITransport& sendTransport, dmq::transport::ITransport& recvTransport); - - /// @brief Optionally wire a RetryMonitor's delivery-failure signal to - /// this engine's own OnDeliveryFailed signal. - /// @details Call once, after Attach(), only if the owning class layered - /// RetryMonitor/ReliableTransport on top of its transport for ACK/retry - /// reliability. Skip this call for a self-reliable transport (e.g. - /// ZeroMQ) that has no RetryMonitor. - /// Once attached, RemoteInvokeWait() treats a TIMEOUT as a retry in - /// progress and waits for the final ACK or delivery failure, so the - /// RetryMonitor must be built on GetTransportMonitor(). - /// @param retryMonitor The independently-owned RetryMonitor whose - /// OnDeliveryFailed signal should forward here. - void AttachRetryMonitor(RetryMonitor& retryMonitor); - - /// @brief Set the handler Stop() calls to close the underlying - /// transport(s). - /// @details Call once, any time before Stop() (typically right after - /// Attach()). Necessary because some transports (sockets, serial ports) - /// are blocking and won't return from Receive() until a message arrives - /// or the resource is closed -- ITransport itself has no Close() (its - /// concrete transports each expose their own), so Stop() calls this - /// handler at the exact point closing needs to happen: after the exit - /// flag is set, before the receive thread is joined. - /// @param handler Called by Stop() to close the transport(s). Optional - /// -- if never set, Stop() simply skips this step, same - /// as the old CloseTransports() hook's no-op default. - void SetCloseHandler(dmq::UnicastDelegate handler) { m_closeHandler = std::move(handler); } - - /// @brief Returns the network thread this engine dispatches on. - /// @details Use `GetThread().IsCurrentThread()` for thread-affinity checks, - /// or pass `GetThread()` as the destination thread to `dmq::MakeDelegate(...)` - /// when marshaling a call from the owning class onto the network thread. - dmq::os::Thread& GetThread() { return m_thread; } - - /// @brief Returns the internal TransportMonitor, for wiring into whichever - /// concrete transport(s) the owning class constructs, e.g. - /// `transport.SetTransportMonitor(&GetTransportMonitor())`. - TransportMonitor& GetTransportMonitor() { return m_transportMonitor; } - - /// @brief Returns the transport passed as `sendTransport` to Attach(), for - /// use by RemoteChannel instances. - /// @details Pass this to RemoteChannel constructors so each channel owns - /// its own Dispatcher while sharing the same physical transport. - /// Hard-faults if called before Attach(). - dmq::transport::ITransport& GetSendTransport(); - - /// @brief Starts the network engine and its receiving thread. - /// - /// @details This method initializes the internal `RecvThread` to begin polling the - /// transport layer for incoming messages. It also starts the `Timeout` timer used - /// by the `TransportMonitor` to track unacknowledged messages. - /// - /// @note This method is thread-safe and will automatically marshal the call to the - /// internal Network Thread if called from a different context. Requires Attach() - /// to have been called first. - void Start(); - - /// @brief Stops the network engine and releases resources. - /// - /// @details This method gracefully shuts down the `RecvThread`, stops the timeout - /// timer, and calls the handler set via SetCloseHandler() (if any) so the - /// owning class can close its underlying transport socket(s). It ensures - /// that all internal threads are joined before returning to prevent - /// resource leaks. - /// - /// @note This call blocks until the shutdown sequence is complete. - void Stop(); - - /// @brief Registers a remote endpoint with the network engine. - /// - /// @details This function maps a unique `DelegateRemoteId` to a specific - /// `DelegateMemberRemote` instance (via the `IRemoteInvoker` interface). - /// When the `RemoteDispatcher` receives data from the transport layer, it - /// uses the message ID to look up the registered endpoint in this map and - /// invokes it to deserialize and handle the payload. - /// - /// @param id The unique identifier for the remote message type. - /// @param endpoint Pointer to the endpoint instance responsible for - /// handling this ID. - void RegisterEndpoint(dmq::DelegateRemoteId id, dmq::IRemoteInvoker* endpoint); - - /// @brief Registers a RemoteChannel endpoint and automatically wires its - /// error handler to fire this RemoteDispatcher's OnError signal. - /// @details Equivalent to calling `channel.SetErrorHandler(...)` followed - /// by `RegisterEndpoint(id, channel.GetEndpoint())`. Prefer this overload - /// so a new channel's send and receive errors are never left unreported. - /// Call `channel.SetErrorHandler(...)` again afterward to override with a - /// custom per-channel handler. - /// @param id The unique identifier for the remote message type. - /// @param channel The RemoteChannel instance responsible for handling - /// this ID. - template - void RegisterEndpoint(dmq::DelegateRemoteId id, dmq::RemoteChannel& channel) { - channel.SetErrorHandler(dmq::MakeDelegate(this, &RemoteDispatcher::InternalErrorHandler)); - RegisterEndpoint(id, channel.GetEndpoint()); - } - - /// @brief Generic helper function to synchronously invoke a remote - /// delegate. - /// - /// @details Blocks the calling thread until the message's final outcome: - /// 1. The remote endpoint acknowledges it (ACK): returns `true`. - /// 2. It is abandoned: returns `false`. With a RetryMonitor attached - /// (AttachRetryMonitor()) that means its retries ran out - /// (`OnDeliveryFailed`); intermediate TIMEOUTs are retries in progress - /// and don't end the wait. Without one, the first TIMEOUT is final. - /// - /// The wait is bounded by GetInvokeWaitLimit(), which covers the whole - /// retry window. Use RemoteInvokeWaitFor() for a shorter limit. - /// - /// **Thread Synchronization Logic:** - /// * **If called from the Network Thread:** The send operation executes - /// immediately and returns the result of the transport send call. No - /// blocking wait occurs because we are already on the thread - /// responsible for I/O. - /// * **If called from any other thread:** The call is marshaled to the - /// Network Thread. The calling thread blocks on a condition variable. - /// When the Network Thread receives an ACK (or timeout), it signals the - /// condition variable to wake up the caller. - /// - /// @tparam TClass The class type of the remote endpoint (usually - /// inferred). - /// @tparam RetType The return type of the function signature (usually - /// void). - /// @tparam Args The argument types of the function signature. - /// @param endpoint The specific `RemoteEndpoint` instance to invoke. - /// @param args The arguments to forward to the remote function. - /// @return `true` if the remote acknowledged the message; `false` on - /// timeout or transport failure. - template - bool RemoteInvokeWait(dmq::DelegateMemberRemote& endpoint, Args&&... args) - { - return RemoteInvokeWaitInternal, Args...>( - endpoint, GetInvokeWaitLimit(), std::forward(args)...); - } - - /// @brief RemoteInvokeWait() with a caller-supplied limit on the wait. - /// @details If `timeout` expires before the final outcome, returns `false` - /// though the message may still be delivered: retries continue in the - /// background. Use it when the caller can't block for the whole retry window. - /// @param endpoint The specific `RemoteEndpoint` instance to invoke. - /// @param timeout The most the caller waits. - /// @param args The arguments to forward to the remote function. - /// @return `true` if the remote acknowledged the message within `timeout`. - template - bool RemoteInvokeWaitFor(dmq::DelegateMemberRemote& endpoint, dmq::Duration timeout, Args&&... args) - { - return RemoteInvokeWaitInternal, Args...>( - endpoint, timeout, std::forward(args)...); - } - - /// @brief Overload of RemoteInvokeWait that accepts a RemoteChannel - /// directly. - /// @details Equivalent to the DelegateMemberRemote overload; routes - /// through the channel's internal delegate. Prefer this when the - /// endpoint is managed by a RemoteChannel (i.e. configured via - /// `channel.Bind()`). - /// @tparam RetType The return type of the function signature (usually - /// void). - /// @tparam Args The argument types of the function signature. - /// @param channel The RemoteChannel instance to invoke. - /// @param args The arguments to forward to the remote function. - /// @return `true` if the remote acknowledged the message; `false` on - /// timeout or transport failure. - template - bool RemoteInvokeWait(dmq::RemoteChannel& channel, Args&&... args) - { - return RemoteInvokeWaitInternal, Args...>( - channel, GetInvokeWaitLimit(), std::forward(args)...); - } - - /// @brief RemoteInvokeWait() on a RemoteChannel with a caller-supplied limit. - /// @details See the DelegateMemberRemote overload of RemoteInvokeWaitFor(). - template - bool RemoteInvokeWaitFor(dmq::RemoteChannel& channel, dmq::Duration timeout, Args&&... args) - { - return RemoteInvokeWaitInternal, Args...>( - channel, timeout, std::forward(args)...); - } - - /// @brief Default limit for RemoteInvokeWait(): - /// (retries + 1) x (ACK timeout + TIMEOUT_POLL_INTERVAL) + ACK timeout / 2. - /// Each attempt's TIMEOUT can be reported up to one poll interval late; the - /// half ACK timeout is scheduling slack. Retries are 0 without a - /// RetryMonitor attached. With the defaults (2 s, 3 retries): 9.4 s. - dmq::Duration GetInvokeWaitLimit() const; - - /// How often the network thread checks for ACK timeouts. - static constexpr std::chrono::milliseconds TIMEOUT_POLL_INTERVAL{ 100 }; - -private: - dmq::os::Thread m_thread; - Dispatcher m_dispatcher; - TransportMonitor m_transportMonitor; - dmq::UnicastDelegate m_closeHandler; - - /// @brief Shared synchronization state for RemoteInvokeWaitInternal(). - /// @details All fields are guarded by `mtx`. The dispatched sequence number - /// is not known until the send executes on the network thread, but the final - /// outcome (ACK, final TIMEOUT, or delivery failure) can arrive first — e.g. - /// on a loopback transport, or an immediate send failure inside the send. - /// Outcomes that arrive before the seq is recorded are buffered in `early` - /// and reconciled by the send lambda, so a fast one is never lost. - struct InvokeWaitState { - bool complete = false; ///< Final outcome received for expectedSeq - bool success = false; ///< Final outcome was an ACK - bool seqSet = false; ///< expectedSeq is valid - uint16_t expectedSeq = 0; ///< Seq assigned to the dispatched message - /// Final outcomes (true = ACKed) received before seqSet, by seq. - dmq::xmap early; - - /// @brief Record a final outcome for `seq`. - /// @return true if it completed the wait, so the caller must Signal(). - bool Report(uint16_t seq, bool acked) { - dmq::LockGuard lock(mtx); - if (!seqSet) { - early.emplace(seq, acked); // keep the first outcome per seq - return false; - } - if (complete || seq != expectedSeq) - return false; - complete = true; - success = acked; - return true; - } - dmq::Mutex mtx; // Generic Mutex - dmq::Semaphore sem; // Portable wake signal (DMQ_HAS_SEMAPHORE is - // available everywhere this file is included -- - // see DelegateMQ.h's #if defined(DMQ_HAS_SEMAPHORE) - // guard -- unlike dmq::ConditionVariable, which - // has no port on Zephyr/CMSIS-RTOS2/NuttX) - XALLOCATOR - }; - - /// @brief Shared implementation for both RemoteInvokeWait() overloads. - /// @tparam Target A sender exposing operator()(Args...), GetRemoteId(), - /// GetError(), and GetLastSeqNum() -- i.e. - /// DelegateMemberRemote or RemoteChannel. - template - bool RemoteInvokeWaitInternal(Target& target, dmq::Duration timeout, Args&&... args) - { - // [Network Thread] Already on the correct thread: send immediately, - // no blocking wait is possible (we would deadlock waiting on ourselves). - if (m_thread.IsCurrentThread()) - { - target(std::forward(args)...); - return (target.GetError() == dmq::DelegateError::SUCCESS); - } - - // 1. [Caller Thread] Create shared synchronization state. - auto state = dmq::xmake_shared(); - dmq::DelegateRemoteId remoteId = target.GetRemoteId(); - - // 2. [Caller Thread] Define the callbacks that report the final outcome. - // With a RetryMonitor attached, a TIMEOUT only means a retry follows; the - // message is final on SUCCESS or on the RetryMonitor's delivery failure. - // Without one, the first TIMEOUT is final. - const bool retrying = (m_retryMonitor != nullptr); - std::function statusCbFunc = - [state, remoteId, retrying](dmq::DelegateRemoteId id, uint16_t seq, TransportMonitor::Status status) { - if (id != remoteId) - return; - const bool acked = (status == TransportMonitor::Status::SUCCESS); - if (!acked && retrying) - return; - if (state->Report(seq, acked)) - state->sem.Signal(); - }; - std::function failedCbFunc = - [state, remoteId](dmq::DelegateRemoteId id, uint16_t seq) { - if (id == remoteId && state->Report(seq, false)) - state->sem.Signal(); - }; - - // 3. [Caller Thread] Register the callbacks. - dmq::ScopedConnection conn = m_transportMonitor.OnSendStatus.Connect(dmq::MakeDelegate(statusCbFunc)); - dmq::ScopedConnection failedConn; - if (retrying) - failedConn = OnDeliveryFailed.Connect(dmq::MakeDelegate(failedCbFunc)); - - // 4. [Caller Thread] Define the "Send" logic lambda. - auto* targetPtr = ⌖ - std::function asyncCallFunc = [targetPtr, state](auto&&... fwdArgs) -> bool { - (*targetPtr)(std::forward(fwdArgs)...); - bool notify = false; - { - dmq::LockGuard lock(state->mtx); - state->expectedSeq = targetPtr->GetLastSeqNum(); - state->seqSet = true; - - // Reconcile an outcome that arrived before the seq was known - auto it = state->early.find(state->expectedSeq); - if (it != state->early.end()) { - state->complete = true; - state->success = it->second; - notify = true; - } - - state->early.clear(); - } - if (notify) - state->sem.Signal(); - return (targetPtr->GetError() == dmq::DelegateError::SUCCESS); - }; - - // 5. [Caller Thread] Dispatch the lambda to the Network Thread queue. - // Must block until asyncCallFunc actually runs (or throws) on the network - // thread rather than timing out on the *queueing* wait: asyncCallFunc - // captures a raw pointer to the caller's `target`. If this wait timed out - // while the message was still queued (a short SEND_TIMEOUT was previously - // used here), a caller seeing "failed" could free `target` while the - // still-queued closure later runs against a dangling pointer. Every other - // marshal-to-network-thread call site in this file (Start, RegisterEndpoint, - // Stop) uses WAIT_INFINITE for the same reason. - auto retVal = dmq::MakeDelegate(std::move(asyncCallFunc), m_thread, dmq::WAIT_INFINITE) - .AsyncInvoke(std::forward(args)...); - - if (retVal.has_value() && retVal.value() == true) - { - // 6. [Caller Thread] BLOCK until the status callback (or the send - // lambda's reconciliation) completes the wait, or timeout. Whichever - // lambda sets state->complete/state->success calls state->sem.Signal() - // exactly once, outside the lock; Signal()-before-Wait() is safe since - // dmq::Semaphore retains its signaled state (see delegate/Semaphore.h). - // If Wait() times out, state->success is still correctly read below -- - // it was initialized false and nothing sets it without also signaling. - state->sem.Wait(timeout); - dmq::LockGuard lock(state->mtx); - return state->success; - } - - // 7. [Caller Thread] Send failed or timed out queueing to the network - // thread. 'conn' disconnects on scope exit; 'state' stays alive via - // shared_ptr if a late status callback races with our return. - dmq::LockGuard lock(state->mtx); - return state->success; - } - - void RecvThread(); - void Incoming(dmq::transport::DmqHeader& header, std::shared_ptr arg_data); - void Timeout(); - void InternalErrorHandler(dmq::DelegateRemoteId id, dmq::DelegateError error, dmq::DelegateErrorAux aux); - void InternalStatusHandler(dmq::DelegateRemoteId id, uint16_t seq, TransportMonitor::Status status); - void InternalDeliveryFailedHandler(dmq::DelegateRemoteId id, uint16_t seqNum); - - dmq::os::Thread m_recvThread; - std::atomic m_recvThreadExit{ false }; - bool m_recvThreadCreated = false; - Timer m_timeoutTimer; - dmq::ScopedConnection m_timeoutTimerConn; - - // Set by Attach(). Not owned -- the derived class retains ownership of - // whatever concrete transport(s) these point to. - dmq::transport::ITransport* m_txTransport = nullptr; - dmq::transport::ITransport* m_rxTransport = nullptr; - - dmq::xmap m_receiveIdMap; - dmq::ScopedConnection m_statusConn; - dmq::ScopedConnection m_deliveryFailedConn; - - /// Set by AttachRetryMonitor(); not owned. Decides whether a TIMEOUT is - /// final for RemoteInvokeWait() and sizes GetInvokeWaitLimit(). - RetryMonitor* m_retryMonitor = nullptr; -}; - -} // namespace dmq::rpc - -#endif // REMOTE_DISPATCHER_H diff --git a/DelegateMQ/extras/rpc/RemoteEndpoint.h b/DelegateMQ/extras/rpc/RemoteEndpoint.h deleted file mode 100644 index ee4c5ee..0000000 --- a/DelegateMQ/extras/rpc/RemoteEndpoint.h +++ /dev/null @@ -1,80 +0,0 @@ -#ifndef REMOTE_ENDPOINT_H -#define REMOTE_ENDPOINT_H - -#include "delegate/DelegateRemote.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include - -namespace dmq::rpc { - -template -struct RemoteEndpoint; // Not defined - -/// @brief `RemoteEndpoint` wraps a `DelegateMemberRemote` and its associated -/// transport infrastructure into a single, cohesive unit. -/// @details This structure is designed to simplify the management of remote -/// endpoints by grouping the delegate, the transport, and the necessary stream -/// for serialization. -/// @tparam TClass The class type that contains the member function. -/// @tparam RetType The return type of the member function. -/// @tparam Args The types of the function arguments. -template -struct RemoteEndpoint -{ - XALLOCATOR - /// @brief The `DelegateMemberRemote` object that handles the remote invocation. - dmq::DelegateMemberRemote delegate; - - /// @brief The transport used to send the serialized data. - dmq::transport::ITransport* transport = nullptr; - - /// @brief The stream used for serializing the function arguments. - dmq::xostringstream stream; - - /// @brief The identifier for the remote endpoint. - dmq::DelegateRemoteId id = 0; - - /// @brief Constructor to initialize the remote endpoint. - /// @param[in] obj A shared pointer to the instance of `TClass`. - /// @param[in] func A pointer to the member function of `TClass`. - /// @param[in] _transport The transport to be used for remote communication. - /// @param[in] _id The remote identifier for this endpoint. - RemoteEndpoint(std::shared_ptr obj, RetType(TClass::* func)(Args...), dmq::transport::ITransport& _transport, dmq::DelegateRemoteId _id) - : delegate(obj, func, _id), transport(&_transport), stream(std::ios::in | std::ios::out | std::ios::binary), id(_id) - { - } -}; - -/// @brief Partial specialization of `RemoteEndpoint` for free functions. -/// @tparam RetType The return type of the function. -/// @tparam Args The types of the function arguments. -template -struct RemoteEndpoint -{ - XALLOCATOR - /// @brief The `DelegateFreeRemote` object that handles the remote invocation. - dmq::DelegateFreeRemote delegate; - - /// @brief The transport used to send the serialized data. - dmq::transport::ITransport* transport = nullptr; - - /// @brief The stream used for serializing the function arguments. - dmq::xostringstream stream; - - /// @brief The identifier for the remote endpoint. - dmq::DelegateRemoteId id = 0; - - /// @brief Constructor to initialize the remote endpoint for a free function. - /// @param[in] func A pointer to the free function. - /// @param[in] _transport The transport to be used for remote communication. - /// @param[in] _id The remote identifier for this endpoint. - RemoteEndpoint(RetType(*func)(Args...), dmq::transport::ITransport& _transport, dmq::DelegateRemoteId _id) - : delegate(func, _id), transport(&_transport), stream(std::ios::in | std::ios::out | std::ios::binary), id(_id) - { - } -}; - -} // namespace dmq::rpc - -#endif diff --git a/DelegateMQ/extras/util/AsyncInvoke.h b/DelegateMQ/extras/util/AsyncInvoke.h deleted file mode 100644 index bd4c838..0000000 --- a/DelegateMQ/extras/util/AsyncInvoke.h +++ /dev/null @@ -1,153 +0,0 @@ -#ifndef ASYNC_INVOKE_H -#define ASYNC_INVOKE_H - -/// @file AsyncInvoke.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Helper functions for simplified, one-line asynchronous function invocation. -/// -/// @details -/// The `AsyncInvoke` helper functions provide a convenient wrapper around the -/// DelegateMQ library to execute any callable (free function, lambda, or member function) -/// on a specific target thread. -/// -/// **Key Features:** -/// * **Automatic Context Switching:** Automatically detects if the caller is already -/// execute on the target thread. -/// - If **Yes**: It executes the function synchronously (immediately) to avoid overhead. -/// - If **No**: It creates a temporary asynchronous delegate, marshals the arguments, -/// and executes the function on the target thread. -/// * **Blocking Wait:** Supports a timeout parameter to wait for the asynchronous -/// execution to complete and return a value. -/// * **Return Value Handling:** Safely retrieves the return value from the target -/// function across thread boundaries. - -#include "delegate/DelegateRemote.h" -#include "delegate/DelegateAsync.h" -#include "delegate/IThread.h" -#include "delegate/DelegateOpt.h" -#include "extras/dispatcher/RemoteChannel.h" -#include -#include -#include -#include -#include - -namespace dmq::util { - -/// Helper function to simplify asynchronous invoke of a free function/lambda. -/// @param[in] func - the function/lambda to invoke -/// @param[in] thread - the thread to invoke func on -/// @param[in] timeout - the time to wait for invoke to complete -/// @param[in] args - the function argument(s) passed to func -template -auto AsyncInvoke(Func func, dmq::IThread& thread, const dmq::Duration& timeout, Args&&... args) -{ - // Deduce return type - using RetType = decltype(func(std::forward(args)...)); - - // Is the calling function executing on the requested thread? - if (!thread.IsCurrentThread()) - { - // Internal type used to bridge raw lambda to DelegateFunctionAsyncWait. - // decay_t ensures that references and const qualifiers are removed for storage. - std::function...)> typedFunc = func; - - // Create a delegate that points to func to invoke on thread - auto delegate = dmq::MakeDelegate(typedFunc, thread, timeout); - - // Invoke the delegate target function asynchronously and wait for completion - auto retVal = delegate.AsyncInvoke(std::forward(args)...); - - // Target function has a return value? - if constexpr (!std::is_void_v) - { - if (retVal.has_value()) { - return retVal.value(); - } - else { - return RetType{}; - } - } - } - else - { - // Invoke target function synchronously - return func(std::forward(args)...); - } -} - -/// Helper function to simplify asynchronous invoke of a member function using a raw pointer. -/// @param[in] tclass - the class instance (pointer) -/// @param[in] func - the member function pointer -/// @param[in] thread - the thread to invoke func on -/// @param[in] timeout - the time to wait for invoke to complete -/// @param[in] args - the function argument(s) passed to func -template -auto AsyncInvoke(TClass* tclass, Func func, dmq::IThread& thread, const dmq::Duration& timeout, Args&&... args) -{ - // Deduce return type using std::invoke (robust for member pointers) - using RetType = decltype(std::invoke(func, tclass, std::forward(args)...)); - - if (!thread.IsCurrentThread()) - { - // Create delegate. MakeDelegate handles member pointers correctly. - auto delegate = dmq::MakeDelegate(tclass, func, thread, timeout); - - auto retVal = delegate.AsyncInvoke(std::forward(args)...); - - if constexpr (!std::is_void_v) - { - if (retVal.has_value()) { - return retVal.value(); - } - else { - return RetType{}; - } - } - } - else - { - return std::invoke(func, tclass, std::forward(args)...); - } -} - -/// Helper function to simplify asynchronous invoke of a member function using a shared pointer. -/// @param[in] tclass - the class instance (shared_ptr) -/// @param[in] func - the member function pointer -/// @param[in] thread - the thread to invoke func on -/// @param[in] timeout - the time to wait for invoke to complete -/// @param[in] args - the function argument(s) passed to func -template -auto AsyncInvoke(std::shared_ptr tclass, Func func, dmq::IThread& thread, const dmq::Duration& timeout, Args&&... args) -{ - // Deduce return type using std::invoke (robust for member pointers) - using RetType = decltype(std::invoke(func, tclass, std::forward(args)...)); - - if (!thread.IsCurrentThread()) - { - // Create delegate. MakeDelegate handles shared_ptr correctly (creates DelegateMemberSp). - auto delegate = dmq::MakeDelegate(tclass, func, thread, timeout); - - auto retVal = delegate.AsyncInvoke(std::forward(args)...); - - if constexpr (!std::is_void_v) - { - if (retVal.has_value()) { - return retVal.value(); - } - else { - return RetType{}; - } - } - } - else - { - return std::invoke(func, tclass, std::forward(args)...); - } -} - -} // namespace dmq::util - -#endif diff --git a/DelegateMQ/extras/util/ClockHelper.h b/DelegateMQ/extras/util/ClockHelper.h deleted file mode 100644 index 01efdec..0000000 --- a/DelegateMQ/extras/util/ClockHelper.h +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef CLOCK_HELPER_H -#define CLOCK_HELPER_H - -#include "../../delegate/DelegateOpt.h" -#include - -namespace dmq::util { - -namespace detail { - /// @brief Captures the process-start time point once, on first call. - inline const dmq::Clock::time_point& ProcessStart() { - static const dmq::Clock::time_point start = dmq::Clock::now(); - return start; - } -} - -/// @brief Get elapsed time since process start in milliseconds. -/// @details Normalizes to process start so timestamps are comparable across -/// nodes regardless of the underlying clock's epoch (e.g. FreeRTOS ticks -/// vs. std::chrono::steady_clock which counts from system boot). -/// @return Milliseconds elapsed since first call to any dmq::util::Timestamp function. -inline uint64_t TimestampMs() { - return static_cast(std::chrono::duration_cast( - dmq::Clock::now() - detail::ProcessStart()).count()); -} - -/// @brief Get elapsed time since process start in microseconds. -/// @return Microseconds elapsed since first call to any dmq::util::Timestamp function. -inline uint64_t TimestampUs() { - return static_cast(std::chrono::duration_cast( - dmq::Clock::now() - detail::ProcessStart()).count()); -} - -} // namespace dmq::util - -#endif diff --git a/DelegateMQ/extras/util/Fault.h b/DelegateMQ/extras/util/Fault.h deleted file mode 100644 index a1937fd..0000000 --- a/DelegateMQ/extras/util/Fault.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef _FAULT_H -#define _FAULT_H - -#ifdef __cplusplus - #define DMQ_NORETURN [[noreturn]] -#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L - #define DMQ_NORETURN _Noreturn -#elif defined(__GNUC__) || defined(__clang__) - #define DMQ_NORETURN __attribute__((noreturn)) -#elif defined(_MSC_VER) - #define DMQ_NORETURN __declspec(noreturn) -#else - #define DMQ_NORETURN -#endif - -#ifdef __cplusplus -namespace dmq::util { - /// Handles all software assertions in the system. - /// @param[in] file - the file name that the software assertion occurred on - /// @param[in] line - the line number that the software assertion occurred on - DMQ_NORETURN void FaultHandler(const char* file, unsigned short line); - - /// Install OS-specific crash handlers to capture and report critical errors. - void InstallCrashHandlers(); -} -#endif - -#ifdef __cplusplus -extern "C" { -#endif - DMQ_NORETURN void FaultHandler(const char* file, unsigned short line); - DMQ_NORETURN void WatchdogHandler(const char* threadName); - void InstallCrashHandlers(); -#ifdef __cplusplus -} -#endif - -#ifdef __cplusplus -#ifndef DMQ_ASSERT -#define DMQ_ASSERT() \ - dmq::util::FaultHandler(__FILE__, static_cast(__LINE__)) -#endif - -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(condition) \ - do {if (!(condition)) dmq::util::FaultHandler(__FILE__, static_cast(__LINE__));} while (0) -#endif -#else -#ifndef DMQ_ASSERT -#define DMQ_ASSERT() \ - FaultHandler(__FILE__, (unsigned short) __LINE__) -#endif - -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(condition) \ - do {if (!(condition)) FaultHandler(__FILE__, (unsigned short) __LINE__);} while (0) -#endif -#endif - -#endif diff --git a/DelegateMQ/extras/util/MonotonicGuard.h b/DelegateMQ/extras/util/MonotonicGuard.h deleted file mode 100644 index 5f22df1..0000000 --- a/DelegateMQ/extras/util/MonotonicGuard.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef MONOTONIC_GUARD_H -#define MONOTONIC_GUARD_H - -#include -#include - -namespace dmq::util { - -/// @brief Utility to guard against out-of-order or stale messages. -/// @details Tracks the last accepted sequence number and rejects any incoming value -/// that is not strictly newer. Handles unsigned integer rollover for types of 32 bits -/// or smaller via signed-difference comparison. -/// -/// Primary use case — LVC rewind: when a DataBus subscriber connects with -/// Last Value Cache enabled, it may receive a stale cached value AFTER a fresher -/// value has already been delivered (see DataBus::InternalSubscribe, step 5). -/// Embed a sequence number in every message (e.g. via MessageBase) and call -/// IsNewer() in the subscriber to silently discard the stale arrival. -/// -/// @note This class is NOT thread-safe. Use within a single thread of control -/// (e.g., an Active Object or a dedicated subscriber thread). -template -class MonotonicGuard { - static_assert(std::is_integral_v && std::is_unsigned_v, "T must be an unsigned integral type"); - -public: - MonotonicGuard() = default; - - /// @brief Check if a message is newer (more recent than the last processed). - /// @param timestamp The timestamp from the incoming message. - /// @return true if newer, false if stale or out-of-order. - bool IsNewer(T timestamp) { - if (m_first) { - m_lastTimestamp = timestamp; - m_first = false; - return true; - } - - if constexpr (sizeof(T) <= 4) { - // Use signed difference to handle rollover for 32-bit (or smaller) types. - // This works correctly up to half the range of the type (e.g., ~24 days for uint32 ms). - using SignedT = std::make_signed_t; - SignedT diff = static_cast(timestamp - m_lastTimestamp); - if (diff > 0) { - m_lastTimestamp = timestamp; - return true; - } - } else { - // For 64-bit types, rollover is effectively impossible. - // Simple greater-than comparison is sufficient. - if (timestamp > m_lastTimestamp) { - m_lastTimestamp = timestamp; - return true; - } - } - - return false; - } - - /// @brief Reset the guard to its initial state. - void Reset() { - m_first = true; - m_lastTimestamp = 0; - } - -private: - T m_lastTimestamp = 0; - bool m_first = true; -}; - -} // namespace dmq::util - -#endif diff --git a/DelegateMQ/extras/util/NetworkConnect.h b/DelegateMQ/extras/util/NetworkConnect.h deleted file mode 100644 index 0086d7c..0000000 --- a/DelegateMQ/extras/util/NetworkConnect.h +++ /dev/null @@ -1,118 +0,0 @@ -#ifndef NETWORK_CONNECT_H -#define NETWORK_CONNECT_H - -/// @brief RAII wrapper to initialize and cleanup network stacks. -/// Instantiate this ONCE at the top of main(). -/// -/// On bare-metal targets (no OS, no socket stack) the class compiles to -/// empty stubs so that DataBus.h can include this header unconditionally. - -// DelegateOpt.h owns the actual platform-header decision and include (see -// its DMQ_NETWORK_CONNECT_DESKTOP_HOST_HEADERS block) so that no library -// file other than DelegateOpt.h ever #includes a platform header directly. -// This header only reads the resulting macro. -#include "delegate/DelegateOpt.h" - -#include - -namespace dmq::util { - -class NetworkContext -{ -public: - NetworkContext() - { -#if defined(DMQ_NETWORK_CONNECT_DESKTOP_HOST_HEADERS) && defined(_WIN32) - WSADATA wsaData; - int result = WSAStartup(MAKEWORD(2, 2), &wsaData); - if (result != 0) - { - // WSAStartup failed — network unavailable - } -#endif - } - - ~NetworkContext() - { -#if defined(DMQ_NETWORK_CONNECT_DESKTOP_HOST_HEADERS) && defined(_WIN32) - WSACleanup(); -#endif - } - - /// @brief Helper to find the first non-loopback physical IPv4 address. - /// @return The IP address as a string (e.g. "192.168.1.5") or "127.0.0.1" if none found. - /// @note Unavailable on embedded RTOS targets (ThreadX/Zephyr/CMSIS-RTOS2) - /// -- a desktop-only convenience with no embedded equivalent, see - /// DelegateOpt.h's DMQ_NETWORK_CONNECT_DESKTOP_HOST_HEADERS block -- - /// and always returns "127.0.0.1" there. - /// FreeRTOS is not in that list: its Win32/POSIX simulator samples - /// (databus-freertos, freertos-linux) use real host sockets on purpose. - static std::string GetLocalAddress() - { -#if !defined(DMQ_NETWORK_CONNECT_DESKTOP_HOST_HEADERS) - return "127.0.0.1"; -#elif defined(_WIN32) - char hostname[256]; - if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR) { - return "127.0.0.1"; - } - - addrinfo hints = {}, *res = nullptr; - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_DGRAM; - - if (getaddrinfo(hostname, nullptr, &hints, &res) != 0) { - return "127.0.0.1"; - } - - std::string firstIp = "127.0.0.1"; - for (addrinfo* p = res; p != nullptr; p = p->ai_next) { - char ipStr[INET_ADDRSTRLEN]; - sockaddr_in* ipv4 = (sockaddr_in*)p->ai_addr; - inet_ntop(AF_INET, &(ipv4->sin_addr), ipStr, INET_ADDRSTRLEN); - std::string current(ipStr); - if (current.find("127.") != 0) { - firstIp = current; - break; - } - } - - freeaddrinfo(res); - return firstIp; -#elif defined(__linux__) || defined(__APPLE__) || defined(__unix__) - struct ifaddrs *ifaddr, *ifa; - if (getifaddrs(&ifaddr) == -1) { - return "127.0.0.1"; - } - - std::string firstIp = "127.0.0.1"; - for (ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) { - if (ifa->ifa_addr == nullptr || ifa->ifa_addr->sa_family != AF_INET) - continue; - if (ifa->ifa_flags & IFF_LOOPBACK) - continue; - if (!(ifa->ifa_flags & IFF_UP)) - continue; - - char ipStr[INET_ADDRSTRLEN]; - void* addrPtr = &((struct sockaddr_in*)ifa->ifa_addr)->sin_addr; - inet_ntop(AF_INET, addrPtr, ipStr, INET_ADDRSTRLEN); - std::string current(ipStr); - if (current != "0.0.0.0" && current.find("127.") != 0) { - firstIp = current; - break; - } - } - - freeifaddrs(ifaddr); - return firstIp; -#else - return "127.0.0.1"; -#endif - } -}; - -} // namespace dmq::util - - -#endif // NETWORK_CONNECT_H diff --git a/DelegateMQ/extras/util/README.md b/DelegateMQ/extras/util/README.md deleted file mode 100644 index f833b40..0000000 --- a/DelegateMQ/extras/util/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# Utility & Helper Layer - -This directory contains concrete utility classes and helper functions that complement the core DelegateMQ library. - -While the core library (`namespace dmq`) provides the fundamental mechanism for delegates and threading interfaces, this directory provides the **"batteries included"** implementations required to build real-world applications (Timers, Reliability, Networking logic, etc.). - -> **Note:** Code in this directory resides in the **`dmq::util`** namespace. - -## Functional Modules - -### 1. Asynchronous Helpers -* **`dmq::util::AsyncInvoke.h`**: A powerful template helper that allows you to fire any function (lambda, member, free) onto any thread in a single line of code. - * *Example:* `dmq::util::AsyncInvoke(myFunc, workerThread, 1s, arg1);` - -### 2. Timing & Scheduling -* **`dmq::util::Timer.h`**: A complete software timer system capable of one-shot and periodic callbacks via delegates. Supports millisecond and microsecond precision depending on the platform clock. -* **`dmq::util::TimerDelegate.h`**: A stateful delegate wrapper that prevents thread queue flooding. It ensures at most one timer message is in the target thread's queue at any time, providing safe backpressure for high-frequency timers. - -### 3. Reliability Layer (QoS) -These classes provide transport-layer reliability (ACKs and Retries) over unreliable media (like UDP or Serial). -* **`dmq::util::TransportMonitor.h`**: Tracks outgoing messages and handles sequence numbers. -* **`dmq::util::RetryMonitor.h`**: Logic to detect lost packets and trigger re-transmissions. -* **`dmq::util::ReliableTransport.h`**: A composite transport that wraps a raw transport (e.g., UDP) and adds reliability logic transparently. - -### 4. Networking Logic -* **`dmq::util::NetworkConnect.h`**: Platform-specific socket initialization helpers (e.g., `dmq::util::NetworkContext`) to handle networking boilerplate like `WSAStartup`. - -> **`RemoteDispatcher`/`RemoteEndpoint`** (the point-to-point RPC pattern) moved to [`extras/rpc`](../rpc/README.md). They still use this directory's `TransportMonitor`/`RetryMonitor`/`ReliableTransport` as shared reliability plumbing. - -### 5. Monotonic Messaging and Time -These utilities help handle message ordering and timestamping in distributed systems. -* **`dmq::util::ClockHelper.h`**: Simplified functions to get monotonic timestamps (`TimestampMs()`, `TimestampUs()`) across all supported platforms. -* **`dmq::util::MonotonicGuard.h`**: A generic template class to filter out-of-order or stale messages. Handles 32-bit rollover logic automatically and provides simple 64-bit monotonic checks. - -### 6. System Utilities -* **`dmq::util::Fault.h`**: Assertions and fault trapping macros (`DMQ_ASSERT_TRUE`, `dmq::util::FaultHandler`) used throughout the library examples. -* **`dmq::util::crc16.h`**: Checksum utility for data integrity in serial/UDP headers. - -## Usage - -Include these headers when you need specific functionality beyond basic delegates. For example, if you need to schedule a periodic callback: - -```cpp -#include "extras/util/Timer.h" - -dmq::util::Timer myTimer; -// Use a delegate to receive timer callbacks; store the connection or it disconnects immediately -auto conn = myTimer.OnExpired.Connect(dmq::MakeDelegate(&myClass, &MyClass::OnTimeout)); -myTimer.Start(std::chrono::milliseconds(1000)); // 1-second periodic timer - -// Drive all timers periodically (main loop or high-priority task; an ISR only on bare metal) -dmq::util::Timer::ProcessTimers(); -``` - -Or to invoke a function on a specific thread with a 5-second timeout: - -```cpp -#include "extras/util/AsyncInvoke.h" - -// Fires and waits up to 5s for completion on workerThread -dmq::util::AsyncInvoke(myWorkerFunc, workerThread, 5s, 123, "hello"); -``` diff --git a/DelegateMQ/extras/util/ReliableTransport.h b/DelegateMQ/extras/util/ReliableTransport.h deleted file mode 100644 index a45f274..0000000 --- a/DelegateMQ/extras/util/ReliableTransport.h +++ /dev/null @@ -1,111 +0,0 @@ -#ifndef RELIABLE_TRANSPORT_H -#define RELIABLE_TRANSPORT_H - -/// @file ReliableTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Reliability adapter for the DelegateMQ transport layer. -/// -/// @details -/// This class applies the **Decorator Pattern** to any existing `ITransport` implementation, -/// adding automatic retransmission capabilities without modifying the underlying transport logic. -/// -/// ### The Reliability Stack -/// It functions as the entry point to the reliability system, routing outgoing messages -/// through the `RetryMonitor` to ensure delivery guarantees (ACKs) are met. -/// -/// @verbatim -/// Application -/// | Send() -/// v -/// +-----------------------+ -/// | ReliableTransport | <-- Adapter / Entry Point -/// +-----------------------+ -/// | -/// v -/// +-----------------------+ +------------------+ -/// | RetryMonitor | <----(Signaled)----- | TransportMonitor | -/// | (Manages Re-sending) | | (Tracks Timeouts)| -/// +-----------------------+ +------------------+ -/// | ^ -/// | Send() | Add(SeqNum) -/// v | -/// +-----------------------+ | -/// | PhysicalTransport | ------------------------------+ -/// | (TCP, UDP, Serial...) | -/// +-----------------------+ -/// | -/// v -/// Network -/// @endverbatim -/// -/// **Key Responsibilities:** -/// 1. **Send Interception**: Redirects `Send()` calls to `RetryMonitor::SendWithRetry()`. -/// 2. **Receive Pass-through**: Forwards `Receive()` calls directly to the physical transport -/// (no interference with incoming data). -/// -/// @brief Notes on Packet Ordering and Reliability -/// -/// The DelegateMQ reliability layer (RetryMonitor) ensures *eventual delivery*, -/// but the order of execution depends heavily on the underlying transport: -/// -/// 1. **UDP / Serial (Unordered Transports)**: -/// These transports do not buffer or reorder packets. If Packet #2 is lost -/// and re-transmitted by the RetryMonitor, the Receiver will process them -/// in the order of arrival: #1 -> #3 -> #2 (Retry). -/// *Application logic must be robust against out-of-order updates.* -/// -/// 2. **TCP (Ordered Stream)**: -/// The TCP protocol stack enforces strict ordering. If Packet #2 is lost -/// (tcp segment loss), the OS holds Packet #3 in the kernel buffer until -/// #2 is retransmitted by the TCP stack itself. The Receiver application -/// will always see: #1 -> #2 -> #3. -/// *Note: If the TCP connection is fully severed and re-connected, the -/// DelegateMQ retry logic may kick in, potentially leading to duplicates -/// or ordering issues across the connection boundary.* - -#include "../../port/transport/common/ITransport.h" -#include "RetryMonitor.h" - -namespace dmq::util { - -/// @brief Adapter to enable automatic retries on any ITransport. -/// @details Routes Send() calls through the RetryMonitor before passing them -/// to the physical transport. -class ReliableTransport : public dmq::transport::ITransport -{ - XALLOCATOR -public: - ReliableTransport() = default; - - ReliableTransport(dmq::transport::ITransport& transport, RetryMonitor& retry) - { - Init(transport, retry); - } - - void Init(dmq::transport::ITransport& transport, RetryMonitor& retry) - { - m_transport = &transport; - m_retry = &retry; - } - - virtual int Send(dmq::xostringstream& os, const dmq::transport::DmqHeader& header) override { - DMQ_ASSERT_TRUE(m_retry != nullptr); - return m_retry->SendWithRetry(os, header); - } - - virtual int Receive(dmq::xstringstream& is, dmq::transport::DmqHeader& header) override { - DMQ_ASSERT_TRUE(m_transport != nullptr); - return m_transport->Receive(is, header); - } - -private: - dmq::transport::ITransport* m_transport = nullptr; - RetryMonitor* m_retry = nullptr; -}; - -} // namespace dmq::util - - -#endif \ No newline at end of file diff --git a/DelegateMQ/extras/util/RetryMonitor.h b/DelegateMQ/extras/util/RetryMonitor.h deleted file mode 100644 index 64defc0..0000000 --- a/DelegateMQ/extras/util/RetryMonitor.h +++ /dev/null @@ -1,311 +0,0 @@ -#ifndef _RETRY_MONITOR_H -#define _RETRY_MONITOR_H - -#include "delegate/DelegateOpt.h" -#include "delegate/DelegateRemote.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "TransportMonitor.h" -#include - -namespace dmq::util { - -/// @file RetryMonitor.h -/// @brief Automatic retransmission manager for DelegateMQ remote calls. -/// -/// @details -/// The RetryMonitor acts as a reliability decorator for any ITransport implementation. -/// It bridges the gap between detection (TransportMonitor) and recovery (Physical Transport). -/// -/// ### Core Responsibilities -/// 1. **Data Persistence**: Stores the fully serialized binary payload of every outgoing -/// remote delegate call, indexed by its unique Sequence Number. -/// 2. **Timeout Handling**: Subscribes to the `TransportMonitor::OnSendStatus` signal. -/// 3. **Automatic Recovery**: If a TIMEOUT status is received, it decrements the retry -/// counter and re-submits the exact binary packet to the transport. -/// 4. **Cleanup**: Discards stored packets upon SUCCESS (ACK received) or when -/// `maxRetries` is exhausted. -/// -/// ### Sequence Number Integrity -/// Retries use the **original** sequence number. This allows the Receiver to perform -/// idempotency checks (filtering out duplicate calls if an ACK was lost but the -/// function was already executed). -/// -/// ### Reentrancy Note -/// This class calls `ITransport::Send()`. If the underlying transport (e.g., SerialTransport) -/// routes its high-level `Send()` back into this monitor, the transport MUST implement -/// a reentrancy guard to prevent infinite recursion. -/// -/// @see https://github.com/DelegateMQ/DelegateMQ -class RetryMonitor -{ - XALLOCATOR -public: - /// @brief Storage for a message that might need retransmission. - struct RetryEntry { - dmq::xstring packetData; ///< The raw serialized arguments - dmq::transport::DmqHeader header; ///< Original metadata (ID, SeqNum, etc.) - int attemptsRemaining; ///< Counter for retry budget - bool isSent = false; ///< Flag to prevent TOCTOU races - }; - - /// Signal emitted when a message is permanently abandoned: either a synchronous - /// send attempt failed immediately (TransportMonitor::Add() or ITransport::Send() - /// itself failed, before any retry could be attempted) or the message exhausted - /// its retry budget without being ACKed. A send rejected because its sequence - /// number is still in use by an earlier in-flight message is reported only by - /// SendWithRetry()'s -1 return. Subscribers receive: (remoteId, seqNum); - /// no further retries or status callbacks will occur for this seqNum. - /// Fired outside the internal lock so subscribers may call back into RetryMonitor safely. - dmq::Signal OnDeliveryFailed; - - RetryMonitor() = default; - - /// @brief Constructor - /// @param transport The underlying transport to use for re-sending. - /// @param monitor The monitor that detects the timeouts. - /// @param maxRetries Number of retries before giving up. - /// Default is dmq::RETRY_MONITOR_MAX_RETRIES (DMQ_RETRY_MONITOR_MAX_RETRIES - /// in delegatemqconfig.h). - RetryMonitor(dmq::transport::ITransport& transport, TransportMonitor& monitor, - int maxRetries = dmq::RETRY_MONITOR_MAX_RETRIES) - { - Init(transport, monitor, maxRetries); - } - - void Init(dmq::transport::ITransport& transport, TransportMonitor& monitor, - int maxRetries = dmq::RETRY_MONITOR_MAX_RETRIES) - { - m_transport = &transport; - m_monitor = &monitor; - m_maxRetries = maxRetries; - m_connection = m_monitor->OnSendStatus.Connect(dmq::MakeDelegate(this, &RetryMonitor::OnStatusChanged)); - } - - ~RetryMonitor() { - m_connection.Disconnect(); - - const dmq::LockGuard lock(m_lock); - m_retryStore.clear(); - } - - /// @brief Resends after the first attempt before a message is abandoned. - int GetMaxRetries() const { return m_maxRetries; } - - /// @brief Sends a message and tracks it for potential retries. - /// @return 0 on success, -1 on immediate transport failure. - int SendWithRetry(dmq::xostringstream& os, const dmq::transport::DmqHeader& header) - { - DMQ_ASSERT_TRUE(m_transport != nullptr); - // Critical Section: Store the packet for retry before sending. - // If Send() fails we remove the entry immediately so it doesn't leak. - uint32_t key = (static_cast(header.GetId()) << 16) | header.GetSeqNum(); - bool collision = false; - { - dmq::LockGuard lock(m_lock); - - // The 16-bit sequence number wrapped while an earlier message with the - // same key is still awaiting its ACK. Reject the new send and leave the - // earlier entry alone: overwriting it would lose its retry data. - collision = m_retryStore.find(key) != m_retryStore.end(); - if (!collision) { - RetryEntry entry; - entry.attemptsRemaining = m_maxRetries; - entry.header = header; - entry.packetData = os.str(); // Copy data - entry.isSent = false; // Mark as NOT yet sent to physical transport - m_retryStore[key] = entry; - } - } - if (collision) { - // Reported only through the -1 return (the sender's delegate raises - // ERR_DISPATCH). Not through OnDeliveryFailed: that is keyed by - // (remoteId, seqNum), which here names the earlier message, still in - // flight. Firing it would report that message as failed. - LOG_ERROR("RetryMonitor: SeqNum wraparound collision for seq {}", header.GetSeqNum()); - return -1; - } - - // Non-Critical Section: Send via Transport. - // We must NOT hold m_lock while calling Send(). - // Send() calls TransportMonitor::Add(), which takes its own lock. - bool added = true; - if (m_monitor) - added = m_monitor->Add(header.GetSeqNum(), header.GetId()); - - if (!added) { - { - dmq::LockGuard lock(m_lock); - m_retryStore.erase(key); - } - LOG_ERROR("RetryMonitor: TransportMonitor::Add() failed for seq {}", header.GetSeqNum()); - OnDeliveryFailed(header.GetId(), header.GetSeqNum()); - return -1; - } - - int result = m_transport->Send(os, header); - - // If the send failed, TransportMonitor::Add() already succeeded above, so - // this entry is sitting in TransportMonitor's pending map. Cancel() frees - // that slot immediately (silently -- no false SUCCESS/TIMEOUT signal) instead - // of leaving it to occupy a slot until TRANSPORT_TIMEOUT expires naturally. - // Report the failure now so it isn't silently lost. - if (result != 0) - { - if (m_monitor) - m_monitor->Cancel(header.GetSeqNum(), header.GetId()); - size_t erased = 0; - { - dmq::LockGuard lock(m_lock); - erased = m_retryStore.erase(key); - } - // erased == 0: OnStatusChanged() already abandoned the entry and - // reported it (failed re-register while this Send() was running). - if (erased > 0) { - LOG_ERROR("RetryMonitor: immediate Send() failure for seq {}", header.GetSeqNum()); - OnDeliveryFailed(header.GetId(), header.GetSeqNum()); - } - } - else - { - // SUCCESS: Mark the entry as sent so OnStatusChanged can retry if needed. - dmq::LockGuard lock(m_lock); - auto it = m_retryStore.find(key); - if (it != m_retryStore.end()) { - it->second.isSent = true; - } - } - - return result; - } - -private: - void OnStatusChanged(dmq::DelegateRemoteId id, uint16_t seqNum, TransportMonitor::Status status) - { - // Variables to hold data for the retry OUTSIDE the lock - bool shouldRetry = false; - bool shouldReregister = false; - bool shouldReportFailure = false; - dmq::xstring retryPayload; - dmq::transport::DmqHeader retryHeader; - uint32_t key = (static_cast(id) << 16) | seqNum; - - { - // 1. Critical Section: Read/Modify Map ONLY - const dmq::LockGuard lock(m_lock); - - auto it = m_retryStore.find(key); - if (it == m_retryStore.end()) return; - - if (status == TransportMonitor::Status::SUCCESS) - { - // Message arrived safely, we can forget about the data now - m_retryStore.erase(it); - return; // Done - } - else if (status == TransportMonitor::Status::TIMEOUT) - { - // ONLY retry if the message has actually finished its first physical send. - // If isSent is false, it means SendWithRetry is still executing m_transport->Send(). - if (it->second.attemptsRemaining > 0 && it->second.isSent) - { - // Decrement counter - it->second.attemptsRemaining--; - - // COPY data to local variables so we can use them after unlocking - retryPayload = it->second.packetData; - retryHeader = it->second.header; - shouldRetry = true; - } - else if (it->second.attemptsRemaining > 0 && !it->second.isSent) - { - // TIMEOUT fired while the initial Send() is still executing. - // TransportMonitor has already erased its pending entry, so no - // further callbacks will fire unless we re-register. Re-add to - // TransportMonitor so monitoring continues; do not decrement - // attemptsRemaining — the first send has not completed yet. - retryHeader = it->second.header; - shouldReregister = true; - } - else if (it->second.attemptsRemaining <= 0) - { - // Max retries exceeded. Clean up. - m_retryStore.erase(it); - shouldReportFailure = true; - } - } - } // <--- LOCK IS RELEASED HERE - - // 2. Non-Critical Section: Perform blocking network operations - if (shouldRetry && m_transport) - { - dmq::xostringstream os(std::ios::in | std::ios::out | std::ios::binary); - os.write(retryPayload.data(), retryPayload.size()); - - bool added = true; - if (m_monitor) - added = m_monitor->Add(retryHeader.GetSeqNum(), retryHeader.GetId()); - - if (added) { - int result = m_transport->Send(os, retryHeader); - if (result != 0) { - // Same reasoning as SendWithRetry's immediate-failure path: Add() - // already succeeded, so cancel it silently rather than leaving the - // slot occupied until TRANSPORT_TIMEOUT expires naturally. - if (m_monitor) - m_monitor->Cancel(retryHeader.GetSeqNum(), retryHeader.GetId()); - { - dmq::LockGuard lock(m_lock); - m_retryStore.erase(key); - } - LOG_ERROR("RetryMonitor: immediate Send() failure while retrying seq {}", seqNum); - OnDeliveryFailed(id, seqNum); - } - } else { - { - dmq::LockGuard lock(m_lock); - m_retryStore.erase(key); - } - LOG_ERROR("RetryMonitor: TransportMonitor::Add() failed while retrying seq {}", seqNum); - OnDeliveryFailed(id, seqNum); - } - } - - if (shouldReregister && m_monitor) - { - if (!m_monitor->Add(retryHeader.GetSeqNum(), retryHeader.GetId())) { - // Nothing is tracking this message any more, so no further status - // will arrive for it. Abandon it now rather than leak the entry. - // SendWithRetry() may still be inside Send(); it finds the entry - // gone and doesn't report again. - size_t erased = 0; - { - dmq::LockGuard lock(m_lock); - erased = m_retryStore.erase(key); - } - if (erased > 0) { - LOG_ERROR("RetryMonitor: TransportMonitor::Add() failed while re-registering seq {}", seqNum); - OnDeliveryFailed(id, seqNum); - } - } - } - - if (shouldReportFailure) - { - LOG_ERROR("RetryMonitor: Max retries exceeded for seq {}", seqNum); - OnDeliveryFailed(id, seqNum); - } - } - - dmq::transport::ITransport* m_transport = nullptr; - TransportMonitor* m_monitor = nullptr; - int m_maxRetries = dmq::RETRY_MONITOR_MAX_RETRIES; - dmq::xmap m_retryStore; - dmq::RecursiveMutex m_lock; - dmq::ScopedConnection m_connection; -}; - -} // namespace dmq::util - - -#endif // _RETRY_MONITOR_H diff --git a/DelegateMQ/extras/util/ThreadMonitor.cpp b/DelegateMQ/extras/util/ThreadMonitor.cpp deleted file mode 100644 index a515069..0000000 --- a/DelegateMQ/extras/util/ThreadMonitor.cpp +++ /dev/null @@ -1,124 +0,0 @@ -// ThreadMonitor publishes per-thread stats gathered by Thread::SnapshotStats(), -// which only exists when DMQ_DATABUS_TOOLS is enabled (desktop default; off on -// embedded DataBus builds -- see DelegateSelect.h). Otherwise this file -// compiles to nothing, so it can stay in a build that adds every DelegateMQ -// source file (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_HAS_THREADING) && defined(DMQ_DATABUS) && defined(DMQ_DATABUS_TOOLS) - -#include "ThreadMonitor.h" -#include "DelegateMQ.h" - -#include -#include - -namespace dmq::util { -// ... rest of namespace dmq::util content ... - -ThreadMonitor::~ThreadMonitor() { - Disable(); -} - -void ThreadMonitor::Register(dmq::os::Thread* thread) { - if (!thread) return; - auto& instance = GetInstance(); - dmq::LockGuard lock(instance.m_mutex); - for (size_t i = 0; i < instance.m_threadCount; ++i) { - if (instance.m_threads[i] == thread) return; - } - if (instance.m_threadCount < dmq::MAX_WATCHDOG_THREADS) - instance.m_threads[instance.m_threadCount++] = thread; - else - DMQ_ASSERT(); -} - -void ThreadMonitor::Deregister(dmq::os::Thread* thread) { - if (!thread) return; - auto& instance = GetInstance(); - dmq::LockGuard lock(instance.m_mutex); - for (size_t i = 0; i < instance.m_threadCount; ++i) { - if (instance.m_threads[i] == thread) { - instance.m_threads[i] = instance.m_threads[--instance.m_threadCount]; - instance.m_threads[instance.m_threadCount] = nullptr; - return; - } - } -} - -void ThreadMonitor::Enable(const dmq::xstring& topic) { - auto& instance = GetInstance(); - if (instance.m_enabled.exchange(true)) return; - - instance.m_topic = topic; - - dmq::LockGuard lock(instance.m_mutex); - instance.m_monitorThread.emplace("ThreadMonitor", 10); - instance.m_monitorThread->CreateThread(); - - (void)dmq::MakeDelegate(&instance, &ThreadMonitor::MonitorLoop, *instance.m_monitorThread).AsyncInvoke(); -} - -void ThreadMonitor::Disable() { - auto& instance = GetInstance(); - if (!instance.m_enabled.exchange(false)) return; - - // ExitThread() must not be called while holding m_mutex: MonitorLoop - // acquires m_mutex after Sleep() to check m_enabled before re-arming, - // which would deadlock if Disable() held the lock across the join. - if (instance.m_monitorThread) { - instance.m_monitorThread->ExitThread(); - } - - dmq::LockGuard lock(instance.m_mutex); - instance.m_monitorThread.reset(); -} - -void ThreadMonitor::MonitorLoop() { - if (!m_enabled) return; - - std::array snapshots; - size_t snapshotCount = 0; - { - dmq::LockGuard lock(m_mutex); - for (size_t i = 0; i < dmq::MAX_WATCHDOG_THREADS; ++i) { - if (i >= m_threadCount || snapshotCount >= dmq::MAX_WATCHDOG_THREADS) - break; - - if (m_threads[i] != nullptr) { - snapshots[snapshotCount++] = m_threads[i]->SnapshotStats(); - } - } - } - - for (size_t i = 0; i < snapshotCount; ++i) { - const auto& s = snapshots[i]; - ThreadStatsPacket packet; - packet.cpu_name = s.cpu_name; - packet.thread_name = s.thread_name; - packet.queue_depth = static_cast(s.queue_depth); - packet.queue_depth_max_window = static_cast(s.queue_depth_max_window); - packet.queue_depth_max_all = static_cast(s.queue_depth_max_all); - packet.queue_size_limit = static_cast(s.queue_size_limit); - packet.latency_avg_ms = s.latency_avg_ms; - packet.latency_max_window_ms = s.latency_max_window_ms; - packet.latency_max_all_ms = s.latency_max_all_ms; - packet.invoke_avg_ms = s.invoke_avg_ms; - packet.invoke_max_window_ms = s.invoke_max_window_ms; - packet.invoke_max_all_ms = s.invoke_max_all_ms; - packet.dispatch_count = s.dispatch_count; - - dmq::databus::DataBus::Publish(m_topic, packet); - } - - if (m_enabled) { - dmq::os::Thread::Sleep(std::chrono::seconds(2)); - - dmq::LockGuard lock(m_mutex); - if (m_enabled && m_monitorThread.has_value()) - (void)dmq::MakeDelegate(this, &ThreadMonitor::MonitorLoop, *m_monitorThread).AsyncInvoke(); - } -} - -} // namespace dmq::util - -#endif // DMQ_DATABUS && DMQ_DATABUS_TOOLS diff --git a/DelegateMQ/extras/util/ThreadMonitor.h b/DelegateMQ/extras/util/ThreadMonitor.h deleted file mode 100644 index aecdfc9..0000000 --- a/DelegateMQ/extras/util/ThreadMonitor.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef THREAD_MONITOR_H -#define THREAD_MONITOR_H - -#include "DelegateMQ.h" - -// ThreadMonitor publishes per-thread stats gathered by Thread::SnapshotStats(), -// which only exists when DMQ_DATABUS_TOOLS is enabled (desktop default; off on -// embedded DataBus builds -- see DelegateOpt.h). -#if defined(DMQ_DATABUS) && defined(DMQ_DATABUS_TOOLS) - -#include -#include -#include - -namespace dmq::util { -// ... rest of namespace dmq::util content ... - -/// @brief Packet published to DataBus for thread monitoring. -struct ThreadStatsPacket { - dmq::xstring cpu_name; - dmq::xstring thread_name; - uint32_t queue_depth = 0; - uint32_t queue_depth_max_window = 0; - uint32_t queue_depth_max_all = 0; - uint32_t queue_size_limit = 0; - float latency_avg_ms = 0.0f; - float latency_max_window_ms = 0.0f; - float latency_max_all_ms = 0.0f; - float invoke_avg_ms = 0.0f; - float invoke_max_window_ms = 0.0f; - float invoke_max_all_ms = 0.0f; - uint64_t dispatch_count = 0; -}; - -/// @brief Central monitor that polls registered threads and publishes stats. -class ThreadMonitor { -public: - /// Register a thread for monitoring. - static void Register(dmq::os::Thread* thread); - - /// Deregister a thread. - static void Deregister(dmq::os::Thread* thread); - - /// Enable the monitor (starts the 2-second polling loop). - static void Enable(const dmq::xstring& topic = "ThreadStats"); - - /// Disable the monitor. - static void Disable(); - -private: - ThreadMonitor() = default; - ~ThreadMonitor(); - - static ThreadMonitor& GetInstance() { - static ThreadMonitor instance; - return instance; - } - - void MonitorLoop(); - - std::array m_threads{}; - size_t m_threadCount = 0; - dmq::Mutex m_mutex; - std::optional m_monitorThread; - std::atomic m_enabled{false}; - dmq::xstring m_topic; -}; - -} // namespace dmq::util - -#endif // DMQ_DATABUS && DMQ_DATABUS_TOOLS - -#endif diff --git a/DelegateMQ/extras/util/ThreadMonitorSer.h b/DelegateMQ/extras/util/ThreadMonitorSer.h deleted file mode 100644 index 7cf3a7a..0000000 --- a/DelegateMQ/extras/util/ThreadMonitorSer.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef THREAD_MONITOR_SER_H -#define THREAD_MONITOR_SER_H - -#include "ThreadMonitor.h" -#include "port/serialize/serialize/msg_serialize.h" -#include - -namespace dmq::util { - -/// @brief Serializer for ThreadStatsPacket. -class ThreadStatsPacketSerializer : public dmq::ISerializer { -public: - virtual std::ostream& Write(std::ostream& os, const ThreadStatsPacket& data) override { - serialize s; - s.write(os, data.cpu_name); - s.write(os, data.thread_name); - s.write(os, data.queue_depth); - s.write(os, data.queue_depth_max_window); - s.write(os, data.queue_depth_max_all); - s.write(os, data.queue_size_limit); - s.write(os, data.latency_avg_ms); - s.write(os, data.latency_max_window_ms); - s.write(os, data.latency_max_all_ms); - s.write(os, data.invoke_avg_ms); - s.write(os, data.invoke_max_window_ms); - s.write(os, data.invoke_max_all_ms); - s.write(os, data.dispatch_count); - return os; - } - - virtual std::istream& Read(std::istream& is, ThreadStatsPacket& data) override { - serialize s; - s.read(is, data.cpu_name); - s.read(is, data.thread_name); - s.read(is, data.queue_depth); - s.read(is, data.queue_depth_max_window); - s.read(is, data.queue_depth_max_all); - s.read(is, data.queue_size_limit); - s.read(is, data.latency_avg_ms); - s.read(is, data.latency_max_window_ms); - s.read(is, data.latency_max_all_ms); - s.read(is, data.invoke_avg_ms); - s.read(is, data.invoke_max_window_ms); - s.read(is, data.invoke_max_all_ms); - s.read(is, data.dispatch_count); - return is; - } -}; - -/// @brief Stringifier for ThreadStatsPacket (for DataSpy). -inline dmq::xstring ThreadStatsPacketToString(const ThreadStatsPacket& p) { - dmq::xstringstream ss; - ss << "CPU:" << p.cpu_name << " Thread:" << p.thread_name - << " Q:" << p.queue_depth << "/" << p.queue_depth_max_window << "/" << p.queue_depth_max_all - << " Latency(ms):" << std::fixed << std::setprecision(2) << p.latency_avg_ms << "/" << p.latency_max_window_ms - << " Invoke(ms):" << std::fixed << std::setprecision(2) << p.invoke_avg_ms << "/" << p.invoke_max_window_ms; - return ss.str(); -} - -} // namespace dmq::util - -#endif diff --git a/DelegateMQ/extras/util/Timer.cpp b/DelegateMQ/extras/util/Timer.cpp deleted file mode 100644 index 7f5f67d..0000000 --- a/DelegateMQ/extras/util/Timer.cpp +++ /dev/null @@ -1,252 +0,0 @@ -#include "Timer.h" -#include "Fault.h" -#include -#include -#include - -namespace dmq::util { - - -std::atomic Timer::m_timerStopped{false}; - -//------------------------------------------------------------------------------ -// Constructor -//------------------------------------------------------------------------------ -Timer::Timer() -{ - const dmq::LockGuard lock(GetLock()); - m_enabled = false; -} - -//------------------------------------------------------------------------------ -// Destructor -//------------------------------------------------------------------------------ -Timer::~Timer() -{ - // Wait out a ProcessTimers() that found this timer expired and hasn't - // copied its subscribers yet (see GetProcessLock()). - const dmq::LockGuard processLock(GetProcessLock()); - const dmq::LockGuard lock(GetLock()); - - // Remove 'this' from the intrusive linked list - Timer** pp = &GetTimersHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_next; - this->m_next = nullptr; - break; - } - pp = &((*pp)->m_next); - } -} - -//------------------------------------------------------------------------------ -// Start -//------------------------------------------------------------------------------ -void Timer::Start(dmq::Duration timeout, bool once) -{ - if (timeout <= dmq::Duration(0)) { -#if !defined(__cpp_exceptions) || defined(DMQ_ASSERTS) - // Use the macro from Fault.h to halt the system - DMQ_ASSERT(); - return; -#else - throw std::invalid_argument("Timeout cannot be 0"); -#endif - } - - const dmq::LockGuard lock(GetLock()); - - m_timeout = timeout; - m_once = once; - m_expireTime = GetNow() + m_timeout; - m_enabled = true; - - // Search for 'this' in the intrusive list - bool found = false; - Timer* p = GetTimersHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_next; - } - - // Only add if not already in the list. - if (!found) - { - m_next = GetTimersHead(); - GetTimersHead() = this; - } - - LOG_INFO("Timer::Start timeout={}", m_timeout.count()); -} - -//------------------------------------------------------------------------------ -// Stop -//------------------------------------------------------------------------------ -void Timer::Stop() -{ - const dmq::LockGuard lock(GetLock()); - - m_enabled = false; - - // Don't remove immediately! Just set a flag. - // Let ProcessTimers() handle the actual removal safely. - m_timerStopped = true; - - LOG_INFO("Timer::Stop timeout={}", m_timeout.count()); -} - -//------------------------------------------------------------------------------ -// CheckExpired -//------------------------------------------------------------------------------ -bool Timer::CheckExpired() -{ - if (!m_enabled) - return false; - - // Has the timer expired? - if (GetNow() < m_expireTime) - return false; // Not expired yet - - if (m_once) - { - m_enabled = false; - m_timerStopped = true; - } - else - { - // Increment the timer to the next expiration - m_expireTime += m_timeout; - - // Check if we are still behind (timer starvation) - // If the new deadline is STILL in the past, we are falling behind. - const dmq::TimePoint now = GetNow(); - if (now > m_expireTime) - { - // The timer has fallen behind. Skip the missed periods and expire one - // full period from now; expiring at `now` would fire again on the - // very next ProcessTimers() call. - m_expireTime = now + m_timeout; - - // Timer processing is falling behind. Maybe user timer expiration is too - // short, time processing takings too long, or CheckExpired not called - // frequently enough. - LOG_INFO("Timer::CheckExpired Timer Processing Falling Behind"); - } - } - - return true; -} - -//------------------------------------------------------------------------------ -// ProcessTimers -//------------------------------------------------------------------------------ -void Timer::ProcessTimers() -{ - // Drains all expired timers across multiple passes so a single call always - // fully clears the backlog, regardless of how many timers expired in the - // same tick — mirrors TransportMonitor::Process()'s identical "batch cap - // exceeded mid-drain" handling for the same MAX_TIMER_EXPIRED-sized batch. - size_t count; - - do { - std::array::Snapshot, dmq::MAX_TIMER_EXPIRED> snapshots; - count = 0; - size_t remaining = 0; - - { - // Held until every timer found expired below has had its subscribers - // copied. ~Timer() takes it too, so none of those timers can be - // destroyed in between. - const dmq::LockGuard processLock(GetProcessLock()); - - std::array expired; - { - const dmq::LockGuard lock(GetLock()); - - // Remove disabled timer from the list if stopped - if (m_timerStopped) - { - Timer** pp = &GetTimersHead(); - while (*pp != nullptr) - { - if (!((*pp)->m_enabled)) - { - Timer* next = (*pp)->m_next; - (*pp)->m_next = nullptr; - *pp = next; - } - else - { - pp = &((*pp)->m_next); - } - } - m_timerStopped = false; - } - - // Identify expired timers while holding the lock. - Timer* t = GetTimersHead(); - while (t != nullptr) - { - if (count >= dmq::MAX_TIMER_EXPIRED) { - // Batch is full for this pass. Deliberately do NOT call - // CheckExpired() on the remaining timers here — that would - // mutate their expiry state (advance m_expireTime / disable - // a one-shot) without capturing a snapshot, permanently - // dropping that expiration. Leaving them untouched lets the - // next pass process them correctly. - Timer* rem = t; - while (rem != nullptr) { ++remaining; rem = rem->m_next; } - break; - } - - if (t->CheckExpired()) - expired[count++] = t; - t = t->m_next; - } - } - - // Copy each expired timer's subscribers outside the critical section: - // GetSnapshot() takes the signal's OS mutexes and can allocate, neither - // of which is allowed with interrupts masked. - for (size_t i = 0; i < count; ++i) - snapshots[i] = expired[i]->OnExpired.GetSnapshot(); - } - - // Call the client's expired callback functions outside the lock. - // This allows callbacks to perform thread-safe operations (like DataBus::Publish) - // without risking a deadlock with the global timer lock. - // The Snapshot holds shared_ptrs to the delegates, so even if a Timer - // was deleted on another thread after the lock was released, the - // callback targets remain valid. - for (size_t i = 0; i < count; ++i) - { - dmq::Signal::InvokeSnapshot(snapshots[i]); - snapshots[i] = {}; // release shared_ptr refs so delegates aren't held between calls - } - - if (remaining > 0) { - LOG_ERROR("Timer::ProcessTimers: batch cap reached, {} timers remain — continuing drain.", remaining); - } - - } while (count == dmq::MAX_TIMER_EXPIRED); -} - -//------------------------------------------------------------------------------ -// GetNow -//------------------------------------------------------------------------------ -dmq::TimePoint Timer::GetNow() -{ - // time_point_cast converts the internal clock resolution (nanos) - // to your custom resolution (millis) inside the time_point wrapper. - return std::chrono::time_point_cast(dmq::Clock::now()); -} - -} // namespace dmq::util \ No newline at end of file diff --git a/DelegateMQ/extras/util/Timer.h b/DelegateMQ/extras/util/Timer.h deleted file mode 100644 index 1ed0d6a..0000000 --- a/DelegateMQ/extras/util/Timer.h +++ /dev/null @@ -1,151 +0,0 @@ -#ifndef _TIMER_H -#define _TIMER_H - -#include "../../delegate/DelegateOpt.h" -#include "../../delegate/Signal.h" -#include -#include -#include - -namespace dmq::util { - -/// @brief A thread-safe timer class that provides periodic or one-shot callbacks. -/// -/// @details -/// The Timer class allows clients to register for callbacks (`OnExpired`) that are invoked -/// when a specified timeout interval elapses. -/// -/// **Key Features:** -/// * **Thread Safe:** All public API methods (`Start`, `Stop`, etc.) are thread-safe and can be called -/// from any thread. -/// * **Flexible Modes:** Supports both one-shot (`once = true`) and periodic (`once = false`) operation. -/// * **Deterministic Execution:** Callbacks are invoked on the thread that calls `ProcessTimers()`. -/// This allows the user to control exactly which thread executes the timer logic (e.g., Main Thread, -/// GUI Thread, or a dedicated Worker Thread). -/// -/// **Usage — Preferred Pattern:** -/// Call `ProcessTimers()` from the highest-priority context that can preempt all watched threads. -/// On an RTOS port (FreeRTOS, ThreadX, Zephyr, CMSIS-RTOS2, NuttX) that is the highest-priority -/// task, never an ISR: `ProcessTimers()` takes OS mutexes to copy each expired timer's -/// subscribers. Only bare metal (`DMQ_THREAD_NONE`, no OS mutexes) can call it from a hardware -/// timer ISR. Connect `OnExpired` to one of: -/// - A plain (synchronous) delegate for inline, fast callbacks (no blocking, no allocation). -/// - An async delegate (`MakeDelegate(..., thread)`) to dispatch work to a worker thread. -/// The target thread MUST use `FullPolicy::FAULT` or `FullPolicy::DROP` — never `TIMEOUT`. -/// (`FAULT` crashes immediately if the queue is full, making overflow visible during testing; -/// `DROP` silently skips the dispatch, which is acceptable for periodic heartbeats.) -/// -/// **ProcessTimers() Blocking Invariant:** -/// `ProcessTimers()` MUST NEVER block. Violating this starves the timer subsystem and defeats -/// the watchdog. Three known causes: -/// -/// **Cause 1 — Async dispatch to a TIMEOUT-policy thread:** -/// `MakeDelegate(fn, thread)()` inside a timer callback calls `DispatchDelegate()` on the -/// target thread. If that thread's queue is full and its policy is `FullPolicy::TIMEOUT`, -/// `ProcessTimers()` stalls for up to `dispatchTimeout` (default 2 s). Fix: target threads -/// that receive timer dispatches must use `FAULT` or `DROP`, never `TIMEOUT`. -/// -/// **Cause 2 — DelegateAsyncWait connected to OnExpired:** -/// `DelegateAsyncWait` blocks its caller until the target thread returns the result. -/// If one is connected to `OnExpired`, `ProcessTimers()` blocks indefinitely waiting -/// for the remote call to complete. Fix: never connect `DelegateAsyncWait` to a timer signal. -/// Only plain async delegates (`MakeDelegate(..., thread)`) are safe for timer callbacks. -/// -/// **Cause 3 — Slow synchronous callback:** -/// A plain (non-async) delegate connected to `OnExpired` runs inline inside `ProcessTimers()`. -/// If that function acquires a lock, does I/O, or otherwise takes significant time, -/// `ProcessTimers()` is delayed for that duration. Fix: keep synchronous timer callbacks fast; -/// dispatch any slow work asynchronously to a worker thread instead. -/// -/// @see SafeTimer.cpp for examples on how to handle callbacks safely with object lifetimes. -class Timer -{ - XALLOCATOR -public: - /// Clients connect to OnExpired to get timer expiration callbacks. - dmq::Signal OnExpired; - - /// Constructor - Timer(void); - - /// Destructor - ~Timer(void); - - /// Starts a timer for callbacks on the specified timeout interval. - /// @param[in] timeout - the timeout. - /// @param[in] once - true if only one timer expiration - void Start(dmq::Duration timeout, bool once = false); - - /// Stops a timer. - void Stop(); - - /// Gets the enabled state of a timer. - /// @return TRUE if the timer is enabled, FALSE otherwise. - bool Enabled() { return m_enabled; } - - /// Get the time. - /// @return The time now. - static dmq::TimePoint GetNow(); - - /// Called on a periodic basic to service all timer instances. - /// @TODO: Call periodically for timer expiration handling. - static void ProcessTimers(); - -private: - // Prevent inadvertent copying of this object - Timer(const Timer&); - Timer& operator=(const Timer&); - - /// Called to check for expired timers and callback registered clients. - bool CheckExpired(); - - /// Get list head using the "Immortal" Pattern - static Timer*& GetTimersHead() - { - // Static head pointer. NEVER delete. Prevents lock from being destroyed - // before the last Timer destructor runs at app shutdown. - static Timer* head = nullptr; - return head; - } - - /// Get lock using the "Immortal" Pattern. Guards the timer list and each - /// timer's state; held only for short, bounded list work. - /// @note dmq::CriticalSection, not dmq::RecursiveMutex, so the list scan in - /// ProcessTimers() never blocks on an OS mutex and bare metal can run it from - /// a hardware ISR. Nothing that can block or allocate may run under it - /// (see GetProcessLock()). - static dmq::CriticalSection& GetLock() - { - // Allocate on heap and NEVER delete. Prevents lock from being destroyed - // before the last Timer destructor runs at app shutdown. - static dmq::CriticalSection* lock = new(std::nothrow) dmq::CriticalSection(); - if (!lock) - BAD_ALLOC(); - return *lock; - } - - /// Held by ProcessTimers() from finding the expired timers until their - /// subscribers are copied, and by ~Timer() before it unlinks itself, so a - /// timer can't be destroyed in between. Copying the subscribers takes the - /// signal's OS mutexes and can allocate, so it can't happen under GetLock(). - /// Lock order: this, then GetLock(). Not held while callbacks run. - static dmq::RecursiveMutex& GetProcessLock() - { - // Immortal, like GetLock(). - static dmq::RecursiveMutex* lock = new(std::nothrow) dmq::RecursiveMutex(); - if (!lock) - BAD_ALLOC(); - return *lock; - } - - dmq::Duration m_timeout = dmq::Duration(0); - dmq::TimePoint m_expireTime; - std::atomic m_enabled{false}; - bool m_once = false; - Timer* m_next = nullptr; - static std::atomic m_timerStopped; -}; - -} // namespace dmq::util - -#endif diff --git a/DelegateMQ/extras/util/TimerDelegate.h b/DelegateMQ/extras/util/TimerDelegate.h deleted file mode 100644 index e8804d4..0000000 --- a/DelegateMQ/extras/util/TimerDelegate.h +++ /dev/null @@ -1,374 +0,0 @@ -#ifndef TIMER_DELEGATE_H -#define TIMER_DELEGATE_H - -#include "Timer.h" -#include "../../delegate/DelegateAsync.h" -#include "../../delegate/UnicastDelegate.h" -#include - -namespace dmq::util { - -/// @brief Tag type whose lifetime tracks a dispatched message through the thread queue. -/// When the async closure is destroyed after Invoke() completes (or immediately on DROP), -/// the reference count falls to zero and the paired weak_ptr in PacedDispatch expires. -struct DispatchToken { - XALLOCATOR -}; - -/// @brief Gate that enforces at-most-one-in-flight dispatch for a periodic timer source. -/// -/// Solves two problems when a periodic timer drives an async dispatch: -/// - ProcessTimers() stalling: skips DispatchDelegate() entirely if previous message -/// is still queued, so ProcessTimers() never blocks on a TIMEOUT-policy thread. -/// - Queue flooding: at most one pending callback exists at any time; a slow thread -/// won't accumulate a backlog of stale timer events. -/// -/// The caller captures the shared_ptr inside the async lambda. When -/// Invoke() completes and the DelegateMsg is destroyed, the token's ref count drops to -/// zero, the weak_ptr expires, and the next TryFire() can proceed. -/// -/// If the message is dropped (FullPolicy::DROP), the DelegateMsg destructs immediately, -/// the token dies, and TryFire() retries on the next timer expiry. -/// -/// @note Not thread-safe for concurrent TryFire() calls. Safe when ProcessTimers() runs -/// on a single thread, which is the standard usage. -/// @note OnStuck fires from ProcessTimers() context -- keep it fast and non-blocking. -class PacedDispatch -{ - XALLOCATOR -public: - /// @brief Attempt a dispatch if no previous one is in flight. - /// - /// @param dispatchFn Callable receiving a shared_ptr by value. - /// Must capture the token in the async closure so its lifetime - /// tracks the message through the queue. - /// @param stuckTimeout If non-zero and the token is still live after this duration, - /// OnStuck is called. Default: disabled. - /// @return true if dispatch was attempted; false if skipped (already in flight). - template - bool TryFire(F&& dispatchFn, dmq::Duration stuckTimeout = dmq::Duration(0)) - { - if (!m_inFlight.expired()) - { - if (stuckTimeout.count() > 0 && OnStuck) - { - if (Timer::GetNow() - m_dispatchTime > stuckTimeout) - OnStuck(); - } - m_pending = true; - return false; - } - - m_pending = false; - - auto token = dmq::xmake_shared(); - m_inFlight = token; - m_dispatchTime = Timer::GetNow(); - - dispatchFn(std::move(token)); - return true; - } - - bool IsInFlight() const { return !m_inFlight.expired(); } - bool IsPending() const { return m_pending; } - void Reset() { m_inFlight.reset(); m_pending = false; } - - /// Optional. Called from ProcessTimers() context -- must be fast and non-blocking. - dmq::UnicastDelegate OnStuck; - -private: - std::weak_ptr m_inFlight; - dmq::TimePoint m_dispatchTime{}; - bool m_pending = false; -}; - -namespace detail { -/// @brief Target state shared between a TimerDelegate and its queued dispatches. -/// The TimerDelegate owns it; each queued message holds only a weak_ptr, so a -/// message still in the thread queue after the TimerDelegate is destroyed (e.g. -/// its Signal connection was dropped) finds it expired and skips the call -/// instead of touching the deleted TimerDelegate. -struct TimerTarget { - XALLOCATOR - dmq::UnicastDelegate fn; -}; -} // namespace detail - -/// @brief Timer-safe async delegate. Connects a periodic timer to a thread dispatch -/// with built-in queue-flood prevention. -/// -/// Implements Delegate directly so it can be stored in Signal connections -/// without a DelegateFunction wrapper -- eliminating the std::function layer on -/// the hot path. -/// -/// At most one message is in the target thread's queue at any time; excess timer -/// ticks are silently dropped rather than accumulated as backlog. -/// -/// Prefer constructing via MakeTimerDelegate() rather than directly. -/// -/// Destroying, clearing or reassigning a TimerDelegate (including disconnecting the -/// Signal connection that owns it) cancels any tick it has queued that the target -/// thread hasn't started: the target is not invoked. Two cases are not cancelled: -/// - A tick the target thread has already started runs to completion. -/// - Signal::operator() invokes a snapshot of its connections, so a Disconnect() -/// on another thread while Timer::ProcessTimers() is emitting OnExpired can -/// still queue one tick after Disconnect() returns. -/// So disconnecting alone doesn't make it safe to destroy a raw-pointer target. -/// Before freeing the target, stop the timer, disconnect, and let the target -/// thread finish what's queued (e.g. ExitThread(), which drains the queue), as -/// NetworkNode::Stop() does. -/// -/// @note Not intended for concurrent invocation. Safe when operator() is called -/// from a single ProcessTimers() context. -class TimerDelegate : public dmq::Delegate -{ - XALLOCATOR -public: - // Constructor for pre-formed Delegate subtypes (DelegateMember, DelegateFree, etc.). - // Stored directly as a delegate -- no std::function wrapping. - TimerDelegate(const dmq::Delegate& func, dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) - : m_thread(&thr) - , m_stuckTimeout(stuckTimeout) - { - m_fn = func; - m_gate.OnStuck = std::move(onStuck); - } - - // Constructor for raw callables (lambdas, function pointers, functors). - // SFINAE excludes Delegate subtypes so the overload above is preferred for them. - template > || - !std::is_base_of_v, std::decay_t>>> - TimerDelegate(F&& func, dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) - : m_thread(&thr) - , m_stuckTimeout(stuckTimeout) - { - m_fn = dmq::DelegateFunction(std::forward(func)); - m_gate.OnStuck = std::move(onStuck); - } - - // A copy shares no state with the original: its own (lazily allocated) target - // and a fresh gate, so destroying either one cancels only its own queued ticks. - TimerDelegate(const TimerDelegate& rhs) - : m_thread(rhs.m_thread) - , m_stuckTimeout(rhs.m_stuckTimeout) - { - m_fn = rhs.Fn(); - m_gate.OnStuck = rhs.m_gate.OnStuck; - } - - TimerDelegate& operator=(const TimerDelegate& rhs) - { - if (this != &rhs) - { - Clear(); // cancels this delegate's queued ticks - m_fn = rhs.Fn(); - m_thread = rhs.m_thread; - m_stuckTimeout = rhs.m_stuckTimeout; - m_gate.OnStuck = rhs.m_gate.OnStuck; - } - return *this; - } - - // A move transfers the target and gate: ticks the source queued now belong to - // the destination, and the source is left empty. - TimerDelegate(TimerDelegate&& rhs) noexcept - : m_fn(std::move(rhs.m_fn)) - , m_target(std::move(rhs.m_target)) - , m_thread(rhs.m_thread) - , m_stuckTimeout(rhs.m_stuckTimeout) - , m_gate(std::move(rhs.m_gate)) - { - rhs.Clear(); - } - - TimerDelegate& operator=(TimerDelegate&& rhs) noexcept - { - if (this != &rhs) - { - m_fn = std::move(rhs.m_fn); - m_target = std::move(rhs.m_target); // releasing the old target cancels its ticks - m_thread = rhs.m_thread; - m_stuckTimeout = rhs.m_stuckTimeout; - m_gate = std::move(rhs.m_gate); - rhs.Clear(); - } - return *this; - } - - virtual void operator()() override - { - if (Empty()) - return; - // Allocated on the first tick rather than at construction, so the temporary - // that Signal::Connect() clones and discards never allocates. - if (!m_target) - { - m_target = dmq::xmake_shared(); - m_target->fn = std::move(m_fn); - } - std::weak_ptr target = m_target; - dmq::IThread& thr = *m_thread; - m_gate.TryFire([&target, &thr](std::shared_ptr token) { - using DelegateType = dmq::DelegateFreeAsync, std::shared_ptr)>; - DelegateType(&TimerDelegate::InvokeTarget, thr)(std::move(target), std::move(token)); - }, m_stuckTimeout); - } - - virtual TimerDelegate* Clone() const override - { - return new(std::nothrow) TimerDelegate(*this); - } - - virtual bool Equal(const dmq::DelegateBase& rhs) const override - { - auto derived = dynamic_cast(&rhs); - if (!derived) return false; - if (Empty() && derived->Empty()) return true; - if (Empty() || derived->Empty()) return false; - if (!Fn().GetDelegate() || !derived->Fn().GetDelegate()) return false; - return m_thread == derived->m_thread && - Fn().GetDelegate()->Equal(*derived->Fn().GetDelegate()); - } - - virtual bool operator==(std::nullptr_t) const noexcept override { return Empty(); } - virtual bool operator!=(std::nullptr_t) const noexcept override { return !Empty(); } - - bool Empty() const noexcept { return Fn().Empty() || !m_thread; } - - /// Empties the delegate and cancels any tick it has queued that hasn't started. - void Clear() noexcept - { - m_fn.Clear(); - m_target.reset(); - m_thread = nullptr; - m_gate.Reset(); - m_gate.OnStuck.Clear(); - } - void operator=(std::nullptr_t) noexcept { Clear(); } - -private: - // The callable: in m_fn until the first tick, then moved into m_target. - const dmq::UnicastDelegate& Fn() const noexcept { return m_target ? m_target->fn : m_fn; } - - // Runs on the target thread. Static so the queued message never refers to the - // TimerDelegate itself; the token is held until the call returns. - static void InvokeTarget(std::weak_ptr target, std::shared_ptr token) - { - (void)token; - if (auto t = target.lock()) - t->fn(); - } - - dmq::UnicastDelegate m_fn; - std::shared_ptr m_target; - dmq::IThread* m_thread = nullptr; - dmq::Duration m_stuckTimeout{0}; - PacedDispatch m_gate; -}; - -/// @brief Create a timer-safe async delegate for a free function or static member function. -/// -/// @code -/// void OnTick() { ... } -/// m_timerConn = m_timer.OnExpired.Connect(MakeTimerDelegate(&OnTick, m_thread)); -/// @endcode -inline TimerDelegate MakeTimerDelegate( - void(*func)(), - dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) -{ - return TimerDelegate(func, thr, std::move(onStuck), stuckTimeout); -} - -/// @brief Create a timer-safe async delegate for a lambda or other callable. -template -TimerDelegate MakeTimerDelegate( - F&& func, - dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) -{ - return TimerDelegate(std::forward(func), thr, std::move(onStuck), stuckTimeout); -} - -/// @brief Create a timer-safe async delegate for a non-const member function. -/// -/// At most one dispatch is in flight; excess timer ticks are dropped. -/// DelegateAsyncWait is structurally prevented -- dispatch is always non-blocking. -/// -/// @param obj Raw pointer to target object. Must outlive the delegate. -/// @param method void() non-const member function to invoke. -/// @param thr Thread on which method is dispatched. -/// @param onStuck Optional. Called from ProcessTimers() when stuck is detected. -/// @param stuckTimeout Duration after which a non-expiring in-flight token triggers -/// onStuck. Zero disables. -/// -/// @code -/// m_timerConn = m_timer.OnExpired.Connect( -/// MakeTimerDelegate(this, &MyClass::OnTick, m_thread)); -/// -/// // With stuck detection: -/// m_timerConn = m_timer.OnExpired.Connect( -/// MakeTimerDelegate(this, &MyClass::OnTick, m_thread, -/// dmq::MakeDelegate(this, &MyClass::OnThreadStuck), std::chrono::seconds(2))); -/// @endcode -template -TimerDelegate MakeTimerDelegate( - TClass* obj, - void (TClass::*method)(), - dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) -{ - return TimerDelegate(dmq::MakeDelegate(obj, method), thr, std::move(onStuck), stuckTimeout); -} - -/// @brief Create a timer-safe async delegate for a const member function. -template -TimerDelegate MakeTimerDelegate( - const TClass* obj, - void (TClass::*method)() const, - dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) -{ - return TimerDelegate(dmq::MakeDelegate(obj, method), thr, std::move(onStuck), stuckTimeout); -} - -/// @brief Create a timer-safe async delegate for a non-const member function (shared_ptr owner). -/// -/// Captures a weak_ptr internally via DelegateMemberSp. If the object has been destroyed -/// by the time the dispatch fires, the invocation is silently skipped. -template -TimerDelegate MakeTimerDelegate( - std::shared_ptr obj, - void (TClass::*method)(), - dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) -{ - return TimerDelegate(dmq::MakeDelegate(obj, method), thr, std::move(onStuck), stuckTimeout); -} - -/// @brief Create a timer-safe async delegate for a const member function (shared_ptr owner). -template -TimerDelegate MakeTimerDelegate( - std::shared_ptr obj, - void (TClass::*method)() const, - dmq::IThread& thr, - dmq::UnicastDelegate onStuck = dmq::UnicastDelegate(), - dmq::Duration stuckTimeout = dmq::Duration(0)) -{ - return TimerDelegate(dmq::MakeDelegate(obj, method), thr, std::move(onStuck), stuckTimeout); -} - -} // namespace dmq::util - -#endif \ No newline at end of file diff --git a/DelegateMQ/extras/util/TransportMonitor.h b/DelegateMQ/extras/util/TransportMonitor.h deleted file mode 100644 index 1d8a9af..0000000 --- a/DelegateMQ/extras/util/TransportMonitor.h +++ /dev/null @@ -1,247 +0,0 @@ -#ifndef _TRANSPORT_MONITOR_HH -#define _TRANSPORT_MONITOR_HH - -#include "delegate/DelegateOpt.h" -#include "delegate/Signal.h" -#include "../../port/transport/common/ITransportMonitor.h" -#include -#include -#include - -namespace dmq::util { - -/// @brief A thread-safe monitor for tracking outgoing remote messages and detecting timeouts. -/// -/// @details -/// The TransportMonitor implements the reliability layer for remote delegate invocations. -/// It tracks "in-flight" messages by their sequence number and timestamps them upon sending. -/// -/// **Key Responsibilities:** -/// * **Timeout Detection:** Identifies messages that have not been acknowledged within the -/// configured `TRANSPORT_TIMEOUT` duration. -/// * **Status Reporting:** Invokes the `SendStatusCb` delegate with `Status::SUCCESS` (upon ACK) -/// or `Status::TIMEOUT` (upon expiration) to notify the application. -/// * **Thread Safety:** Internal state is protected by a recursive mutex, allowing safe access -/// from multiple threads (e.g., sending thread vs. ACK receiving thread). -/// -/// **Usage Note:** -/// This class relies on a cooperative polling model. The `Process()` method must be called -/// periodically (typically by a background timer or the network thread loop) to scan for -/// and handle expired messages. -class TransportMonitor : public dmq::transport::ITransportMonitor -{ - XALLOCATOR -public: - enum class Status - { - SUCCESS, // Message received by remote - TIMEOUT // Message timeout - }; - - /// Signal emitted when a message status is determined. - /// Subscribers receive: (remoteId, seqNum, status) - dmq::Signal OnSendStatus; - - /// Signal emitted when the pending map hits MAX_TRANSPORT_MONITOR_PENDING. - /// Subscribers receive: (currentSize) — the number of unacknowledged messages at the time of rejection. - /// Fired outside the internal lock so subscribers may call back into TransportMonitor safely. - dmq::Signal OnCapExceeded; - - /// Signal emitted when Process() fills its batch buffer before emptying m_pending. - /// Subscribers receive: (remaining) — number of entries still in m_pending after the current pass. - /// Indicates that expired messages are accumulating faster than Process() is being called. - /// Fired outside the internal lock so subscribers may call back into TransportMonitor safely. - dmq::Signal OnPendingExceeded; - - /// @param timeout Per-message ACK timeout. Default is dmq::TRANSPORT_MONITOR_TIMEOUT - /// (DMQ_TRANSPORT_MONITOR_TIMEOUT_SEC in delegatemqconfig.h). - TransportMonitor(const dmq::Duration timeout = dmq::TRANSPORT_MONITOR_TIMEOUT) : TRANSPORT_TIMEOUT(timeout) {} - - ~TransportMonitor() - { - const dmq::LockGuard lock(m_lock); - m_pending.clear(); - } - - /// Add a sequence number - /// param[in] seqNum - the delegate message sequence number - /// param[in] remoteId - the remote ID - /// @return true if added; false otherwise. - virtual bool Add(uint16_t seqNum, dmq::DelegateRemoteId remoteId) override - { - size_t capSize = 0; - uint32_t key = (static_cast(remoteId) << 16) | seqNum; - { - const dmq::LockGuard lock(m_lock); - - if (m_pending.size() >= dmq::MAX_TRANSPORT_MONITOR_PENDING) { - capSize = m_pending.size(); - } else if (m_pending.find(key) != m_pending.end()) { - // Collision: 16-bit sequence wrapped before the old message timed out. - // Reject the send rather than silently clobbering the old message's tracking. - LOG_ERROR("TransportMonitor: SeqNum wraparound collision for seq {}", seqNum); - return false; - } else { - TimeoutData d; - d.timeStamp = dmq::Clock::now(); - d.remoteId = remoteId; - d.seqNum = seqNum; - m_pending[key] = d; - } - } - - if (capSize > 0) { - LOG_ERROR("TransportMonitor: Pending map full ({} entries). Check ACK logic or comm link.", capSize); - OnCapExceeded(capSize); - return false; - } - - return true; - } - - /// Remove a sequence number. Invokes SendStatusCb callback to notify - /// registered client of removal. - /// param[in] seqNum - the delegate message sequence number - /// param[in] remoteId - the remote ID (default 0 for backwards compatibility, but strongly recommended) - virtual void Remove(uint16_t seqNum, dmq::DelegateRemoteId remoteId = 0) - { - bool found = false; - TimeoutData d; - uint32_t key = (static_cast(remoteId) << 16) | seqNum; - - { - const dmq::LockGuard lock(m_lock); - - if (remoteId != 0) { - // Exact composite key lookup - auto it = m_pending.find(key); - if (it != m_pending.end()) { - d = it->second; - m_pending.erase(it); - found = true; - } - } else { - // Backwards compatibility: linear scan for seqNum if remoteId is unknown - for (auto it = m_pending.begin(); it != m_pending.end(); ++it) { - if (it->second.seqNum == seqNum) { - d = it->second; - m_pending.erase(it); - found = true; - break; - } - } - } - } - - if (found) - { - OnSendStatus(d.remoteId, seqNum, Status::SUCCESS); - } - } - - // Standard ITransportMonitor override (uses default remoteId 0) - virtual void Remove(uint16_t seqNum) override { Remove(seqNum, 0); } - - /// @brief Silently remove a sequence number without signaling SUCCESS. - /// @details Use this instead of Remove() when the entry must be freed because - /// the send itself is known to have failed (e.g. a synchronous ITransport::Send() - /// error right after Add() succeeded) -- Remove() fires OnSendStatus(..., SUCCESS), - /// which would misreport a failed send as an acknowledged one. Frees the pending - /// slot immediately instead of leaving it to expire via Process()/TRANSPORT_TIMEOUT. - /// @return true if an entry was found and removed. - bool Cancel(uint16_t seqNum, dmq::DelegateRemoteId remoteId) - { - const dmq::LockGuard lock(m_lock); - uint32_t key = (static_cast(remoteId) << 16) | seqNum; - auto it = m_pending.find(key); - if (it == m_pending.end()) - return false; - m_pending.erase(it); - return true; - } - - /// @brief The ACK timeout: how long a message waits for its ACK before - /// TIMEOUT is reported. - dmq::Duration GetTimeout() const { return TRANSPORT_TIMEOUT; } - - /// Call periodically to process message timeouts. - /// Drains all expired entries across multiple passes so a single call always - /// fully clears the backlog, regardless of how many entries have timed out. - void Process() - { - size_t expiredCount = 0; - - do { - expiredCount = 0; - size_t remaining = 0; - - // Local, not a member: it's read after the lock is released, when a - // concurrent Process() on another thread could overwrite a member. - std::array expiredItems; - - { - // Lock ONLY while reading/modifying the map - const dmq::LockGuard lock(m_lock); - - if (m_pending.empty()) - return; - - auto now = dmq::Clock::now(); - auto it = m_pending.begin(); - - while (it != m_pending.end()) - { - auto elapsed = std::chrono::duration_cast(now - (*it).second.timeStamp); - - if (elapsed > TRANSPORT_TIMEOUT) - { - if (expiredCount >= dmq::MAX_TIMER_EXPIRED) { - remaining = m_pending.size(); - break; - } - expiredItems[expiredCount++] = { (*it).second.remoteId, (*it).second.seqNum }; - it = m_pending.erase(it); - } - else - { - // map is sorted by key, not time — must scan all entries - ++it; - } - } - } // Lock is RELEASED here - - // Fire timeout callbacks without holding the lock - for (size_t i = 0; i < expiredCount; ++i) - { - OnSendStatus(expiredItems[i].remoteId, expiredItems[i].seq, Status::TIMEOUT); - } - - // Notify app if a full pass still left entries; loop to drain them - if (remaining > 0) { - LOG_ERROR("TransportMonitor: Cleanup bottleneck — {} entries remain after pass. Continuing drain.", remaining); - OnPendingExceeded(remaining); - } - - } while (expiredCount == dmq::MAX_TIMER_EXPIRED); - } - -private: - struct TimeoutData - { - dmq::DelegateRemoteId remoteId = 0; - uint16_t seqNum = 0; - dmq::TimePoint timeStamp; - }; - - struct ExpiredItem { dmq::DelegateRemoteId remoteId; uint16_t seq; }; - - // Key is (remoteId << 16) | seqNum - dmq::xmap m_pending; - const dmq::Duration TRANSPORT_TIMEOUT; - dmq::RecursiveMutex m_lock; -}; - -} // namespace dmq::util - - -#endif diff --git a/DelegateMQ/extras/util/crc16.h b/DelegateMQ/extras/util/crc16.h deleted file mode 100644 index 8ed3341..0000000 --- a/DelegateMQ/extras/util/crc16.h +++ /dev/null @@ -1,91 +0,0 @@ -#ifndef CRC16_H -#define CRC16_H - -/** - * @file crc16.h - * @brief Header-only 16-bit CRC-CCITT implementation (Polynomial 0x1021). - */ - -// Define USE_CRC_TABLE to use the faster table-based calculation. -// If commented out, the smaller loop-based calculation is used. -#define USE_CRC_TABLE - -namespace dmq::util { - -#ifdef USE_CRC_TABLE - -/** - * @brief CRC-CCITT lookup table based on x^16 + x^12 + x^5 + 1 (0x1021). - * - * `inline constexpr` (C++17) so every translation unit shares one definition. - * Plain `constexpr` at namespace scope has internal linkage, so each TU that - * used the table would get its own 512-byte copy. - */ -inline constexpr unsigned short crcccitt_table[] = { - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, - 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, - 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, - 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, - 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, - 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, - 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, - 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, - 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, - 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, - 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, - 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, - 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, - 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, - 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, - 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, - 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, - 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, - 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, - 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 -}; - -/** - * @brief Calculates a 16-bit CRC using the table-based method. - */ -inline unsigned short Crc16CalcBlock(const unsigned char* crc_msg, int len, unsigned short crc = 0xFFFF) -{ - while (len--) - crc = (crc << 8) ^ crcccitt_table[(crc >> 8) ^ *crc_msg++]; - return crc; -} - -#else - -/** - * @brief Calculates a 16-bit CRC using the loop-based method (saves memory). - */ -inline unsigned short Crc16CalcBlock(const unsigned char* crc_msg, int len, unsigned short crc = 0xFFFF) -{ - constexpr unsigned short POLY = 0x1021; - unsigned short data; - - while (len--) { - data = static_cast(*crc_msg++ << 8); - for (int i = 8; i > 0; i--) { - if ((data ^ crc) & 0x8000) - crc = static_cast((crc << 1) ^ POLY); - else - crc = static_cast(crc << 1); - data = static_cast(data << 1); - } - } - return crc; -} - -#endif // USE_CRC_TABLE - -} // namespace dmq::util - - -#endif // CRC16_H diff --git a/DelegateMQ/port/fault/Fault.cpp b/DelegateMQ/port/fault/Fault.cpp deleted file mode 100644 index eea88d9..0000000 --- a/DelegateMQ/port/fault/Fault.cpp +++ /dev/null @@ -1,291 +0,0 @@ -// Default FaultHandler()/WatchdogHandler(). An application that provides its -// own defines DMQ_CUSTOM_FAULT_HANDLER, and this file compiles to nothing, so -// it can stay in a build that adds every DelegateMQ source (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if !defined(DMQ_CUSTOM_FAULT_HANDLER) - -#include "extras/util/Fault.h" -#include -#include - -#if defined(_WIN32) || defined(__linux__) -#include -#include -#include "delegate/DelegateOpt.h" -#endif - -#ifdef _WIN32 -#include -#include -#include -#include -#pragma comment(lib, "dbghelp.lib") -#endif - -#ifdef __linux__ -#include -#include -#include -#endif - -namespace dmq::util { - -#ifdef __linux__ -static void LinuxSignalHandler(int sig) { - const char* name = "Unknown Signal"; - switch (sig) { - case SIGSEGV: name = "SIGSEGV (Segmentation Fault)"; break; - case SIGABRT: name = "SIGABRT (Abort)"; break; - case SIGFPE: name = "SIGFPE (Floating Point Exception)"; break; - case SIGILL: name = "SIGILL (Illegal Instruction)"; break; - case SIGBUS: name = "SIGBUS (Bus Error)"; break; - case SIGTERM: name = "SIGTERM (Termination Request)"; break; - } - FaultHandler(name, (unsigned short)sig); -} - -void InstallCrashHandlers() { - std::signal(SIGSEGV, LinuxSignalHandler); - std::signal(SIGABRT, LinuxSignalHandler); - std::signal(SIGFPE, LinuxSignalHandler); - std::signal(SIGILL, LinuxSignalHandler); - std::signal(SIGBUS, LinuxSignalHandler); - std::signal(SIGTERM, LinuxSignalHandler); -} -#endif - -#ifdef _WIN32 -LONG WINAPI WindowsExceptionFilter(EXCEPTION_POINTERS* pExceptionPointers) { - (void)pExceptionPointers; - FaultHandler("Windows Unhandled Exception", 0); -} - -void InstallCrashHandlers() { - SetUnhandledExceptionFilter(WindowsExceptionFilter); -} -#endif - -#if !defined(_WIN32) && !defined(__linux__) -void InstallCrashHandlers() { - // Stub for other platforms -} -#endif - -#ifdef _WIN32 -static void PrintStackTraceWindows(HANDLE hThread, const char* threadName) { - - DWORD tid = GetThreadId(hThread); - printf("\n--- Stack Trace: %s (TID: %lu) ---\n", (threadName ? threadName : "Unknown"), tid); - fflush(stdout); - - CONTEXT context = { 0 }; - context.ContextFlags = CONTEXT_FULL; - if (!GetThreadContext(hThread, &context)) { - printf(" Failed to get thread context (Error: %lu)\n", GetLastError()); - fflush(stdout); - return; - } - - STACKFRAME64 stackFrame = { 0 }; -#ifdef _M_IX86 - DWORD machineType = IMAGE_FILE_MACHINE_I386; - stackFrame.AddrPC.Offset = context.Eip; - stackFrame.AddrPC.Mode = AddrModeFlat; - stackFrame.AddrFrame.Offset = context.Ebp; - stackFrame.AddrFrame.Mode = AddrModeFlat; - stackFrame.AddrStack.Offset = context.Esp; - stackFrame.AddrStack.Mode = AddrModeFlat; -#elif _M_X64 - DWORD machineType = IMAGE_FILE_MACHINE_AMD64; - stackFrame.AddrPC.Offset = context.Rip; - stackFrame.AddrPC.Mode = AddrModeFlat; - stackFrame.AddrFrame.Offset = context.Rsp; - stackFrame.AddrFrame.Mode = AddrModeFlat; - stackFrame.AddrStack.Offset = context.Rsp; - stackFrame.AddrStack.Mode = AddrModeFlat; -#else - return; -#endif - - HANDLE hProcess = GetCurrentProcess(); - int frameCount = 0; - while (StackWalk64(machineType, hProcess, hThread, &stackFrame, &context, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL)) { - if (stackFrame.AddrPC.Offset == 0 || frameCount++ > 50) break; - - char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)]; - PSYMBOL_INFO pSymbol = reinterpret_cast(buffer); - pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); - pSymbol->MaxNameLen = MAX_SYM_NAME; - - DWORD64 displacement = 0; - if (SymFromAddr(hProcess, stackFrame.AddrPC.Offset, &displacement, pSymbol)) { - IMAGEHLP_LINE64 line = { 0 }; - line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); - DWORD lineDisplacement = 0; - if (SymGetLineFromAddr64(hProcess, stackFrame.AddrPC.Offset, &lineDisplacement, &line)) { - printf(" %s [%s:%lu]\n", pSymbol->Name, line.FileName, line.LineNumber); - } else { - printf(" %s (no line info)\n", pSymbol->Name); - } - } else { - printf(" 0x%llX (no symbol info)\n", stackFrame.AddrPC.Offset); - } - fflush(stdout); - } -} - -static void PrintAllThreadsStackTraces() { - printf("\nCapturing stack traces for all threads...\n"); - fflush(stdout); - - HANDLE hProcess = GetCurrentProcess(); - SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME); - - // Use FALSE for fInvadeProcess to avoid Error 87 in some environments. - // Symbols will be loaded on-demand. - if (!SymInitialize(hProcess, NULL, FALSE)) { - printf("SymInitialize failed (Error: %lu)\n", GetLastError()); - fflush(stdout); - return; - } - - // Refresh modules manually since we didn't invade - SymRefreshModuleList(hProcess); - - DWORD currentProcessId = GetCurrentProcessId(); - DWORD currentThreadId = GetCurrentThreadId(); - HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); - - if (hSnapshot != INVALID_HANDLE_VALUE) { - THREADENTRY32 te = { 0 }; - te.dwSize = sizeof(THREADENTRY32); - - if (Thread32First(hSnapshot, &te)) { - do { - if (te.th32OwnerProcessID == currentProcessId) { - if (te.th32ThreadID == currentThreadId) { - PrintStackTraceWindows(GetCurrentThread(), "Fault/Watchdog Thread"); - } else { - HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID); - if (hThread) { - SuspendThread(hThread); - PrintStackTraceWindows(hThread, "Suspended Thread"); - ResumeThread(hThread); - CloseHandle(hThread); - } - } - } - } while (Thread32Next(hSnapshot, &te)); - } - CloseHandle(hSnapshot); - } - SymCleanup(hProcess); - printf("\nStack trace capture complete.\n"); - fflush(stdout); -} -#endif - -#ifdef __linux__ -static void PrintStackTraceLinux() { - void* array[50]; - int size = backtrace(array, 50); - char** symbols = backtrace_symbols(array, size); - printf("\n--- Stack Trace (Current Thread) ---\n"); - for (int i = 0; i < size; i++) { - printf(" %s\n", symbols[i]); - } - fflush(stdout); - free(symbols); -} -#endif - -//---------------------------------------------------------------------------- -// FaultHandler -//---------------------------------------------------------------------------- -DMQ_NORETURN void FaultHandler(const char* file, unsigned short line) -{ - // 1. PRINT FIRST - printf("\n************************************************\n"); - printf("FaultHandler called. Application terminated.\n"); - printf("File: %s Line: %u\n", file, static_cast(line)); - printf("************************************************\n"); - fflush(stdout); - -#if defined(_WIN32) || defined(__linux__) - LOG_ERROR("FaultHandler File={} Line={}", file, line); -#endif - - // 2. PRINT STACK TRACES -#ifdef _WIN32 - PrintAllThreadsStackTraces(); -#elif defined(__linux__) - PrintStackTraceLinux(); -#endif - - // 3. Break only if interactive or specifically desired -#ifdef _WIN32 - if (IsDebuggerPresent()) { - DebugBreak(); - } -#endif - - // 4. Force exit -#if defined(__linux__) - printf("\nTerminating application...\n"); - fflush(stdout); - - // When running via terminal wrappers (like xterm -e), the console closes - // immediately on exit. Wait for input to allow the user to read the crash info. - // Note: isatty() can return false when stdin is redirected by the wrapper. - printf("Press Enter to exit (or wait 60s)..."); - fflush(stdout); - - // Set a timeout on stdin so we don't hang forever in CI/headless - struct timeval tv; - fd_set fds; - tv.tv_sec = 60; - tv.tv_usec = 0; - FD_ZERO(&fds); - FD_SET(STDIN_FILENO, &fds); - if (select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv) > 0) { - (void)getchar(); - } - - abort(); -#elif defined(_WIN32) - printf("\nTerminating application...\n"); - fflush(stdout); - abort(); -#else - printf("FaultHandler: %s line %u\r\n", file, static_cast(line)); - fflush(stdout); - while(1); -#endif -} - -} // namespace dmq::util - -extern "C" DMQ_NORETURN void FaultHandler(const char* file, unsigned short line) -{ - dmq::util::FaultHandler(file, line); -} - -extern "C" void InstallCrashHandlers() -{ - dmq::util::InstallCrashHandlers(); -} - -extern "C" DMQ_NORETURN void WatchdogHandler(const char* threadName) -{ -#if defined(_WIN32) || defined(__linux__) - std::cout << "\n************************************************" << std::endl; - std::cout << "WATCHDOG EXPIRED: " << threadName << std::endl; - std::cout << "************************************************\n" << std::endl; - DMQ_ASSERT(); -#else - printf("WATCHDOG EXPIRED: %s\r\n", threadName); - while (1); -#endif -} - -#endif // !DMQ_CUSTOM_FAULT_HANDLER diff --git a/DelegateMQ/port/os/README.md b/DelegateMQ/port/os/README.md deleted file mode 100644 index 0c863d1..0000000 --- a/DelegateMQ/port/os/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# OS Ports (DelegateMQ Abstraction Layer) - -This directory contains the OS part of the **DelegateMQ Abstraction Layer**: the concrete threading implementations required to execute asynchronous delegates, plus the portable mutex, semaphore, clock and critical-section types the whole library uses. The transport and serializer parts are in `port/transport` and `port/serialize`. - -By abstracting the threading model behind the `dmq::IThread` interface, DelegateMQ can run seamlessly on everything from high-performance servers (Windows/Linux) to resource-constrained embedded systems (FreeRTOS, ThreadX, Zephyr). - -## Implementations - -The subdirectories contain the platform-specific thread wrappers: - -* **`stdlib`**: Standard C++11 implementation. - * *Target:* Windows, Linux, macOS, or any OS with a compliant C++ Standard Library. - * *Implementation:* Uses `std::thread`, `std::mutex`, `std::condition_variable`, and `std::promise`. -* **`win32`**: Native Windows implementation. - * *Target:* Windows. - * *Implementation:* Uses Win32 thread and message-queue APIs directly rather than `std::thread`. -* **`posix`**: Raw POSIX implementation. - * *Target:* Linux (verified). Written against the POSIX API rather than any Linux-specific - syscall, but `pthread_condattr_setclock(CLOCK_MONOTONIC)` -- used here so timed waits are - immune to wall-clock jumps -- is a common POSIX extension present on Linux (glibc, musl) and - not guaranteed elsewhere (e.g. not implemented on Darwin/macOS), so treat portability beyond - Linux as untested rather than assumed. - * *Implementation:* Uses native POSIX primitives directly -- `pthread_create`, `pthread_mutex_t`, - `pthread_cond_t` (with `CLOCK_MONOTONIC` via `pthread_condattr_setclock`) -- rather than going - through `std::thread`. Mutex/ConditionVariable/Clock/ThisThread still reuse the same `std::` - types as `stdlib` (already thin wrappers over these same primitives under glibc/libstdc++); - only the `Thread` class itself is native, mirroring `win32`'s relationship to `stdlib` but for - POSIX. See `example/sample-projects/posix-linux/`. -* **`freertos`**: Real-Time OS implementation. - * *Target:* Embedded ARM Cortex-M (STM32, NXP, etc.), ESP32, and others running FreeRTOS. - * *Implementation:* Uses native FreeRTOS primitives: `xTaskCreate`, `xQueueSend/Receive`, and `vTaskDelay`. -* **`threadx`**: Azure RTOS (ThreadX) implementation. - * *Target:* Enterprise embedded devices running Eclipse ThreadX (formerly Azure RTOS). - * *Implementation:* Uses `tx_thread_create` and `tx_queue_send/receive`. -* **`zephyr`**: Zephyr RTOS implementation. - * *Target:* Modern IoT devices supported by the Zephyr Project. - * *Implementation:* Uses kernel primitives `k_thread_create` and `k_msgq_put/get`. -* **`cmsis-rtos2`**: CMSIS-RTOS API v2 implementation. - * *Target:* Any kernel compliant with the ARM CMSIS-RTOS2 standard (Keil RTX5, Micrium OS, etc.). - * *Implementation:* Uses standard APIs `osThreadNew` and `osMessageQueuePut/Get`. -* **`nuttx`**: Apache NuttX RTOS implementation. - * *Target:* Any board supported by NuttX (POSIX-compliant embedded RTOS), including its `sim` simulation target. - * *Implementation:* Uses NuttX's native POSIX APIs directly: `pthread_create`, `pthread_mutex_t`, `sem_t`, and a POSIX `mqueue` (with native `msg_prio`-based priority) for message passing. -* **`bare-metal`**: No-OS support (`DMQ_THREAD_NONE`). - * *Target:* Super-loop firmware on ARM Cortex-M or RISC-V. - * *Implementation:* Provides `Clock`, `ThisThread` and an ISR-safe `CriticalSection` so synchronous delegates, signals and `dmq::util::Timer` work; there is no `Thread`, so asynchronous delegates are unavailable. -* **`qt`**: Qt Framework implementation. - * *Target:* Desktop or embedded GUI applications using Qt. - * *Implementation:* Uses `QThread` and the native Signal & Slot mechanism (`moveToThread`) to safely dispatch delegates to the Qt Event Loop. - -## Configuration - -To select the appropriate threading model, set the `DMQ_THREAD` variable in your CMake configuration: - -```cmake -# Options: -# DMQ_THREAD_STDLIB (Default for PC/Linux) -# DMQ_THREAD_WIN32 (Native Win32 threads) -# DMQ_THREAD_POSIX (Raw POSIX pthreads -- Linux, verified) -# DMQ_THREAD_FREERTOS (FreeRTOS) -# DMQ_THREAD_THREADX (Azure RTOS ThreadX) -# DMQ_THREAD_ZEPHYR (Zephyr RTOS) -# DMQ_THREAD_CMSIS_RTOS2 (ARM CMSIS-RTOS2) -# DMQ_THREAD_NUTTX (Apache NuttX RTOS) -# DMQ_THREAD_QT (Qt Framework) -# DMQ_THREAD_NONE (For Bare-metal super-loops) - -set(DMQ_THREAD "DMQ_THREAD_STDLIB" CACHE STRING "" FORCE) -``` - -## Custom Porting - -If you need to run DelegateMQ on a different OS (e.g., VxWorks, QNX, or a proprietary kernel), you can simply implement the `dmq::IThread` interface and inject your custom thread wrapper into the library. diff --git a/DelegateMQ/port/os/bare-metal/BareMetalClock.h b/DelegateMQ/port/os/bare-metal/BareMetalClock.h deleted file mode 100644 index b1ac27b..0000000 --- a/DelegateMQ/port/os/bare-metal/BareMetalClock.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef BARE_METAL_CLOCK_H -#define BARE_METAL_CLOCK_H - -#include -#include - -// 1. Declare the external tick counter. -// This variable must be defined in your main.cpp or startup.c -// and incremented by your SysTick_Handler (or other timer ISR). -extern "C" volatile uint64_t g_ticks; - -namespace dmq::os { - - struct BareMetalClock { - // 2. Define duration traits - // We assume g_ticks represents Milliseconds (1/1000 sec). - // If your timer runs at a different rate (e.g. Microseconds), change std::milli to std::micro. - using rep = int64_t; - using period = std::milli; - using duration = std::chrono::duration; - using time_point = std::chrono::time_point; - - static const bool is_steady = true; - - // 3. The critical "now()" function - static time_point now() noexcept { - // On a 32-bit target, reading a 64-bit value requires two 32-bit - // loads. A timer ISR firing between them would produce a torn - // read, so interrupts are masked for the read. The previous - // interrupt state is saved and restored, not unconditionally - // re-enabled: Timer calls this while holding its - // BareMetalCriticalSection (Timer::Start(), and ProcessTimers() -> - // CheckExpired(), possibly from the timer ISR itself), and turning - // interrupts back on there would let the ISR run ProcessTimers() - // against a half-updated timer list. Same technique as - // BareMetalCriticalSection. -#if defined(__riscv) - unsigned long prev; - __asm__ volatile("csrrci %0, mstatus, 0x8" : "=r"(prev) :: "memory"); // clear MIE, save old - uint64_t t = g_ticks; - __asm__ volatile("csrs mstatus, %0" :: "r"(prev & 0x8ul) : "memory"); // restore MIE only if it was set -#elif defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) - uint32_t prev; - __asm__ volatile("mrs %0, primask" : "=r"(prev) :: "memory"); - __asm__ volatile("cpsid i" ::: "memory"); - uint64_t t = g_ticks; - __asm__ volatile("msr primask, %0" :: "r"(prev) : "memory"); -#elif defined(__CC_ARM) || defined(__ARMCC_VERSION) - uint32_t prev = __get_PRIMASK(); - __disable_irq(); - uint64_t t = g_ticks; - __set_PRIMASK(prev); -#else - // Fallback: plain read (safe on platforms with atomic 64-bit loads) - uint64_t t = g_ticks; -#endif - return time_point(duration(static_cast(t))); - } - }; -} // namespace dmq::os - -#endif // BARE_METAL_CLOCK_H \ No newline at end of file diff --git a/DelegateMQ/port/os/bare-metal/BareMetalCriticalSection.h b/DelegateMQ/port/os/bare-metal/BareMetalCriticalSection.h deleted file mode 100644 index 8e8f9b1..0000000 --- a/DelegateMQ/port/os/bare-metal/BareMetalCriticalSection.h +++ /dev/null @@ -1,97 +0,0 @@ -#ifndef BARE_METAL_CRITICAL_SECTION_H -#define BARE_METAL_CRITICAL_SECTION_H - -/// @file BareMetalCriticalSection.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ISR-safe critical section for bare metal (no RTOS). -/// -/// @details -/// Bare metal has no threads, so dmq::Mutex/RecursiveMutex are correctly a -/// no-op (NullMutex) there -- but that same no-op is NOT correct for a -/// critical section: real hardware ISRs still exist and can still preempt -/// the main loop even with no RTOS at all. dmq::util::Timer::ProcessTimers() -/// is commonly driven from a hardware ISR on this port (e.g. -/// SysTick_Handler), so its lock genuinely needs interrupt masking. -/// -/// Uses the same save-and-disable/restore technique, and the same per- -/// architecture branching, that BareMetalClock.h already uses for the -/// identical reason -- raw inline assembly (ARM: MRS/MSR PRIMASK: RISC-V: -/// CSRRCI/CSRS on mstatus.MIE) rather than a vendor intrinsics header, -/// since a minimal bare-metal build may not pull in the full CMSIS-Core -/// headers CmsisRtos2CriticalSection.h relies on for ARM, and there is no -/// RISC-V equivalent of CMSIS-Core at all. -/// -/// *** NARROW PURPOSE -- DO NOT USE THIS AS A GENERAL-PURPOSE LOCK *** -/// Holding this masks ALL maskable interrupts on the CPU for as long as it -/// is held. Only use it to protect something genuinely tiny and bounded -/// that may be touched from ISR context. -/// -/// *** NOT RE-LOCKABLE ON THE SAME INSTANCE *** -/// Calling lock() twice on the SAME instance without an intervening -/// unlock() is incorrect -- see ThreadXCriticalSection.h for the full -/// explanation; the same reasoning applies here. Locking two DIFFERENT -/// instances in proper LIFO lock/unlock order is fine. - -#include - -namespace dmq::os { - - // ========================================================================= - // BareMetalCriticalSection - // See the file-level comment above before using this type anywhere new. - // ========================================================================= - class BareMetalCriticalSection { - public: - BareMetalCriticalSection() = default; - - void lock() { -#if defined(__riscv) - // csrrci atomically reads mstatus into m_savedState AND clears - // the bits set in the immediate (0x8 = MIE, bit 3) in one - // instruction -- no separate disable step needed. - __asm__ volatile ("csrrci %0, mstatus, 0x8" : "=r" (m_savedState)); -#elif defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) - __asm__ volatile ("mrs %0, primask" : "=r" (m_savedState)); - __asm__ volatile ("cpsid i" ::: "memory"); -#elif defined(__CC_ARM) || defined(__ARMCC_VERSION) - m_savedState = __get_PRIMASK(); - __disable_irq(); -#else - // Fallback: no real interrupt masking available on this - // toolchain/target -- see BareMetalClock.h for the same - // fallback rationale. - m_savedState = 0; -#endif - } - - void unlock() { -#if defined(__riscv) - // Restore mstatus.MIE only if it was set before lock() -- - // csrs ORs its argument's set bits into mstatus, so masking - // m_savedState down to just the MIE bit before restoring - // means an already-clear MIE (interrupts were off before this - // lock() at all, e.g. nested inside another disabled region) - // stays clear rather than being unconditionally forced back on. - __asm__ volatile ("csrs mstatus, %0" :: "r" (m_savedState & 0x8u) : "memory"); -#elif defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) - __asm__ volatile ("msr primask, %0" :: "r" (m_savedState) : "memory"); -#elif defined(__CC_ARM) || defined(__ARMCC_VERSION) - __set_PRIMASK(m_savedState); -#endif - } - - // No try_lock(): interrupt masking cannot fail to "acquire", so a - // try_lock() here would always trivially succeed and isn't meaningful. - - BareMetalCriticalSection(const BareMetalCriticalSection&) = delete; - BareMetalCriticalSection& operator=(const BareMetalCriticalSection&) = delete; - - private: - uint32_t m_savedState = 0; - }; - -} // namespace dmq::os - -#endif // BARE_METAL_CRITICAL_SECTION_H diff --git a/DelegateMQ/port/os/bare-metal/BareMetalThisThread.h b/DelegateMQ/port/os/bare-metal/BareMetalThisThread.h deleted file mode 100644 index 19eb730..0000000 --- a/DelegateMQ/port/os/bare-metal/BareMetalThisThread.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef BARE_METAL_THIS_THREAD_H -#define BARE_METAL_THIS_THREAD_H - -/// @file BareMetalThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Portable sleep_for()/yield() for the calling thread, bare-metal backend. -/// -/// @details -/// This is dmq::ThisThread for this port (see DelegateOpt.h). GetCurrent() -/// has no per-thread storage here yet and returns nullptr. There is -/// no scheduler on DMQ_THREAD_NONE, so sleep_for() busy-waits against -/// BareMetalClock -- the same tick source Timer already keys off of -- rather -/// than pretending a real blocking delay exists. yield() is a no-op: with a -/// single thread of control (a superloop), there is nothing else to hand the -/// CPU to; hardware ISRs preempt regardless of this call. - -#include "BareMetalClock.h" -#include "port/os/common/CurrentThreadStorage.h" -#include - -namespace dmq::os { - - struct BareMetalThisThread : NoCurrentThread { - template - static void sleep_for(std::chrono::duration d) { - const auto ms = std::chrono::duration_cast(d); - auto start = BareMetalClock::now(); - while (BareMetalClock::now() - start < ms) { - // Busy-wait: no scheduler to yield to on bare metal. - } - } - - static void yield() noexcept { - // No-op: single thread of control on bare metal. - } - }; - -} // namespace dmq::os - -#endif // BARE_METAL_THIS_THREAD_H diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Clock.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Clock.h deleted file mode 100644 index b495611..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Clock.h +++ /dev/null @@ -1,70 +0,0 @@ -#ifndef CMSIS_RTOS2_CLOCK_H -#define CMSIS_RTOS2_CLOCK_H - -#include "cmsis_os2.h" -#include "CmsisRtos2CriticalSection.h" -#include "CmsisRtos2Ticks.h" -#include - -namespace dmq::os { - struct CmsisRtos2Clock { - // Milliseconds. now() converts the kernel tick count using the - // kernel's tick rate (osKernelGetTickFreq()), so any tick rate works. - using rep = int64_t; - using period = std::milli; - using duration = std::chrono::duration; - using time_point = std::chrono::time_point; - static const bool is_steady = true; - - static time_point now() noexcept { - // Static state to track the 32-bit rollover. - // osKernelGetTickCount() wraps after 2^32 ticks (~49.7 days at 1 kHz). - - // NOTE: This implementation relies on static state. - // It must be called at least once per wrap period to detect the wrap. - // - // Thread/ISR safety: dmq::util::Timer::ProcessTimers() (the only - // caller that needs 'last'/'high' updated atomically) is documented - // as callable from ISR context, and on CMSIS-RTOS2/Zephyr that's a - // real requirement, not a hypothetical -- a k_timer expiry_fn (which - // is what a CMSIS-RTOS2 osTimer callback compiles down to under - // Zephyr's compatibility layer) runs in genuine ISR context per - // Zephyr's own kernel.h. osKernelLock()/osKernelRestoreLock() are - // NOT ISR-safe -- Zephyr's implementation returns osErrorISR from - // osKernelLock() when called from an ISR, but osKernelRestoreLock() - // unconditionally writes that error code into the interrupted - // thread's own scheduler-lock-nesting count before it even checks - // for ISR context, corrupting scheduler state (verified: this is - // exactly what caused a one-shot dmq::util::Timer to refire forever - // instead of once, in example/sample-projects/cmsis-rtos2-linux). - // dmq::CriticalSection is the primitive this library already uses - // everywhere else for "must work from both thread and ISR context" - // (see CLAUDE.md's "ISR-Safe Locking" section) -- used here for the - // same reason. - static uint32_t last = 0; - static uint64_t high = 0; - - CmsisRtos2CriticalSection lock; - lock.lock(); - - uint32_t cur = osKernelGetTickCount(); - - // Check for wrap-around (current time is less than last seen time) - if (cur < last) { - // Add 2^32 to the high part accumulator - high += 0x100000000ULL; - } - - last = cur; - - // Combine the high part with the current low part. - uint64_t ticks = high + cur; - - lock.unlock(); - - return time_point(duration(static_cast(CmsisRtos2TicksToMs(ticks)))); - } - }; -} // namespace dmq::os - -#endif // CMSIS_RTOS2_CLOCK_H \ No newline at end of file diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2CriticalSection.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2CriticalSection.h deleted file mode 100644 index 71aedbd..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2CriticalSection.h +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef CMSIS_RTOS2_CRITICAL_SECTION_H -#define CMSIS_RTOS2_CRITICAL_SECTION_H - -/// @file CmsisRtos2CriticalSection.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ISR-safe critical section for CMSIS-RTOS2. -/// -/// @details -/// osMutexAcquire()/osMutexNew() are explicitly documented as not callable -/// from Interrupt Service Routines. Unlike Zephyr/ThreadX, CMSIS-RTOS2 has -/// no ISR-safe primitive of its own for this -- so this type bypasses -/// osMutex entirely and drops to the ARM Cortex-M CMSIS-Core intrinsics -/// directly (__get_PRIMASK()/__disable_irq()/__set_PRIMASK()), since -/// CMSIS-RTOS2 always sits on ARM Cortex-M. This is the same save/restore -/// technique BareMetalClock.h and ThreadXCriticalSection.h already use for -/// the identical reason: global interrupt masking is the only primitive -/// that is valid from both thread and ISR context on this architecture. -/// -/// @note UNVERIFIED: written against documented CMSIS-RTOS2/CMSIS-Core API -/// behavior. No CMSIS-RTOS2 SDK (e.g. Keil RTX5) or Cortex-M hardware/QEMU -/// target is available in this development environment to build and run it -/// (unlike ThreadXCriticalSection, exercised for real via the threadx-linux -/// sample). __get_PRIMASK()/__set_PRIMASK()/__disable_irq() are standard -/// CMSIS-Core intrinsics -- declared in cmsis_gcc.h (or the armclang/IAR -/// equivalent selected by cmsis_compiler.h), NOT in cmsis_os2.h itself, so -/// this file includes cmsis_compiler.h directly rather than assuming a -/// vendor device header already pulled it in transitively. -/// -/// *** NARROW PURPOSE -- DO NOT USE THIS AS A GENERAL-PURPOSE LOCK *** -/// Holding this masks ALL maskable interrupts on the CPU for as long as it -/// is held. Only use it to protect something genuinely tiny and bounded -/// that may be touched from ISR context. Do NOT use it in place of -/// dmq::Mutex / dmq::RecursiveMutex for ordinary thread-to-thread -/// synchronization (e.g. DataBus internals, a Thread's message queue) -- -/// anything that can block, take a while, or run for an unbounded time -/// must not run with interrupts globally masked; that is a real-time -/// correctness bug on hardware, not just a style issue. -/// -/// *** NOT RE-LOCKABLE ON THE SAME INSTANCE *** -/// Unlike dmq::RecursiveMutex, calling lock() twice on the SAME instance -/// without an intervening unlock() is incorrect: the second lock() call -/// overwrites the single saved PRIMASK member with the (already disabled) -/// inner state, so the outer unlock() restores the wrong state and -/// interrupts are left disabled permanently. There is no "recursive" -/// variant of this type -- it has no ownership concept to make recursion -/// meaningful, and Timer's own usage never nests. Locking two DIFFERENT -/// instances in proper LIFO lock/unlock order is fine: each instance saves -/// and restores its own PRIMASK independently. - -#include "cmsis_os2.h" -#include "cmsis_compiler.h" - -namespace dmq::os { - - // ========================================================================= - // CmsisRtos2CriticalSection - // See the file-level comment above before using this type anywhere new. - // ========================================================================= - class CmsisRtos2CriticalSection { - public: - CmsisRtos2CriticalSection() = default; - - void lock() { - m_savedPrimask = __get_PRIMASK(); - __disable_irq(); - } - - void unlock() { - __set_PRIMASK(m_savedPrimask); - } - - // No try_lock(): interrupt masking cannot fail to "acquire", so a - // try_lock() here would always trivially succeed and isn't meaningful. - - CmsisRtos2CriticalSection(const CmsisRtos2CriticalSection&) = delete; - CmsisRtos2CriticalSection& operator=(const CmsisRtos2CriticalSection&) = delete; - - private: - uint32_t m_savedPrimask = 0; - }; - -} // namespace dmq::os - -#endif // CMSIS_RTOS2_CRITICAL_SECTION_H diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2DelegateQueue.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2DelegateQueue.h deleted file mode 100644 index 6f3d093..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2DelegateQueue.h +++ /dev/null @@ -1,168 +0,0 @@ -#ifndef CMSIS_RTOS2_DELEGATE_QUEUE_H -#define CMSIS_RTOS2_DELEGATE_QUEUE_H - -/// @file CmsisRtos2DelegateQueue.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Thin RAII wrapper around a pair of CMSIS-RTOS2 osMessageQueue -/// primitives used by dmq::os::Thread to carry pending ThreadMsg pointers, -/// with priority support. See the Priority enum in delegate/DelegateMsg.h for -/// the cross-port ordering contract this class must uphold. -/// -/// @details -/// *** DO NOT "SIMPLIFY" THIS BACK TO ONE QUEUE + msg_prio *** -/// osMessageQueuePut() takes a msg_prio argument, and an earlier version of -/// this class relied on it for HIGH priority with a single queue. CMSIS-RTOS2 -/// leaves msg_prio's effect to the implementation, and common ones ignore it: -/// Zephyr's CMSIS-RTOS2 layer (the backend this port is verified on) does -/// ARG_UNUSED(msg_prio) and always appends with k_msgq_put(), so HIGH messages -/// were delivered behind every NORMAL one already queued, breaking the Priority -/// contract every other port meets. -/// -/// The fix is the same design as FreeRTOSDelegateQueue and ThreadXDelegateQueue: -/// two independent osMessageQueue instances, one per priority lane, both always -/// appended to, and a counting osSemaphore as a shared "doorbell". Every -/// successful Send() (to either lane) releases the semaphore once; Receive() -/// acquires it (the single blocking wait) and then does a non-blocking get, -/// checking the HIGH lane first so it drains ahead of NORMAL while each lane -/// stays FIFO. -/// -/// Each lane is sized to the full requested 'capacity', so worst-case combined -/// depth is 2x capacity; the semaphore's max count is sized to match (2x -/// capacity) so a Send() that already found room in its lane can never fail to -/// release it. -/// -/// Send() is callable from an ISR with a zero timeout (osMessageQueuePut and -/// osSemaphoreRelease are ISR-safe in CMSIS-RTOS2); Receive() is only called by -/// the owning thread. This class owns no policy decisions of its own -/// (FullPolicy, timeout computation, and stats stay in Thread.cpp) -- it only -/// knows how to move ThreadMsg* pointers through two fixed-capacity CMSIS-RTOS2 -/// queues in priority order. - -#include "cmsis_os2.h" -#include "port/os/common/ThreadMsg.h" - -namespace dmq::os { - -class CmsisRtos2DelegateQueue -{ -public: - CmsisRtos2DelegateQueue() = default; - ~CmsisRtos2DelegateQueue() { Destroy(); } - - CmsisRtos2DelegateQueue(const CmsisRtos2DelegateQueue&) = delete; - CmsisRtos2DelegateQueue& operator=(const CmsisRtos2DelegateQueue&) = delete; - - /// Create both lanes (each with room for 'capacity' pointers) and the - /// doorbell semaphore. On a partial failure everything created so far is - /// destroyed, so a later Create() starts clean. - /// @return true on success, false if any CMSIS-RTOS2 object couldn't be created. - bool Create(size_t capacity) - { - if (IsCreated()) - return true; - - const uint32_t cap = static_cast(capacity); - if (!m_highQueue) - m_highQueue = osMessageQueueNew(cap, sizeof(ThreadMsg*), NULL); - if (!m_normalQueue) - m_normalQueue = osMessageQueueNew(cap, sizeof(ThreadMsg*), NULL); - if (!m_countSem) - m_countSem = osSemaphoreNew(cap * 2, 0, NULL); - - if (!IsCreated()) { - Destroy(); - return false; - } - return true; - } - - bool IsCreated() const { return m_highQueue != NULL && m_normalQueue != NULL && m_countSem != NULL; } - - /// Send a message pointer. 'highPriority' routes to the HIGH lane, which - /// Receive() always drains first; otherwise the NORMAL lane. Both lanes are - /// always appended to. 'waitOption' is 0 for non-blocking, osWaitForever to - /// block forever, or a finite timeout in kernel ticks (see CmsisRtos2ToTicks()); - /// it applies only to waiting for room in the lane. - /// @return true if the message was enqueued. - bool Send(ThreadMsg* msg, bool highPriority, uint32_t waitOption) - { - osMessageQueueId_t q = highPriority ? m_highQueue : m_normalQueue; - if (osMessageQueuePut(q, &msg, 0, waitOption) != osOK) - return false; - osSemaphoreRelease(m_countSem); - return true; - } - - /// Receive a message pointer, HIGH lane first, blocking up to 'waitOption' - /// for either lane to have one. - /// @return the message, or nullptr on timeout. - ThreadMsg* Receive(uint32_t waitOption) - { - if (osSemaphoreAcquire(m_countSem, waitOption) != osOK) - return nullptr; // timed out waiting for either lane - - ThreadMsg* msg = nullptr; - if (osMessageQueueGet(m_highQueue, &msg, NULL, 0) == osOK) - return msg; - if (osMessageQueueGet(m_normalQueue, &msg, NULL, 0) == osOK) - return msg; - return nullptr; - } - - /// Current number of messages waiting in both lanes. - size_t Size() const - { - if (!m_highQueue || !m_normalQueue) - return 0; - return static_cast(osMessageQueueGetCount(m_highQueue)) - + static_cast(osMessageQueueGetCount(m_normalQueue)); - } - - /// Remove and delete every pending message without blocking. Used during - /// shutdown once the owning thread has stopped consuming the queue. - /// Each message is canceled first (CancelThreadMsg()), releasing a sender - /// blocked waiting on it. - void DrainAndDelete() - { - ThreadMsg* msg = nullptr; - if (m_highQueue) { - while (osMessageQueueGet(m_highQueue, &msg, NULL, 0) == osOK) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - } - if (m_normalQueue) { - while (osMessageQueueGet(m_normalQueue, &msg, NULL, 0) == osOK) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - } - } - - void Destroy() - { - if (m_highQueue) { - osMessageQueueDelete(m_highQueue); - m_highQueue = NULL; - } - if (m_normalQueue) { - osMessageQueueDelete(m_normalQueue); - m_normalQueue = NULL; - } - if (m_countSem) { - osSemaphoreDelete(m_countSem); - m_countSem = NULL; - } - } - -private: - osMessageQueueId_t m_highQueue = NULL; - osMessageQueueId_t m_normalQueue = NULL; - osSemaphoreId_t m_countSem = NULL; -}; - -} // namespace dmq::os - -#endif // CMSIS_RTOS2_DELEGATE_QUEUE_H diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Mutex.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Mutex.h deleted file mode 100644 index f8a1abf..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Mutex.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef CMSIS_RTOS2_MUTEX_H -#define CMSIS_RTOS2_MUTEX_H - -#include "cmsis_os2.h" -#include - -namespace dmq::os { - - // ========================================================================= - // CmsisRtos2Mutex (Non-Recursive) - // ========================================================================= - class CmsisRtos2Mutex { - public: - CmsisRtos2Mutex() { - // Explicitly define attributes as 0 (Non-Recursive) - osMutexAttr_t attr = {0}; - attr.attr_bits = 0; - m_id = osMutexNew(&attr); - assert(m_id != NULL); - } - - ~CmsisRtos2Mutex() { - if (m_id) osMutexDelete(m_id); - } - - void lock() { - if (m_id) osMutexAcquire(m_id, osWaitForever); - } - - // REQUIRED for std::unique_lock compatibility - bool try_lock() { - if (m_id) { - return osMutexAcquire(m_id, 0) == osOK; - } - return false; - } - - void unlock() { - if (m_id) osMutexRelease(m_id); - } - - CmsisRtos2Mutex(const CmsisRtos2Mutex&) = delete; - CmsisRtos2Mutex& operator=(const CmsisRtos2Mutex&) = delete; - - private: - osMutexId_t m_id = NULL; - }; - - // ========================================================================= - // CmsisRtos2RecursiveMutex (Recursive) - // ========================================================================= - class CmsisRtos2RecursiveMutex { - public: - CmsisRtos2RecursiveMutex() { - osMutexAttr_t attr = {0}; - attr.attr_bits = osMutexRecursive; - m_id = osMutexNew(&attr); - assert(m_id != NULL); - } - - ~CmsisRtos2RecursiveMutex() { - if (m_id) osMutexDelete(m_id); - } - - void lock() { - if (m_id) osMutexAcquire(m_id, osWaitForever); - } - - bool try_lock() { - if (m_id) { - return osMutexAcquire(m_id, 0) == osOK; - } - return false; - } - - void unlock() { - if (m_id) osMutexRelease(m_id); - } - - CmsisRtos2RecursiveMutex(const CmsisRtos2RecursiveMutex&) = delete; - CmsisRtos2RecursiveMutex& operator=(const CmsisRtos2RecursiveMutex&) = delete; - - private: - osMutexId_t m_id = NULL; - }; -} // namespace dmq::os - -#endif // CMSIS_RTOS2_MUTEX_H \ No newline at end of file diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Semaphore.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Semaphore.h deleted file mode 100644 index 689424c..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Semaphore.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef CMSIS_RTOS2_SEMAPHORE_H -#define CMSIS_RTOS2_SEMAPHORE_H - -/// @file CmsisRtos2Semaphore.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief dmq::Semaphore backing for CMSIS-RTOS2, using osSemaphore -/// directly instead of the generic dmq::ConditionVariable + dmq::Mutex -/// implementation in delegate/Semaphore.h. -/// -/// @details -/// CMSIS-RTOS2 has no dmq::ConditionVariable port (no DMQ_HAS_CV) -- and no -/// native condition-variable primitive to build one from, unlike Zephyr's -/// k_condvar. It does have a native binary semaphore (osSemaphore), which -/// is a direct fit for what dmq::Semaphore actually needs: no need to build -/// one out of a mutex + condition variable when the RTOS already has a real -/// one. DelegateOpt.h resolves dmq::Semaphore to this type on CMSIS-RTOS2; -/// see the "Semaphore" comment next to DMQ_THREAD_CMSIS_RTOS2's -/// `using Semaphore = ...;` there. -/// -/// @note This header is included from DelegateOpt.h's early port-include -/// block, before "namespace dmq { ... }" opens and dmq::Duration is defined -/// inside it (including it any later would nest as dmq::dmq::os instead of -/// dmq::os) -- so, like the other CMSIS-RTOS2 port files, Wait() is -/// templated on the chrono duration type instead of depending on -/// dmq::Duration directly. A dmq::Duration argument still deduces through -/// it seamlessly at the call site, since dmq::Duration is itself a -/// std::chrono::duration specialization. -/// -/// @note osSemaphoreAcquire()'s timeout is in kernel ticks; Wait() converts -/// with CmsisRtos2ToTicks() (CmsisRtos2Ticks.h), so any tick rate works. - -#include "cmsis_os2.h" -#include "CmsisRtos2Ticks.h" -#include -#include - -namespace dmq::os { - - // ========================================================================= - // CmsisRtos2Semaphore - // Binary semaphore (max count 1), matching the semantics of the generic - // dmq::Semaphore this replaces: Signal() when already signaled is a - // no-op (not a counting semaphore), and Wait() consumes exactly one - // pending signal. - // ========================================================================= - class CmsisRtos2Semaphore { - public: - CmsisRtos2Semaphore() { - m_id = osSemaphoreNew(1, 0, nullptr); - assert(m_id != nullptr); - } - - ~CmsisRtos2Semaphore() { - if (m_id) osSemaphoreDelete(m_id); - } - - /// Called to wait on a semaphore to be signaled. - /// @param[in] timeout - semaphore timeout - /// @return Return true if semaphore signaled, false if timeout occurred. - template - bool Wait(const std::chrono::duration& timeout) { - if (!m_id) return false; - return osSemaphoreAcquire(m_id, CmsisRtos2ToTicks(timeout)) == osOK; - } - - /// Called to signal a semaphore. - void Signal() { - if (m_id) osSemaphoreRelease(m_id); - } - - CmsisRtos2Semaphore(const CmsisRtos2Semaphore&) = delete; - CmsisRtos2Semaphore& operator=(const CmsisRtos2Semaphore&) = delete; - - private: - osSemaphoreId_t m_id = nullptr; - }; - -} // namespace dmq::os - -#endif // CMSIS_RTOS2_SEMAPHORE_H diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2ThisThread.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2ThisThread.h deleted file mode 100644 index 398acb7..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2ThisThread.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef CMSIS_RTOS2_THIS_THREAD_H -#define CMSIS_RTOS2_THIS_THREAD_H - -/// @file CmsisRtos2ThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Portable sleep_for()/yield() for the calling thread, CMSIS-RTOS2 backend. -/// -/// @details -/// This is dmq::ThisThread for this port (see DelegateOpt.h). GetCurrent() -/// uses RegistryCurrentThread, keyed by the calling thread's id. Exists so -/// library internals that need to delay or yield (e.g. RetryMonitor backoff) -/// aren't forced to pull in the full dmq::os::Thread class -- which also -/// drags in the message queue, watchdog, and stats machinery -- just to -/// sleep. dmq::os::Thread::Sleep() forwards here too, so the CMSIS-RTOS2 -/// delay call is implemented exactly once. - -#include "cmsis_os2.h" -#include "CmsisRtos2Mutex.h" -#include "CmsisRtos2Ticks.h" -#include "port/os/common/CurrentThreadStorage.h" -#include - -namespace dmq::os { - - /// @brief Key for RegistryCurrentThread: the calling thread's id. - /// @TODO: Return 0 inside an ISR if your target can detect it (e.g. - /// __get_IPSR() != 0 on ARM Cortex-M). CMSIS-RTOS2 has no portable ISR check, - /// so dmq::ThisThread::GetCurrent() from an ISR returns the interrupted - /// thread's IThread instead of nullptr. See docs/PORTING.md, "Current Thread". - inline uintptr_t CmsisRtos2CurrentThreadKey() { - return reinterpret_cast(osThreadGetId()); - } - - struct CmsisRtos2ThisThread : RegistryCurrentThread { - template - static void sleep_for(std::chrono::duration d) { - osDelay(CmsisRtos2ToTicks(d)); // kernel ticks, rounded up - } - - static void yield() noexcept { - osThreadYield(); - } - }; - -} // namespace dmq::os - -#endif // CMSIS_RTOS2_THIS_THREAD_H diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.cpp b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.cpp deleted file mode 100644 index 89f7167..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.cpp +++ /dev/null @@ -1,671 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_CMSIS_RTOS2 is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_CMSIS_RTOS2) - -#include "DelegateMQ.h" -#include "CmsisRtos2Thread.h" -#include "CmsisRtos2Ticks.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include -#include - -// Define DMQ_ASSERT_TRUE if not already defined -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(x) if(!(x)) { while(1); } -#endif - -namespace dmq::os { - -using namespace dmq; -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// Thread Constructor -//---------------------------------------------------------------------------- -CmsisRtos2Thread::CmsisRtos2Thread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , m_queueSize((maxQueueSize == 0) ? DEFAULT_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - // Default Priority - m_priority = osPriorityNormal; - -#if defined(DMQ_DATABUS_TOOLS) - m_statMutex = osMutexNew(NULL); -#endif -} - -//---------------------------------------------------------------------------- -// Thread Destructor -//---------------------------------------------------------------------------- -CmsisRtos2Thread::~CmsisRtos2Thread() -{ - ExitThread(); - - const dmq::LockGuard lock(GetWatchdogLock()); - CmsisRtos2Thread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } - -#if defined(DMQ_DATABUS_TOOLS) - if (m_statMutex) { - osMutexDelete(m_statMutex); - m_statMutex = NULL; - } -#endif - - // Cleanup semaphore if it exists - if (m_exitSem) { - osSemaphoreDelete(m_exitSem); - m_exitSem = NULL; - } - - if (m_startSem) { - osSemaphoreDelete(m_startSem); - m_startSem = NULL; - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool CmsisRtos2Thread::CreateThread(std::optional watchdogTimeout) -{ - if (m_thread == NULL) - { - // Reset from a previous ExitThread(), so the thread can be created again - m_exit.store(false); - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - m_discard.store(false); - - // 1. Create Exit Semaphore (Max 1, Initial 0) - // We use this to wait for the thread to shut down gracefully. Created - // once and reused across ExitThread()/CreateThread() cycles (ExitThread() - // doesn't delete it; the destructor does), so a restart doesn't leak one. - if (m_exitSem == NULL) { - m_exitSem = osSemaphoreNew(1, 0, NULL); - DMQ_ASSERT_TRUE(m_exitSem != NULL); - } - - // 2. Create Message Queue - DMQ_ASSERT_TRUE(m_queue.Create(m_queueSize)); - - // 3. Create Thread - osThreadAttr_t attr = {0}; - attr.name = THREAD_NAME.c_str(); - attr.stack_size = STACK_SIZE; - attr.priority = m_priority; - - // If the kernel is running, CreateThread() waits for the start handler. - // Before osKernelStart() it cannot block; the start handler then runs - // when the kernel starts, still before any message is processed. - // - // Zephyr's CMSIS-RTOS2 compatibility layer (subsys/portability/cmsis_rtos_v2/) - // never implements osKernelGetState() -- calling it is a link error -- but on - // Zephyr the kernel is already scheduling before main() runs (there is no - // separate osKernelStart() call on this backend; see cmsis-rtos2-linux's - // main_delegate.cpp), so it would always report osKernelRunning anyway. - // __ZEPHYR__ is defined by Zephyr's own build system on every compile. -#if defined(__ZEPHYR__) - m_startSync = true; -#else - m_startSync = (osKernelGetState() == osKernelRunning); -#endif - if (m_startSync && m_startSem == NULL) { - m_startSem = osSemaphoreNew(1, 0, NULL); - DMQ_ASSERT_TRUE(m_startSem != NULL); - } - - m_thread = osThreadNew(CmsisRtos2Thread::Process, this, &attr); - DMQ_ASSERT_TRUE(m_thread != NULL); - - if (m_startSync) { - // m_thread is now stored: let Run() proceed to the start handler (see - // Run()), then wait for it to complete. - osThreadFlagsSet(m_thread, START_FLAG); - osSemaphoreAcquire(m_startSem, osWaitForever); - } - - m_lastAliveTime.store(Timer::GetNow()); - - if (watchdogTimeout.has_value()) - { - - const dmq::LockGuard lock(GetWatchdogLock()); - - // Add to watchdog registry if not already present - bool found = false; - CmsisRtos2Thread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// SetThreadPriority -//---------------------------------------------------------------------------- -void CmsisRtos2Thread::SetThreadPriority(osPriority_t priority) -{ - m_priority = priority; - - // If the thread is already running, update it live - if (m_thread != NULL) { - osThreadSetPriority(m_thread, m_priority); - } -} - -//---------------------------------------------------------------------------- -// GetThreadPriority -//---------------------------------------------------------------------------- -osPriority_t CmsisRtos2Thread::GetThreadPriority() -{ - return m_priority; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void CmsisRtos2Thread::ExitThread(ExitPolicy policy) -{ - if (m_queue.IsCreated()) - { - // Set before m_exit: Run() reads it for every message ahead of the exit message - m_discard.store(policy == ExitPolicy::DISCARD); - m_exit.store(true); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Check self-exit BEFORE attempting to enqueue the exit message. If - // this thread is destroying itself from within its own dispatched - // callback, it is not consuming its own queue right now -- it is - // blocked here, inside ExitThread(). A blocking osMessageQueuePut() - // would deadlock forever if the queue happened to be full. No message - // needs to be queued in that case: Run()'s dispatch loop already - // checks m_selfExitPtr immediately after the current callback invoke - // returns, and unwinds without touching 'this' again. - if (osThreadGetId() == m_thread) { - if (m_selfExitPtr) { *m_selfExitPtr = true; m_selfExitPtr = nullptr; } - m_startGate.Leave(); // exited from its start handler: never reaches the gate - } else { - // Send exit message - ThreadMsg* msg = new (std::nothrow) ThreadMsg(MSG_EXIT_THREAD); - if (msg) - { - // Send pointer, wait forever to ensure it gets in. - if (!m_queue.Send(msg, /*highPriority=*/false, osWaitForever)) - { - delete msg; // Failed to send - } - } - - // Wait for thread to process the exit message and signal completion. - if (m_exitSem != NULL) osSemaphoreAcquire(m_exitSem, osWaitForever); - } - - // Thread has finished Run(). Now we can safely clean up resources. - m_thread = NULL; - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - m_queue.DrainAndDelete(); - m_queue.Destroy(); - } -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -osThreadId_t CmsisRtos2Thread::GetThreadId() -{ - return m_thread; -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -osThreadId_t CmsisRtos2Thread::GetCurrentThreadId() -{ - return osThreadGetId(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool CmsisRtos2Thread::IsCurrentThread() -{ - return GetThreadId() == GetCurrentThreadId(); -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t CmsisRtos2Thread::GetQueueSize() -{ - return m_queue.Size(); -} - -void CmsisRtos2Thread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool CmsisRtos2Thread::DispatchDelegate(std::shared_ptr msg) -{ - DMQ_ASSERT_TRUE(m_queue.IsCreated()); - - // 1. Allocate message container - ThreadMsg* threadMsg = new (std::nothrow) ThreadMsg(MSG_DISPATCH_DELEGATE, msg); - if (!threadMsg) return false; -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // 2. Send pointer to queue - uint32_t timeout; - if (FULL_POLICY == FullPolicy::TIMEOUT) - timeout = CmsisRtos2ToTicks(m_dispatchTimeout); - else - timeout = 0; // DROP and FAULT: non-blocking - - // High priority goes to the queue's HIGH lane, drained first (see CmsisRtos2DelegateQueue). - bool sent = m_queue.Send(threadMsg, msg->GetPriority() == Priority::HIGH, timeout); - if (!sent) - { - if (FULL_POLICY == FullPolicy::FAULT) { - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(sent); - } else if (FULL_POLICY == FullPolicy::TIMEOUT) { - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } else { // DROP - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } - // Failed to send (queue full or timed out) - delete threadMsg; - return false; - } - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - osMutexAcquire(m_statMutex, osWaitForever); - size_t currentDepth = GetQueueSize(); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - osMutexRelease(m_statMutex); -#endif - - return true; -} - -//---------------------------------------------------------------------------- -// Process (Static Entry Point) -//---------------------------------------------------------------------------- -void CmsisRtos2Thread::Process(void* argument) -{ - CmsisRtos2Thread* thread = static_cast(argument); - if (thread) - { - thread->Run(); - } - - // Thread terminates automatically when function returns. - osThreadExit(); -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void CmsisRtos2Thread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void CmsisRtos2Thread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void CmsisRtos2Thread::WatchdogCheckAll() -{ - const dmq::LockGuard lock(GetWatchdogLock()); - CmsisRtos2Thread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -CmsisRtos2Thread*& CmsisRtos2Thread::GetWatchdogHead() -{ - static CmsisRtos2Thread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& CmsisRtos2Thread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -void CmsisRtos2Thread::Run() -{ - bool selfExit = false; - m_selfExitPtr = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // osThreadNew() returns m_thread only after this thread may already be - // running; wait for CreateThread() so the start handler can use it. - const bool startSync = m_startSync; - if (startSync) - osThreadFlagsWait(START_FLAG, osFlagsWaitAny, osWaitForever); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Reset - // before the exit handler runs (and destroyed before exitGuard on a - // self-exit), so the exit handler sees nullptr. - std::optional currentScope; - currentScope.emplace(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - if (startSync) - osSemaphoreRelease(m_startSem); - if (exitedInStart) - return; - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - // ExitThread() while held: run nothing. Cancel each queued message - // (DISCARD) until the exit message. Consuming them also keeps - // ExitThread()'s blocking send of the exit message from waiting on a - // full queue. - if (!opened) - m_discard.store(true); - } - - ThreadMsg* msg = nullptr; - - while (!selfExit) - { - dmq::Duration watchdogTimeout; - { - m_lastAliveTime.store(Timer::GetNow()); - watchdogTimeout = m_watchdogTimeout.load(); - } - - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever to save power. - uint32_t waitOption = osWaitForever; - if (watchdogTimeout.count() > 0) - { - // Divide in microseconds so a 1-3 ms watchdog doesn't truncate to 0; - // CmsisRtos2ToTicks() rounds any nonzero wait up to at least 1 tick. - waitOption = CmsisRtos2ToTicks( - std::chrono::duration_cast(watchdogTimeout) / dmq::WATCHDOG_HEARTBEAT_DIVISOR); - } - if (idle.Enabled()) - { - uint32_t idleTicks = CmsisRtos2ToTicks(idle.WaitTime(dmq::Duration(-1))); - if (idleTicks < waitOption) waitOption = idleTicks; - } - - // Block for a message or timeout - msg = m_queue.Receive(waitOption); - if (msg == nullptr) - { - // Exit requested but no exit message arrived (e.g. it could not be allocated) - if (m_exit.load()) - break; - - // Timed out with the queue empty: run the idle handler if it is due - if (idle.IsDue()) - { - idle.Run(); - // The idle handler exited this thread (and may have deleted it): leave - // without touching 'this', as the message path does - if (selfExit) - return; - } - } - else - { - int msgId = msg->GetId(); - if (msgId == MSG_DISPATCH_DELEGATE && m_discard.load()) - { - // ExitPolicy::DISCARD: skip messages queued ahead of the exit message - CancelThreadMsg(*msg); - } - else if (msgId == MSG_DISPATCH_DELEGATE) - { - #if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - osMutexAcquire(m_statMutex, osWaitForever); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - osMutexRelease(m_statMutex); - } - #endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - bool success = false; - try { - success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - printf("[Thread:%s] Unhandled exception in delegate callback: %s\n", THREAD_NAME.c_str(), e.what()); - DMQ_ASSERT(); - } - catch (...) { - printf("[Thread:%s] Unhandled unknown exception in delegate callback.\n", THREAD_NAME.c_str()); - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - delete msg; - return; - } - -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - { - osMutexAcquire(m_statMutex, osWaitForever); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - osMutexRelease(m_statMutex); - } -#endif - } - - delete msg; - - if (msgId == MSG_EXIT_THREAD) { - break; - } - - // Any message restarts the idle countdown - idle.Restart(); - } - } - - // Run the exit handler before signalling ExitThread(), so it returns only after it - currentScope.reset(); - exitGuard.Fire(); - - // Clear before signalling: once ExitThread() returns, 'this' may be destroyed - m_selfExitPtr = nullptr; - // Signal ExitThread() that we are done - if (m_exitSem) { - osSemaphoreRelease(m_exitSem); - } -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -CmsisRtos2Thread::ThreadStats CmsisRtos2Thread::SnapshotStats() -{ - osMutexAcquire(m_statMutex, osWaitForever); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = GetQueueSize(); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = m_queueSize; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = static_cast(std::chrono::duration_cast(m_latencyTotalWindow).count()) / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = static_cast(std::chrono::duration_cast(m_latencyMaxWindow).count()) / 1000.0f; - stats.latency_max_all_ms = static_cast(std::chrono::duration_cast(m_latencyMaxAll).count()) / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = static_cast(std::chrono::duration_cast(m_invokeTotalWindow).count()) / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = static_cast(std::chrono::duration_cast(m_invokeMaxWindow).count()) / 1000.0f; - stats.invoke_max_all_ms = static_cast(std::chrono::duration_cast(m_invokeMaxAll).count()) / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = Duration(0); - - m_invokeTotalWindow = Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = Duration(0); - - osMutexRelease(m_statMutex); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_CMSIS_RTOS2 diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.h deleted file mode 100644 index 8f98b3f..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Thread.h +++ /dev/null @@ -1,296 +0,0 @@ -#ifndef _THREAD_CMSIS_RTOS2_H -#define _THREAD_CMSIS_RTOS2_H - -/// @file CmsisRtos2Thread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief CMSIS-RTOS2 implementation of the DelegateMQ IThread interface. -/// -/// @details -/// This class provides a concrete implementation of the `IThread` interface using -/// the CMSIS-RTOS2 standard API (`cmsis_os2.h`). It enables DelegateMQ to dispatch -/// asynchronous delegates to a dedicated thread on any CMSIS-compliant RTOS -/// (e.g., Keil RTX, FreeRTOS wrapped by CMSIS, Zephyr, etc.). -/// -/// @note This implementation is a basic port. For reference, the stdlib and win32 -/// implementations provide additional features: -/// 1. Synchronized Startup: CreateThread() blocks until the worker thread is ready. -/// -/// **Key Features:** -/// * **Task Integration:** Wraps `osThreadNew` to establish a dedicated worker loop. -/// * **FullPolicy Support:** Configurable back-pressure (DROP or TIMEOUT) when the -/// message queue is full. -/// * **Priority Support:** Normal and High priorities, as two queue lanes drained -/// HIGH first (see `CmsisRtos2DelegateQueue` for why `osMessageQueuePut`'s -/// `msg_prio` isn't relied on). -/// * **Queue-Based Dispatch:** Uses `CmsisRtos2DelegateQueue` (a thin RAII wrapper -/// around two `osMessageQueue` lanes and a counting `osSemaphore`) to receive -/// and process incoming delegate messages in a thread-safe manner. -/// * **Priority Control:** Supports runtime priority configuration via `SetThreadPriority` -/// using standard `osPriority_t` levels. -/// * **Graceful Shutdown:** Implements robust termination logic using semaphores to ensure -/// the thread exits cleanly before destruction. -/// * **Watchdog Integration:** Optional heartbeat mechanism detects stalled or deadlocked -/// threads. Enable by passing a timeout to CreateThread(). Requires -/// Thread::WatchdogCheckAll() to be called periodically from a context that can preempt -/// watched threads -- the highest-priority task in the system, not an ISR. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "extras/util/Timer.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include "CmsisRtos2DelegateQueue.h" -#include "cmsis_os2.h" -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -class CmsisRtos2Thread : public dmq::IThread -{ -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Default queue size if 0 is passed - static const uint32_t DEFAULT_QUEUE_SIZE = dmq::DEFAULT_QUEUE_SIZE; - - /// Constructor - /// @param threadName Name for the thread - /// @param maxQueueSize Max number of messages in queue (0 = Default dmq::DEFAULT_QUEUE_SIZE) - /// @param fullPolicy Action when queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - CmsisRtos2Thread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - CmsisRtos2Thread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : CmsisRtos2Thread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - ~CmsisRtos2Thread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - osThreadId_t GetThreadId(); - static osThreadId_t GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Set the thread priority. - /// Can be called before or after CreateThread(). - void SetThreadPriority(osPriority_t priority); - - /// Get current priority - osPriority_t GetThreadPriority(); - - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get current queue size - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(m_thread == NULL); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(m_thread == NULL); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(m_thread == NULL); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning CmsisRtos2Thread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(m_thread == NULL); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(m_thread == NULL); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(m_thread == NULL); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(m_thread == NULL); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - CmsisRtos2Thread(const CmsisRtos2Thread&) = delete; - CmsisRtos2Thread& operator=(const CmsisRtos2Thread&) = delete; - - // Entry point - static void Process(void* argument); - void Run(); - - /// Check watchdog is expired. Called by WatchdogCheckAll(). - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static CmsisRtos2Thread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - const size_t m_queueSize; - const FullPolicy FULL_POLICY; - const dmq::Duration m_dispatchTimeout; - osPriority_t m_priority; - - osThreadId_t m_thread = NULL; - CmsisRtos2DelegateQueue m_queue; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - osSemaphoreId_t m_exitSem = NULL; // Semaphore to signal thread completion - osSemaphoreId_t m_startSem = NULL; // Released by Run() once the start handler has run - bool m_startSync = false; // CreateThread() waits for the start handler (kernel running) - std::atomic m_exit = false; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - std::atomic m_discard = false; // ExitPolicy::DISCARD: cancel queued messages instead of invoking - bool* m_selfExitPtr = nullptr; - - // Configurable sizes - static const uint32_t STACK_SIZE = static_cast(dmq::CMSIS_RTOS2_STACK_BYTES); // Bytes, DMQ_CMSIS_RTOS2_STACK_BYTES - static const uint32_t START_FLAG = 0x1U; // Thread flag: CreateThread() has stored m_thread - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - CmsisRtos2Thread* m_watchdogNext = nullptr; - -#if defined(DMQ_DATABUS_TOOLS) - osMutexId_t m_statMutex = NULL; // Mutex to protect statistics - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the CMSIS-RTOS2 port. -using Thread = CmsisRtos2Thread; - -} // namespace dmq::os - -#endif // _THREAD_CMSIS_RTOS2_H diff --git a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Ticks.h b/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Ticks.h deleted file mode 100644 index acfae3a..0000000 --- a/DelegateMQ/port/os/cmsis-rtos2/CmsisRtos2Ticks.h +++ /dev/null @@ -1,70 +0,0 @@ -#ifndef CMSIS_RTOS2_TICKS_H -#define CMSIS_RTOS2_TICKS_H - -/// @file CmsisRtos2Ticks.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Converts between std::chrono durations and CMSIS-RTOS2 kernel ticks. -/// -/// @details -/// Every CMSIS-RTOS2 timeout (osSemaphoreAcquire, osMessageQueuePut/Get, -/// osDelay, ...) and osKernelGetTickCount() are in kernel ticks, and the tick -/// rate is whatever the kernel is configured for (osKernelGetTickFreq()), not -/// necessarily 1 kHz. Every place in this port that passes a timeout to the -/// kernel or reads the tick count goes through these helpers. -/// -/// Included from DelegateOpt.h's early port-include block (before namespace -/// dmq opens), so it doesn't use dmq::Duration; the helpers are templated on -/// the chrono duration type instead, like CmsisRtos2Semaphore::Wait(). - -#include "cmsis_os2.h" -#include -#include - -namespace dmq::os { - - /// @return the kernel tick rate in Hz (1000 if the kernel reports 0). - inline uint32_t CmsisRtos2TickFreq() noexcept { - uint32_t freq = osKernelGetTickFreq(); - return freq != 0 ? freq : 1000u; - } - - /// @brief Convert a duration to a CMSIS-RTOS2 timeout in kernel ticks. - /// @details Rounds up, so a nonzero timeout never becomes 0 (a non-blocking - /// call) and never waits less than asked. duration::max() maps to - /// osWaitForever; a zero or negative duration maps to 0. A finite timeout - /// too long for 32 bits saturates just below osWaitForever. - template - uint32_t CmsisRtos2ToTicks(const std::chrono::duration& d) noexcept { - using DurationT = std::chrono::duration; - if (d == DurationT::max()) - return osWaitForever; - if (d <= DurationT::zero()) - return 0; - constexpr uint64_t maxFinite = static_cast(osWaitForever) - 1u; - // Saturate before converting to microseconds, which would overflow - // int64 for a huge finite seconds/hours value. 2,000,000 hours is more - // than 2^32 ticks at any tick rate of 1 Hz or above. - if (d > std::chrono::hours(2000000)) - return static_cast(maxFinite); - const auto us = std::chrono::ceil(d).count(); - const uint64_t freq = CmsisRtos2TickFreq(); - if (static_cast(us) > (UINT64_MAX - 999999u) / freq) - return static_cast(maxFinite); - const uint64_t ticks = (static_cast(us) * freq + 999999u) / 1000000u; - return static_cast(ticks > maxFinite ? maxFinite : ticks); - } - - /// @brief Convert a kernel tick count to milliseconds. - inline uint64_t CmsisRtos2TicksToMs(uint64_t ticks) noexcept { - const uint64_t freq = CmsisRtos2TickFreq(); - if (freq == 1000u) - return ticks; - // Split to avoid overflowing ticks * 1000 on a long uptime. - return (ticks / freq) * 1000u + ((ticks % freq) * 1000u) / freq; - } - -} // namespace dmq::os - -#endif // CMSIS_RTOS2_TICKS_H diff --git a/DelegateMQ/port/os/common/CurrentThreadStorage.h b/DelegateMQ/port/os/common/CurrentThreadStorage.h deleted file mode 100644 index 7690224..0000000 --- a/DelegateMQ/port/os/common/CurrentThreadStorage.h +++ /dev/null @@ -1,169 +0,0 @@ -#ifndef _CURRENT_THREAD_STORAGE_H -#define _CURRENT_THREAD_STORAGE_H - -/// @file CurrentThreadStorage.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Per-thread storage behind dmq::ThisThread::GetCurrent(). -/// -/// @details Each port's ThisThread struct (e.g. StdlibThisThread) derives from one -/// of these to supply GetCurrent(), which returns the dmq::IThread whose worker is -/// the calling thread. Values are written only by dmq::CurrentThreadScope (IThread.h), -/// which a worker loop creates on its own thread: -/// * ThreadLocalCurrentThread - C++ thread_local (desktop ports). -/// * RegistryCurrentThread - a fixed table keyed by the RTOS's native thread handle, -/// for RTOS ports, where C++ thread_local is not tied to the RTOS's task switching. -/// * NoCurrentThread - always nullptr (bare metal: no threads). -/// -/// Included from DelegateOpt.h (via each port's ThisThread header), after the -/// DelegateMQ config and Fault.h, which provide DMQ_MAX_CURRENT_THREADS and -/// DMQ_ASSERT_TRUE. - -#include -#include -#include - -namespace dmq { - class IThread; - class CurrentThreadScope; -} - -namespace dmq::os { - -/// @brief Current-thread storage using C++ thread_local, for ports whose threads -/// are native OS threads (stdlib, Win32, Qt, POSIX). -struct ThreadLocalCurrentThread -{ - /// @return the IThread whose worker is the calling thread, or nullptr. - static dmq::IThread* GetCurrent() noexcept { return Slot(); } - -private: - friend class dmq::CurrentThreadScope; - - static dmq::IThread* SetCurrent(dmq::IThread* thread) noexcept - { - dmq::IThread* prev = Slot(); - Slot() = thread; - return prev; - } - - static dmq::IThread*& Slot() noexcept - { - static thread_local dmq::IThread* current = nullptr; - return current; - } -}; - -/// @brief Current-thread storage for RTOS ports: a fixed table of (native thread -/// key, IThread*) slots, one per thread currently inside a CurrentThreadScope. -/// -/// @details GetCurrent() is lock-free: it scans for the calling thread's key, and -/// only that thread ever writes its own slot. SetCurrent() takes Lock only to claim -/// a free slot; it is called only from thread context (CurrentThreadScope), never -/// from an ISR. No heap and no RTOS configuration (task-local storage slots, -/// custom thread data) is required. -/// -/// @tparam GetKey Returns a nonzero key identifying the calling thread (typically -/// its native handle), or 0 when there is no calling thread (e.g. inside an ISR, -/// where the port can detect it); GetCurrent() then returns nullptr. -/// @tparam Lock The port's mutex type (lock()/unlock()). -/// @tparam Capacity Max threads registered at once. Exceeding it faults; raise -/// DMQ_MAX_CURRENT_THREADS (dmq::MAX_CURRENT_THREADS) for more threads. The macro -/// is used directly because this is instantiated before DelegateOpt.h defines -/// the dmq:: constant. -template -class RegistryCurrentThread -{ -public: - /// @return the IThread whose worker is the calling thread, or nullptr. - static dmq::IThread* GetCurrent() noexcept - { - const uintptr_t key = GetKey(); - if (key == 0) - return nullptr; - Slot* slot = Find(key); - return slot ? slot->thread : nullptr; - } - -private: - friend class dmq::CurrentThreadScope; - - struct Slot - { - std::atomic key{ 0 }; // 0 = free - dmq::IThread* thread = nullptr; // written only by the thread owning the key - }; - - static dmq::IThread* SetCurrent(dmq::IThread* thread) - { - const uintptr_t key = GetKey(); - DMQ_ASSERT_TRUE(key != 0); // A CurrentThreadScope needs a calling thread - - Slot* slot = Find(key); - dmq::IThread* prev = slot ? slot->thread : nullptr; - - if (slot) - { - slot->thread = thread; - if (thread == nullptr) - slot->key.store(0, std::memory_order_release); // Release the slot - return prev; - } - - if (thread == nullptr) - return prev; - - // Claim a free slot. Other threads may be claiming too; releases need no lock. - GetLock().lock(); - for (Slot& s : s_slots) - { - if (s.key.load(std::memory_order_acquire) == 0) - { - s.thread = thread; - s.key.store(key, std::memory_order_release); - GetLock().unlock(); - return prev; - } - } - GetLock().unlock(); - - // More threads registered at once than DMQ_MAX_CURRENT_THREADS - DMQ_ASSERT_TRUE(false); - return prev; - } - - static Slot* Find(uintptr_t key) noexcept - { - for (Slot& s : s_slots) - { - if (s.key.load(std::memory_order_acquire) == key) - return &s; - } - return nullptr; - } - - static Lock& GetLock() - { - static Lock lock; - return lock; - } - - static inline Slot s_slots[Capacity]; -}; - -/// @brief For ports without threads (bare metal): GetCurrent() always returns nullptr. -struct NoCurrentThread -{ - /// @return always nullptr. - static dmq::IThread* GetCurrent() noexcept { return nullptr; } - -private: - friend class dmq::CurrentThreadScope; - - static dmq::IThread* SetCurrent(dmq::IThread*) noexcept { return nullptr; } -}; - -} // namespace dmq::os - -#endif diff --git a/DelegateMQ/port/os/common/PortableScopedLock.h b/DelegateMQ/port/os/common/PortableScopedLock.h deleted file mode 100644 index 8593f93..0000000 --- a/DelegateMQ/port/os/common/PortableScopedLock.h +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef _PORTABLE_SCOPED_LOCK_H -#define _PORTABLE_SCOPED_LOCK_H - -/// @file PortableScopedLock.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Multi-mutex lock for toolchains without std::scoped_lock. -/// -/// @details Some bare-metal standard libraries, built without thread support -/// (e.g. Arm GNU Toolchain 14), provide but no std::scoped_lock. -/// DelegateOpt.h selects this class as dmq::ScopedLock on those toolchains only; -/// everywhere else dmq::ScopedLock is std::scoped_lock. -/// -/// Locks the mutexes in address order, so two locks over the same mutexes can't -/// deadlock, and unlocks in reverse order. A mutex passed twice is locked once. -/// All mutexes must be the same type (every DelegateMQ use is). - -#include -#include -#include - -namespace dmq::os { - -template -class PortableScopedLock { - static_assert((std::is_same_v && ...), - "PortableScopedLock: all mutexes must be the same type"); - static constexpr std::size_t N = 1 + sizeof...(Rest); - M* m_mutexes[N]; - - // A mutex passed twice sorts next to its duplicate. - bool IsDuplicate(std::size_t i) const noexcept { - return i > 0 && m_mutexes[i] == m_mutexes[i - 1]; - } - -public: - explicit PortableScopedLock(M& first, Rest&... rest) : m_mutexes{ &first, &rest... } { - for (std::size_t i = 1; i < N; i++) { // insertion sort by address - M* m = m_mutexes[i]; - std::size_t j = i; - for (; j > 0 && std::less()(m, m_mutexes[j - 1]); j--) - m_mutexes[j] = m_mutexes[j - 1]; - m_mutexes[j] = m; - } - for (std::size_t i = 0; i < N; i++) - if (!IsDuplicate(i)) m_mutexes[i]->lock(); - } - - ~PortableScopedLock() { - for (std::size_t i = N; i-- > 0;) - if (!IsDuplicate(i)) m_mutexes[i]->unlock(); - } - - PortableScopedLock(const PortableScopedLock&) = delete; - PortableScopedLock& operator=(const PortableScopedLock&) = delete; -}; - -} // namespace dmq::os - -#endif // _PORTABLE_SCOPED_LOCK_H diff --git a/DelegateMQ/port/os/common/StartGate.h b/DelegateMQ/port/os/common/StartGate.h deleted file mode 100644 index 561421c..0000000 --- a/DelegateMQ/port/os/common/StartGate.h +++ /dev/null @@ -1,311 +0,0 @@ -#ifndef _DMQ_START_GATE_H -#define _DMQ_START_GATE_H - -/// @file -/// @brief Optional start gate: hold any number of threads until one "go". -/// -/// @details A `dmq::os::Thread` given a gate with `SetStartGate()` is created -/// as usual: `CreateThread()` runs its start handler and returns once the -/// thread is ready, and other threads can dispatch to it. It then waits at the -/// gate and processes nothing, at any priority, until `Open()` is called. Every -/// thread holding at the gate is released at once. -/// -/// Typical startup: create every thread with the same gate, wire up -/// subscriptions and connections, then call `Open()`. No thread runs a -/// message while others are still being created or connected. -/// -/// @code -/// dmq::os::StartGate gate; -/// sensors.SetStartGate(&gate); // before CreateThread() -/// network.SetStartGate(&gate); -/// sensors.CreateThread(); // ready, holding at the gate -/// network.CreateThread(); -/// // ... subscribe, connect; dispatched messages wait in the queues ... -/// gate.Open(); // all gated threads start together -/// @endcode -/// -/// - A thread with no gate (the default) is unaffected. -/// - The start handler runs before the gate, during `CreateThread()`. Keep it -/// to local setup: other threads may not exist yet. -/// - `Open()` is permanent: a thread created (or re-created) after it passes -/// straight through. `Close()` makes the gate hold threads again. -/// - There is no timeout. A gate that is never opened holds its threads -/// until they are told to exit. -/// - `ExitThread()` on a held thread releases it without running any queued -/// message; those messages are canceled as for `ExitPolicy::DISCARD`. -/// - A held thread is not reported by the watchdog. Its watchdog starts when -/// the gate opens. -/// - Lifetime: the gate may be destroyed right after `Open()`, e.g. a local in -/// a startup function. Its destructor waits for every released thread to -/// leave the gate (they may not have run yet). Destroying it while a thread -/// is still held (not opened, not exited) faults. `CreateThread()` uses the -/// gate again, so call `SetStartGate(nullptr)` before re-creating a thread -/// whose gate is gone. On an RTOS, don't destroy it before the scheduler runs. -/// -/// Supported where `DMQ_HAS_START_GATE` is defined (delegate/DelegateSelect.h): -/// every thread port (not bare metal, which has no threads). - -#include "delegate/DelegateOpt.h" -#include "delegate/Semaphore.h" -#include -#include -#include - -#if defined(DMQ_HAS_START_GATE) && defined(DMQ_HAS_SEMAPHORE) - -namespace dmq::os { - -class StartGateClient; - -class StartGate -{ -public: - StartGate() = default; - - /// Waits for every released thread to leave the gate. Faults if a thread - /// is still held: it would wait forever. - ~StartGate() - { - for (;;) - { - { - dmq::LockGuard lock(m_mutex); - DMQ_ASSERT_TRUE(m_held == 0); // a thread still held would never leave - if (m_users == 0) - return; - m_destroying = true; - } - // Signaled under m_mutex by the last thread to leave; relocking - // above means that signal has completed before members go away - m_idle.Wait(dmq::Duration::max()); - } - } - - /// Release every thread created with this gate so far, whether it is - /// already waiting or still on its way to the gate. Threads created later - /// pass straight through until Close(). - void Open() - { - dmq::LockGuard lock(m_mutex); - m_open = true; - m_openCount++; - m_held = 0; - for (Waiter* w = m_waiters; w != nullptr; w = w->next) - w->sem->Signal(); - } - - /// Hold threads created from now on (to reuse the gate for another - /// startup). Threads released by an earlier Open() still start, even if - /// they haven't reached the gate or woken yet. - void Close() - { - dmq::LockGuard lock(m_mutex); - m_open = false; - } - - bool IsOpen() const - { - dmq::LockGuard lock(m_mutex); - return m_open; - } - - StartGate(const StartGate&) = delete; - StartGate& operator=(const StartGate&) = delete; - -private: - friend class StartGateClient; - - /// What a thread got from Attach(): the open count then, and whether the - /// gate was holding (it counts in m_held until released or detached). - struct Ticket - { - uint32_t openCount = 0; - bool held = false; - }; - - /// One per waiting thread, on that thread's stack; `sem` is the thread's - /// own (StartGateClient), so the gate allocates nothing. - struct Waiter - { - dmq::Semaphore* sem = nullptr; - Waiter* next = nullptr; - }; - - /// CreateThread(), before the thread starts: the gate is in use until the - /// thread Detach()es, so it can't be destroyed under it. - Ticket Attach() - { - dmq::LockGuard lock(m_mutex); - m_users++; - Ticket t; - t.openCount = m_openCount; - t.held = !m_open; - if (t.held) - m_held++; - return t; - } - - /// The thread is done with the gate (left Wait(), or was never started). - /// Last access to the gate by that thread. - void Detach(const Ticket& t) - { - dmq::LockGuard lock(m_mutex); - if (t.held && t.openCount == m_openCount) - m_held--; // not released by an Open(), so still counted - m_users--; - if (m_users == 0 && m_destroying) - m_idle.Signal(); - } - - /// Attached while open (passes through even if Close() came since), open - /// now, or opened since the ticket was taken. - bool Released(const Ticket& t) const - { - return !t.held || m_open || m_openCount != t.openCount; - } - - /// On the thread itself, after its start handshake and before its message - /// loop. Blocks until the gate opens (now or since Attach()) or `exit` is - /// set and `sem` signaled (StartGateClient::Wake()). Detaches before - /// returning, so the gate isn't touched afterwards. - /// @return true if the gate opened: the thread enters its loop, and an exit - /// requested meanwhile follows its ExitPolicy (DRAIN runs the queued - /// messages). false if the thread was told to exit while still held: it - /// runs nothing. - bool Wait(const std::atomic& exit, const Ticket& t, dmq::Semaphore& sem) - { - Waiter self; - self.sem = &sem; - bool opened; - bool waiting = false; // decided once, under the lock: on the list or not - { - dmq::LockGuard lock(m_mutex); - opened = Released(t); - if (!opened && !exit.load()) - { - self.next = m_waiters; - m_waiters = &self; - waiting = true; - } - } - - // Open() signals under m_mutex; ExitThread() signals `sem` directly - // after setting `exit`. A signal sent before this wait starts is kept - // by the semaphore, and a stale one only causes an extra check. - while (waiting) - { - sem.Wait(dmq::Duration::max()); - dmq::LockGuard lock(m_mutex); - if (exit.load() || Released(t)) - { - opened = Released(t); - Unlink(&self); - waiting = false; - } - } - - Detach(t); - return opened; - } - - void Unlink(Waiter* target) - { - for (Waiter** pp = &m_waiters; *pp != nullptr; pp = &(*pp)->next) - { - if (*pp == target) - { - *pp = target->next; - return; - } - } - } - - mutable dmq::Mutex m_mutex; - bool m_open = false; - uint32_t m_openCount = 0; // Open() calls; wraps harmlessly (only compared for change) - uint32_t m_users = 0; // threads attached and not yet detached - uint32_t m_held = 0; // of those, attached while closed and not released since - bool m_destroying = false; - Waiter* m_waiters = nullptr; - dmq::Semaphore m_idle; // ~StartGate() waits on it for m_users to reach 0 -}; - -/// A thread port's start gate state: one member per `dmq::os::Thread`, so -/// every port wires the gate the same way. -/// -/// Port calls: `Set()` from SetStartGate(); `OnCreate()` in CreateThread() -/// before the thread exists, and `OnCreateFailed()` if it then can't be -/// created; `Enabled()`/`Wait()`/`Passed()` on the thread before its loop; -/// `Wake()` in ExitThread() after setting the exit flag, and `Leave()` on its -/// self-exit path; `IsHeld()` in WatchdogCheck(). -class StartGateClient -{ -public: - void Set(StartGate* gate) { m_gate = gate; } - StartGate* Get() const { return m_gate; } - - void OnCreate() - { - m_held.store(m_gate != nullptr); - m_attached = false; - if (m_gate) - { - if (!m_wake) - m_wake.emplace(); // created here, not in the Thread constructor (RTOS heap) - m_ticket = m_gate->Attach(); - m_attached = true; - } - } - - void OnCreateFailed() { Leave(); } - - /// ExitThread() on a self-exit, from the thread itself: if it exited from - /// its start handler it never reaches Wait(), so detach here, while the - /// object is alive. No effect once the thread has passed the gate. - void Leave() - { - if (m_attached) - m_gate->Detach(m_ticket); - m_attached = false; - m_held.store(false); - } - - /// True if this thread must wait at a gate before its loop. - bool Enabled() const { return m_attached; } - - /// Thread side. Returns true if the gate opened; see StartGate::Wait(). - /// The gate is not touched after this returns. - bool Wait(const std::atomic& exit) - { - m_attached = false; - return m_gate->Wait(exit, m_ticket, *m_wake); - } - - /// Thread side, after Wait() and after refreshing the watchdog heartbeat: - /// no longer held. - void Passed() { m_held.store(false); } - - /// ExitThread(): wake this thread if it is waiting at its gate. Uses only - /// this object, never the gate, so a destroyed gate is never touched. - void Wake() - { - if (m_wake && m_held.load()) - m_wake->Signal(); - } - - /// Held at the gate: the watchdog skips the thread. - bool IsHeld() const { return m_held.load(); } - -private: - StartGate* m_gate = nullptr; - std::atomic m_held{false}; - bool m_attached = false; - StartGate::Ticket m_ticket; - std::optional m_wake; -}; - -} // namespace dmq::os - -#endif // DMQ_HAS_START_GATE && DMQ_HAS_SEMAPHORE - -#endif // _DMQ_START_GATE_H diff --git a/DelegateMQ/port/os/common/ThreadHooks.h b/DelegateMQ/port/os/common/ThreadHooks.h deleted file mode 100644 index eb23582..0000000 --- a/DelegateMQ/port/os/common/ThreadHooks.h +++ /dev/null @@ -1,109 +0,0 @@ -#ifndef _THREAD_HOOKS_H -#define _THREAD_HOOKS_H - -/// @file ThreadHooks.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Start, exit and idle handler support shared by the dmq::os::Thread ports. -/// -/// @details Each port exposes SetStartHandler()/SetExitHandler()/SetIdleHandler() -/// and calls these helpers from its worker loop, so the handler semantics stay the -/// same on every port: -/// * The start handler runs on the worker thread before any message, and -/// CreateThread() returns only after it completes. -/// * The exit handler runs on the worker thread after the last message, on every -/// loop return path (ThreadExitGuard). -/// * The idle handler runs on the worker thread once its queue has been empty for -/// the idle interval, then every interval while it stays empty; any processed -/// message restarts the countdown (ThreadIdleTimer). -/// -/// Both helpers take a copy of the handler when the loop starts, so they can run -/// after the owning Thread object has been destroyed (a thread that exits itself). - -#include "delegate/DelegateOpt.h" -#include "delegate/UnicastDelegate.h" - -namespace dmq::os { - -/// @brief Runs a thread's exit handler when the worker loop's stack frame unwinds. -/// Declare it at the top of the loop function, before any return. -class ThreadExitGuard -{ -public: - explicit ThreadExitGuard(const dmq::UnicastDelegate& handler) : m_handler(handler) {} - ~ThreadExitGuard() { Fire(); } - - /// @brief Run the exit handler now rather than at scope exit, e.g. before the - /// loop signals ExitThread() that it has finished. Runs it at most once. - void Fire() - { - if (!m_fired && m_handler) - m_handler(); - m_fired = true; - } - -private: - ThreadExitGuard(const ThreadExitGuard&) = delete; - ThreadExitGuard& operator=(const ThreadExitGuard&) = delete; - - dmq::UnicastDelegate m_handler; - bool m_fired = false; -}; - -/// @brief Tracks when a worker loop's idle handler is next due. -/// @details Usage per loop iteration: bound the queue wait with WaitTime(); if the -/// wait ends with the queue empty and IsDue(), call Run(); after processing a -/// message, call Restart(). All methods are no-ops when no handler is set. -class ThreadIdleTimer -{ -public: - ThreadIdleTimer(const dmq::UnicastDelegate& handler, dmq::Duration interval) - : m_handler(handler), m_interval(interval), m_due(dmq::Clock::now() + interval) {} - - /// @return true if an idle handler is set. - bool Enabled() const { return static_cast(m_handler); } - - /// @brief Bound a queue wait so the loop wakes when the idle handler is due. - /// @param[in] wait - the loop's own wait bound (e.g. the watchdog heartbeat), - /// or a negative duration to mean "wait forever". - /// @return the shorter of `wait` and the time until the idle handler is due - /// (never negative when the idle handler is enabled); `wait` unchanged otherwise. - dmq::Duration WaitTime(dmq::Duration wait) const - { - if (!Enabled()) - return wait; - dmq::Duration untilIdle = m_due - dmq::Clock::now(); - if (untilIdle < dmq::Duration::zero()) - untilIdle = dmq::Duration::zero(); - if (wait < dmq::Duration::zero() || untilIdle < wait) - return untilIdle; - return wait; - } - - /// @return true if the idle handler is set and its interval has elapsed. - bool IsDue() const { return Enabled() && dmq::Clock::now() >= m_due; } - - /// @brief Restart the countdown. Call after processing each message. - void Restart() - { - if (Enabled()) - m_due = dmq::Clock::now() + m_interval; - } - - /// @brief Invoke the idle handler and restart the countdown. - void Run() - { - m_handler(); - Restart(); - } - -private: - const dmq::UnicastDelegate m_handler; - const dmq::Duration m_interval; - dmq::TimePoint m_due; -}; - -} // namespace dmq::os - -#endif diff --git a/DelegateMQ/port/os/common/ThreadMsg.h b/DelegateMQ/port/os/common/ThreadMsg.h deleted file mode 100644 index 6b06e4b..0000000 --- a/DelegateMQ/port/os/common/ThreadMsg.h +++ /dev/null @@ -1,83 +0,0 @@ -#ifndef DMQ_OS_COMMON_THREAD_MSG_H -#define DMQ_OS_COMMON_THREAD_MSG_H - -/// @file ThreadMsg.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief A class to hold a platform-specific thread message that will be passed -/// through a dmq::os::Thread port's OS message queue. -/// -/// @details -/// Identical across every dmq::os::Thread port (FreeRTOS, ThreadX, Zephyr, -/// CMSIS-RTOS2, stdlib, Win32) except Qt, which dispatches via Qt's own -/// signal/slot queued-connection mechanism instead of a ThreadMsg wrapper -- -/// kept as a single shared file here instead of one copy per port directory. - -#include "delegate/DelegateOpt.h" -#include - -namespace dmq::os { - -// Message IDs -#define MSG_DISPATCH_DELEGATE 1 -#define MSG_EXIT_THREAD 2 - -class ThreadMsg -{ -public: - /// Constructor - /// @param[in] id - a unique identifier for the thread message - /// @param[in] data - a pointer to the message data to be typecast - /// by the receiving task based on the id value. - ThreadMsg(int id, std::shared_ptr data = nullptr) - : m_id(id), m_data(data) { - } - - virtual ~ThreadMsg() = default; - - int GetId() const { return m_id; } - std::shared_ptr GetData() const { return m_data; } - - /// Get the message priority - dmq::Priority GetPriority() const { - return m_data ? m_data->GetPriority() : dmq::Priority::NORMAL; - } - -#if defined(DMQ_DATABUS_TOOLS) - void SetEnqueueTime(dmq::TimePoint time) { m_enqueueTime = time; } - dmq::TimePoint GetEnqueueTime() const { return m_enqueueTime; } -#endif - -private: - int m_id; - std::shared_ptr m_data; -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint m_enqueueTime; -#endif - - // Use fixed-block memory allocator if DMQ_ALLOCATOR set - XALLOCATOR -}; - -/// @brief Discard a queued message without invoking it: a sender blocked waiting -/// on it is released and sees the call fail (DelegateMsg::Cancel()). Used for -/// dmq::ExitPolicy::DISCARD and for messages still queued when a thread exits. -inline void CancelThreadMsg(const ThreadMsg& msg) -{ - if (auto delegateMsg = msg.GetData()) - delegateMsg->Cancel(); -} - -/// @brief CancelThreadMsg() every message in a queue of std::shared_ptr, then clear it. -template -void CancelAll(Queue& queue) -{ - for (auto& msg : queue) - CancelThreadMsg(*msg); - queue.clear(); -} - -} // namespace dmq::os - -#endif // DMQ_OS_COMMON_THREAD_MSG_H diff --git a/DelegateMQ/port/os/freertos/FreeRTOSClock.h b/DelegateMQ/port/os/freertos/FreeRTOSClock.h deleted file mode 100644 index f2e63de..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSClock.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef FREERTOS_CLOCK_H -#define FREERTOS_CLOCK_H - -#include "FreeRTOS.h" -#include "task.h" -#include "FreeRTOSCriticalSection.h" -#include - -namespace dmq::os { - struct FreeRTOSClock { - // 1. Define duration traits. - // NOTE: This assumes configTICK_RATE_HZ is 1000 (1ms ticks). - // If your system uses a different tick rate, change std::milli to std::ratio<1, configTICK_RATE_HZ>. - using rep = int64_t; - using period = std::milli; - using duration = std::chrono::duration; - using time_point = std::chrono::time_point; - static const bool is_steady = true; - - // 2. The critical "now()" function - static time_point now() noexcept { - // Static state to track the tick rollover. - // 1. It must be called at least once per rollover period to detect the wrap. - // 2. Thread/ISR safety: protected by the critical section below. - static TickType_t last = 0; - static uint64_t high = 0; - - // Timer::ProcessTimers() calls this through Timer::GetNow(), and on a - // real Cortex-M target ProcessTimers() may run in a hardware ISR (see - // CLAUDE.md "ISR-Safe Locking"). taskENTER_CRITICAL() and - // xTaskGetTickCount() are task-only, so use FreeRTOSCriticalSection - // (which picks taskENTER_CRITICAL[_FROM_ISR] by context) and the - // matching tick-count call. Nesting inside Timer's own - // FreeRTOSCriticalSection is safe: each instance saves and restores - // its own state, released in LIFO order. - const bool inIsr = detail::IsInsideFreeRTOSInterrupt() != pdFALSE; - FreeRTOSCriticalSection cs; - cs.lock(); - - TickType_t cur = inIsr ? xTaskGetTickCountFromISR() : xTaskGetTickCount(); - - // If TickType_t is 64-bit, we don't need the rollover logic as it essentially never wraps. - // This also prevents a compilation error (shift count >= width of type). - if (sizeof(TickType_t) < 8) { - // Determine the rollover modulus based on the width of TickType_t. - // This makes the logic portable for both 16-bit and 32-bit FreeRTOS ticks. - // Note: Use a ternary to ensure we never shift by 64 even during constexpr evaluation. - constexpr uint32_t SHIFT_AMT = (sizeof(TickType_t) < 8) ? (sizeof(TickType_t) * 8) : 0; - constexpr uint64_t TICK_MODULO = static_cast(1ULL) << SHIFT_AMT; - - // Check for wrap-around - if (cur < last) { - high += TICK_MODULO; - } - } - - last = cur; - - // Combine high part with current tick - uint64_t ticks = high + cur; - - cs.unlock(); - - return time_point(duration(static_cast(ticks))); - } - }; -} // namespace dmq::os - -#endif // FREERTOS_CLOCK_H \ No newline at end of file diff --git a/DelegateMQ/port/os/freertos/FreeRTOSConditionVariable.h b/DelegateMQ/port/os/freertos/FreeRTOSConditionVariable.h deleted file mode 100644 index 4a4bcde..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSConditionVariable.h +++ /dev/null @@ -1,136 +0,0 @@ -#ifndef FREERTOS_CONDITION_VARIABLE_H -#define FREERTOS_CONDITION_VARIABLE_H - -#include "FreeRTOS.h" -#include "semphr.h" -#include "task.h" -#include - -namespace dmq::os { - /// @brief Production-grade wrapper around FreeRTOS Semaphore to mimic std::condition_variable - /// @details - /// - Uses a Binary Semaphore (1 token). - /// - ISR-safe notification logic. - /// - Robust tick overflow handling using elapsed time subtraction. - /// - /// @note Limitation: Unlike std::cv, a binary semaphore retains its signal state. - /// If notify() occurs before wait(), the wait will effectively "fall through". - /// Multiple notifies before a wait are coalesced into a single signal. - class FreeRTOSConditionVariable - { - public: - FreeRTOSConditionVariable() - { - // Binary semaphore is sufficient for signaling state changes - m_sem = xSemaphoreCreateBinary(); - - // Critical check: Ensure heap was sufficient - configASSERT(m_sem != NULL); - } - - ~FreeRTOSConditionVariable() - { - if (m_sem) { - vSemaphoreDelete(m_sem); - } - } - - FreeRTOSConditionVariable(const FreeRTOSConditionVariable&) = delete; - FreeRTOSConditionVariable& operator=(const FreeRTOSConditionVariable&) = delete; - - /// @brief Wake up one waiting thread (ISR Safe) - void notify_one() noexcept - { - if (!m_sem) return; - -#if defined(_WIN32) || defined(WIN32) || defined(__linux__) - // Simulator Ports (Windows/Linux): - // "Interrupts" are simulated. The hardware ISR check - // often does not exist. Standard API is safe here. - xSemaphoreGive(m_sem); -#else - // Embedded (e.g., ARM Cortex-M): - // Must check if running in ISR context to use FromISR API. - if (xPortIsInsideInterrupt()) - { - BaseType_t xHigherPriorityTaskWoken = pdFALSE; - xSemaphoreGiveFromISR(m_sem, &xHigherPriorityTaskWoken); - portYIELD_FROM_ISR(xHigherPriorityTaskWoken); - } - else - { - xSemaphoreGive(m_sem); - } -#endif - } - - /// @brief Wait indefinitely until predicate is true - template - void wait(Lock& lock, Predicate pred) - { - while (!pred()) - { - if (lock.owns_lock()) - lock.unlock(); - - // Wait indefinitely - BaseType_t ret = xSemaphoreTake(m_sem, portMAX_DELAY); - configASSERT(ret == pdTRUE); - - if (!lock.owns_lock()) - lock.lock(); - } - } - - /// @brief Wait until predicate is true or timeout expires - /// @details Uses overflow-safe subtraction logic to track elapsed ticks. - template - bool wait_for(Lock& lock, std::chrono::milliseconds timeout, Predicate pred) - { - const TickType_t timeoutTicks = pdMS_TO_TICKS(timeout.count()); - const TickType_t start = xTaskGetTickCount(); - - while (!pred()) - { - TickType_t now = xTaskGetTickCount(); - - // Overflow-safe elapsed time calculation - TickType_t elapsed = now - start; - - if (elapsed >= timeoutTicks) - { - if (!lock.owns_lock()) - lock.lock(); - return pred(); // Timeout expired, check predicate one last time - } - - TickType_t remaining = timeoutTicks - elapsed; - - if (lock.owns_lock()) - lock.unlock(); - - // Wait for the semaphore or timeout - BaseType_t res = xSemaphoreTake(m_sem, remaining); - - if (!lock.owns_lock()) - lock.lock(); - - if (res == pdFALSE) - { - // Semaphore timeout occurred - return pred(); - } - - // If success (res == pdTRUE), loop around and check pred() again. - // If pred() is still false, it was a spurious wakeup or coalesced signal. - } - - return true; - } - - private: - SemaphoreHandle_t m_sem = NULL; - }; -} // namespace dmq::os - -#endif // FREERTOS_CONDITION_VARIABLE_H \ No newline at end of file diff --git a/DelegateMQ/port/os/freertos/FreeRTOSCriticalSection.h b/DelegateMQ/port/os/freertos/FreeRTOSCriticalSection.h deleted file mode 100644 index 4421bd8..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSCriticalSection.h +++ /dev/null @@ -1,122 +0,0 @@ -#ifndef FREERTOS_CRITICAL_SECTION_H -#define FREERTOS_CRITICAL_SECTION_H - -/// @file FreeRTOSCriticalSection.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ISR-safe critical section for FreeRTOS. -/// -/// @details -/// Unlike ThreadX/Zephyr/CMSIS-RTOS2, FreeRTOS has no single primitive that -/// is safe to call from BOTH thread and ISR context: it splits critical -/// sections into two separate APIs -- taskENTER_CRITICAL()/EXIT() for task -/// context, taskENTER_CRITICAL_FROM_ISR()/EXIT_FROM_ISR() for ISR context -- -/// and expects the caller to already know which one applies. Calling the -/// wrong one for the current context is undefined behavior. -/// -/// This type resolves that at runtime via xPortIsInsideInterrupt(), so -/// lock()/unlock() work correctly from either context without the caller -/// needing to know which one it's in -- exactly the contract -/// dmq::util::Timer::GetLock() needs, since Timer::ProcessTimers() is -/// documented as callable from the highest-priority context available. -/// -/// xPortIsInsideInterrupt() is provided by every real ARM Cortex-M FreeRTOS -/// port this project supports (ARM_CM3, CM4F, CM7, CM23, CM33, CM55 -- -/// e.g. the stm32-freertos sample), detected via reading the ARM Cortex-M -/// core register whose value is meaningless outside a real Cortex-M CPU. -/// The desktop simulator ports (POSIX, Win32 -- used by freertos-linux, -/// freertos-bare-metal, databus-freertos) do not provide it: they run as -/// an ordinary host-OS thread with no real hardware interrupt to detect, -/// so "always task context" is the correct (and only meaningful) answer -/// there. dmq::os::detail::IsInsideFreeRTOSInterrupt() below selects -/// between the two at compile time via the __arm__/__ARM_ARCH compiler -/// predefines (set by arm-none-eabi-gcc, never set when GCC/Clang builds -/// the desktop simulators for x86_64) -- no new DMQ_* build option needed, -/// and no risk of colliding with FreeRTOS's own xPortIsInsideInterrupt() -/// symbol, since we never redefine it under that name ourselves. -/// -/// @note Scoping assumption: this assumes ARM Cortex-M is the embedded -/// target, true for every FreeRTOS port this project currently supports. -/// A RISC-V or Xtensa FreeRTOS port would need the detection below -/// extended for its own architecture predefines. -/// -/// *** NARROW PURPOSE -- DO NOT USE THIS AS A GENERAL-PURPOSE LOCK *** -/// On the ISR path this masks interrupts up to configMAX_SYSCALL_INTERRUPT_PRIORITY -/// for as long as it is held; on the task path it disables the scheduler -/// and masks interrupts the same way. Only use it to protect something -/// genuinely tiny and bounded that may be touched from ISR context. Do NOT -/// use it in place of dmq::Mutex / dmq::RecursiveMutex for ordinary -/// thread-to-thread synchronization (e.g. DataBus internals, a Thread's -/// message queue) -- anything that can block, take a while, or run for an -/// unbounded time must not run with interrupts globally masked; that is a -/// real-time correctness bug on hardware, not just a style issue. -/// -/// *** NOT RE-LOCKABLE ON THE SAME INSTANCE *** -/// Unlike dmq::RecursiveMutex, calling lock() twice on the SAME instance -/// without an intervening unlock() is incorrect: the second lock() call -/// overwrites the single saved-interrupt-state member with the (already -/// masked) inner state, so the outer unlock() restores the wrong state. -/// There is no "recursive" variant of this type -- it has no ownership -/// concept to make recursion meaningful, and Timer's own usage never -/// nests. Locking two DIFFERENT instances in proper LIFO lock/unlock -/// order is fine: each instance saves and restores its own state -/// independently. - -#include "FreeRTOS.h" -#include "task.h" - -namespace dmq::os { - - namespace detail { -#if defined(__arm__) || defined(__ARM_ARCH) - // Real ARM Cortex-M FreeRTOS port -- it provides - // xPortIsInsideInterrupt() itself; call the real thing. - inline BaseType_t IsInsideFreeRTOSInterrupt() { return xPortIsInsideInterrupt(); } -#else - // Desktop simulator port (POSIX/Win32) -- no real hardware - // interrupt to detect; always task context. - inline BaseType_t IsInsideFreeRTOSInterrupt() { return pdFALSE; } -#endif - } // namespace detail - - // ========================================================================= - // FreeRTOSCriticalSection - // See the file-level comment above before using this type anywhere new. - // ========================================================================= - class FreeRTOSCriticalSection { - public: - FreeRTOSCriticalSection() = default; - - void lock() { - if (detail::IsInsideFreeRTOSInterrupt() != pdFALSE) { - m_savedInterruptStatus = taskENTER_CRITICAL_FROM_ISR(); - m_lockedFromIsr = true; - } else { - taskENTER_CRITICAL(); - m_lockedFromIsr = false; - } - } - - void unlock() { - if (m_lockedFromIsr) { - taskEXIT_CRITICAL_FROM_ISR(m_savedInterruptStatus); - } else { - taskEXIT_CRITICAL(); - } - } - - // No try_lock(): interrupt masking cannot fail to "acquire", so a - // try_lock() here would always trivially succeed and isn't meaningful. - - FreeRTOSCriticalSection(const FreeRTOSCriticalSection&) = delete; - FreeRTOSCriticalSection& operator=(const FreeRTOSCriticalSection&) = delete; - - private: - UBaseType_t m_savedInterruptStatus = 0; - bool m_lockedFromIsr = false; - }; - -} // namespace dmq::os - -#endif // FREERTOS_CRITICAL_SECTION_H diff --git a/DelegateMQ/port/os/freertos/FreeRTOSDelegateQueue.h b/DelegateMQ/port/os/freertos/FreeRTOSDelegateQueue.h deleted file mode 100644 index ee28e75..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSDelegateQueue.h +++ /dev/null @@ -1,191 +0,0 @@ -#ifndef FREERTOS_DELEGATE_QUEUE_H -#define FREERTOS_DELEGATE_QUEUE_H - -/// @file FreeRTOSDelegateQueue.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Thin RAII wrapper around a pair of FreeRTOS xQueue primitives used -/// by dmq::os::Thread to carry pending ThreadMsg pointers, with priority -/// support. See the Priority enum in delegate/DelegateMsg.h for the -/// cross-port ordering contract this class must uphold. -/// -/// @details -/// *** DO NOT "SIMPLIFY" THIS BACK TO ONE QUEUE + xQueueSendToFront() *** -/// An earlier version of this class used a single xQueue and called -/// xQueueSendToFront() for HIGH priority messages. That is WRONG: sending to -/// the front of a single queue makes HIGH messages a LIFO stack relative to -/// each other, not a FIFO lane. Concretely, starting from [Normal1]: -/// 1. HIGH-A sent to front -> [HIGH-A, Normal1] -/// 2. HIGH-B sent to front -> [HIGH-B, HIGH-A, Normal1] -/// The consumer then dequeues HIGH-B before HIGH-A, even though A arrived -/// first -- exactly backwards. See DelegateMsg.h's Priority comment for the -/// required contract (HIGH jumps ahead of NORMAL, but FIFO is preserved -/// within each priority). -/// -/// The fix: two independent xQueue instances, one per priority lane, each -/// always pushed to the BACK (xQueueSendToBack, never xQueueSendToFront). -/// FreeRTOS gives no way to block on "either of two queues has data" the way -/// a std::condition_variable can wait on an arbitrary predicate, so a -/// counting semaphore is used as a shared "doorbell": every successful Send() -/// (to either lane) gives the semaphore once; Receive() takes the semaphore -/// (the single blocking wait) and then does a non-blocking pop, checking the -/// HIGH lane first so it still drains ahead of NORMAL. This mirrors -/// StdlibThread's two-std::deque + one-condition_variable design and -/// ZephyrDelegateQueue's two-k_msgq + k_poll design -- same shape, RTOS-native -/// primitives. -/// -/// Each lane is sized to the full requested 'capacity' (like -/// ZephyrDelegateQueue), so worst-case combined depth is 2x capacity rather -/// than exactly capacity -- this doubles queue memory relative to the old -/// single-queue design. The semaphore's max count is sized to match (2x -/// capacity) so a Send() that already found room in its lane can never fail -/// to give the semaphore. -/// -/// Isolates the native xQueueCreate/xQueueSendToBack/xQueueReceive/ -/// vQueueDelete/xSemaphoreCreateCounting calls behind a small type so -/// Thread.cpp's DispatchDelegate()/Run() read as policy and dispatch logic, -/// not FreeRTOS API plumbing. This class owns no policy decisions of its own -/// (FullPolicy, timeout computation, and stats stay in Thread.cpp) -- it only -/// knows how to move ThreadMsg* pointers through two fixed-capacity FreeRTOS -/// queues in priority order. -/// -/// @note Requires configUSE_COUNTING_SEMAPHORES == 1 in the application's -/// FreeRTOSConfig.h (needed for xSemaphoreCreateCounting). - -#include "FreeRTOS.h" -#include "task.h" -#include "queue.h" -#include "semphr.h" -#include "port/os/common/ThreadMsg.h" - -namespace dmq::os { - -class FreeRTOSDelegateQueue -{ -public: - FreeRTOSDelegateQueue() = default; - ~FreeRTOSDelegateQueue() { Destroy(); } - - FreeRTOSDelegateQueue(const FreeRTOSDelegateQueue&) = delete; - FreeRTOSDelegateQueue& operator=(const FreeRTOSDelegateQueue&) = delete; - - /// Create the underlying HIGH and NORMAL queues, each with room for - /// 'capacity' pointers, plus the counting semaphore doorbell (max count - /// 2 * capacity, matching the combined capacity of both lanes). - /// @return true on success, false if any FreeRTOS object could not be - /// created (OOM). - bool Create(size_t capacity) - { - if (m_highQueue && m_normalQueue && m_countSem) - return true; - - if (!m_highQueue) - m_highQueue = xQueueCreate(static_cast(capacity), sizeof(ThreadMsg*)); - if (!m_normalQueue) - m_normalQueue = xQueueCreate(static_cast(capacity), sizeof(ThreadMsg*)); - if (!m_countSem) - m_countSem = xSemaphoreCreateCounting(static_cast(capacity * 2), 0); - - if (!m_highQueue || !m_normalQueue || !m_countSem) { - Destroy(); - return false; - } - return true; - } - - bool IsCreated() const { return m_highQueue != nullptr && m_normalQueue != nullptr && m_countSem != nullptr; } - - /// Send a message pointer. 'highPriority' routes to the HIGH lane, which - /// Receive() always drains first; otherwise the NORMAL lane. Both lanes - /// are always pushed to the BACK -- see the file-level comment for why - /// "send to front" must never be reintroduced here. 'waitTicks' is 0 for - /// non-blocking, portMAX_DELAY to block forever, or a finite tick count - /// for a bounded wait; it applies only to the queue push (each lane has - /// its own independent capacity -- there is no combined-depth wait across - /// both). Giving the doorbell semaphore never blocks and cannot fail: its - /// max count (2 * capacity) matches the combined lane capacity, so a - /// Send() that already found room in its lane always has room in the - /// semaphore's count too. - /// @return true if the message was enqueued. - bool Send(ThreadMsg* msg, bool highPriority, TickType_t waitTicks) - { - QueueHandle_t q = highPriority ? m_highQueue : m_normalQueue; - if (xQueueSendToBack(q, &msg, waitTicks) != pdPASS) - return false; - xSemaphoreGive(m_countSem); - return true; - } - - /// Receive a message pointer, blocking up to 'waitTicks'. The HIGH lane - /// is always checked -- and drained -- first, so a pending HIGH message - /// is returned even if NORMAL messages arrived earlier. Blocks on the - /// doorbell semaphore (the single native wait), then does a - /// non-blocking pop from whichever lane has data; the semaphore count - /// guarantees at least one lane is non-empty once the take succeeds. - /// @return the message, or nullptr on timeout. - ThreadMsg* Receive(TickType_t waitTicks) - { - if (xSemaphoreTake(m_countSem, waitTicks) != pdPASS) - return nullptr; // timed out waiting for either lane - - ThreadMsg* msg = nullptr; - if (xQueueReceive(m_highQueue, &msg, 0) == pdPASS) - return msg; - if (xQueueReceive(m_normalQueue, &msg, 0) == pdPASS) - return msg; - return nullptr; - } - - /// Combined number of messages waiting across both lanes. - size_t Size() const - { - if (!m_highQueue || !m_normalQueue) - return 0; - return static_cast(uxQueueMessagesWaiting(m_highQueue)) - + static_cast(uxQueueMessagesWaiting(m_normalQueue)); - } - - /// Remove and delete every pending message in both lanes without - /// blocking. Used during shutdown once the owning thread has stopped - /// consuming the queues. - /// Each message is canceled first (CancelThreadMsg()), releasing a sender - /// blocked waiting on it. - void DrainAndDelete() - { - ThreadMsg* msg = nullptr; - while (xQueueReceive(m_highQueue, &msg, 0) == pdPASS) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - while (xQueueReceive(m_normalQueue, &msg, 0) == pdPASS) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - } - - void Destroy() - { - if (m_highQueue) { - vQueueDelete(m_highQueue); - m_highQueue = nullptr; - } - if (m_normalQueue) { - vQueueDelete(m_normalQueue); - m_normalQueue = nullptr; - } - if (m_countSem) { - vSemaphoreDelete(m_countSem); - m_countSem = nullptr; - } - } - -private: - QueueHandle_t m_highQueue = nullptr; - QueueHandle_t m_normalQueue = nullptr; - SemaphoreHandle_t m_countSem = nullptr; -}; - -} // namespace dmq::os - -#endif // FREERTOS_DELEGATE_QUEUE_H diff --git a/DelegateMQ/port/os/freertos/FreeRTOSMutex.h b/DelegateMQ/port/os/freertos/FreeRTOSMutex.h deleted file mode 100644 index a7c90d3..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSMutex.h +++ /dev/null @@ -1,103 +0,0 @@ -#ifndef FREERTOS_MUTEX_H -#define FREERTOS_MUTEX_H - -#include "FreeRTOS.h" -#include "semphr.h" - -namespace dmq::os { - - // ========================================================================= - // FreeRTOSMutex (Non-Recursive) - // Matches std::mutex behavior - // ========================================================================= - class FreeRTOSMutex { - public: - FreeRTOSMutex() { - m_handle = xSemaphoreCreateMutex(); - configASSERT(m_handle); - } - - ~FreeRTOSMutex() { - if (m_handle) { - vSemaphoreDelete(m_handle); - } - } - - void lock() { - if (m_handle) { - BaseType_t ret = xSemaphoreTake(m_handle, portMAX_DELAY); - configASSERT(ret == pdTRUE); - } - } - - bool try_lock() { - if (m_handle) { - // Wait time of 0 ticks = non-blocking attempt - return xSemaphoreTake(m_handle, 0) == pdTRUE; - } - return false; - } - - void unlock() { - if (m_handle) { - xSemaphoreGive(m_handle); - } - } - - FreeRTOSMutex(const FreeRTOSMutex&) = delete; - FreeRTOSMutex& operator=(const FreeRTOSMutex&) = delete; - - private: - SemaphoreHandle_t m_handle = nullptr; - }; - - // ========================================================================= - // FreeRTOSRecursiveMutex (Recursive) - // Matches std::recursive_mutex behavior - // ========================================================================= - class FreeRTOSRecursiveMutex { - public: - FreeRTOSRecursiveMutex() { - // Requires configUSE_RECURSIVE_MUTEXES == 1 in FreeRTOSConfig.h - m_handle = xSemaphoreCreateRecursiveMutex(); - configASSERT(m_handle); - } - - ~FreeRTOSRecursiveMutex() { - if (m_handle) { - vSemaphoreDelete(m_handle); - } - } - - void lock() { - if (m_handle) { - BaseType_t ret = xSemaphoreTakeRecursive(m_handle, portMAX_DELAY); - configASSERT(ret == pdTRUE); - } - } - - // Added try_lock (Required by std::unique_lock) - bool try_lock() { - if (m_handle) { - // Wait time of 0 ticks = non-blocking attempt - return xSemaphoreTakeRecursive(m_handle, 0) == pdTRUE; - } - return false; - } - - void unlock() { - if (m_handle) { - xSemaphoreGiveRecursive(m_handle); - } - } - - FreeRTOSRecursiveMutex(const FreeRTOSRecursiveMutex&) = delete; - FreeRTOSRecursiveMutex& operator=(const FreeRTOSRecursiveMutex&) = delete; - - private: - SemaphoreHandle_t m_handle = nullptr; - }; - -} // namespace dmq::os - -#endif // FREERTOS_MUTEX_H \ No newline at end of file diff --git a/DelegateMQ/port/os/freertos/FreeRTOSThisThread.h b/DelegateMQ/port/os/freertos/FreeRTOSThisThread.h deleted file mode 100644 index 1dffb88..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSThisThread.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef FREERTOS_THIS_THREAD_H -#define FREERTOS_THIS_THREAD_H - -/// @file FreeRTOSThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Portable sleep_for()/yield() for the calling thread, FreeRTOS backend. -/// -/// @details -/// This is dmq::ThisThread for this port (see DelegateOpt.h). GetCurrent() -/// uses RegistryCurrentThread, keyed by the calling task's handle. Exists so -/// library internals that need to delay or yield (e.g. RetryMonitor backoff) -/// aren't forced to pull in the full dmq::os::Thread class -- which also -/// drags in the message queue, watchdog, and stats machinery -- just to -/// sleep. dmq::os::Thread::Sleep() forwards here too, so the FreeRTOS delay -/// call is implemented exactly once. - -#include "FreeRTOS.h" -#include "task.h" -#include "FreeRTOSMutex.h" -#include "FreeRTOSCriticalSection.h" -#include "port/os/common/CurrentThreadStorage.h" -#include - -namespace dmq::os { - - /// @brief Key for RegistryCurrentThread: the calling task's handle, or 0 - /// inside an ISR (detected on ARM Cortex-M; see FreeRTOSCriticalSection.h). - /// @TODO: On a non-ARM FreeRTOS port (RISC-V, Xtensa, ...), extend - /// detail::IsInsideFreeRTOSInterrupt() for that architecture; until then, - /// dmq::ThisThread::GetCurrent() from an ISR returns the interrupted task's - /// IThread instead of nullptr. See docs/PORTING.md, "Current Thread". - inline uintptr_t FreeRTOSCurrentThreadKey() { - if (detail::IsInsideFreeRTOSInterrupt()) - return 0; - return reinterpret_cast(xTaskGetCurrentTaskHandle()); - } - - struct FreeRTOSThisThread : RegistryCurrentThread { - template - static void sleep_for(std::chrono::duration d) { - const auto ms = std::chrono::duration_cast(d); - vTaskDelay(pdMS_TO_TICKS(ms.count())); - } - - static void yield() noexcept { - taskYIELD(); - } - }; - -} // namespace dmq::os - -#endif // FREERTOS_THIS_THREAD_H diff --git a/DelegateMQ/port/os/freertos/FreeRTOSThread.cpp b/DelegateMQ/port/os/freertos/FreeRTOSThread.cpp deleted file mode 100644 index 54dc503..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSThread.cpp +++ /dev/null @@ -1,652 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_FREERTOS is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_FREERTOS) - -#include "DelegateMQ.h" -#include "FreeRTOSThread.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include - -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(x) configASSERT(x) -#endif - -namespace dmq::os { - -using namespace dmq; -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// Thread Constructor -//---------------------------------------------------------------------------- -FreeRTOSThread::FreeRTOSThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - m_queueSize = (maxQueueSize == 0) ? DEFAULT_QUEUE_SIZE : maxQueueSize; -#if defined(_MSC_VER) -#pragma warning(push) -#pragma warning(disable: 6326) -#endif - m_priority = configMAX_PRIORITIES > 2 ? configMAX_PRIORITIES - 2 : tskIDLE_PRIORITY + 1; -#if defined(_MSC_VER) -#pragma warning(pop) -#endif -} - -//---------------------------------------------------------------------------- -// Destructor -//---------------------------------------------------------------------------- -FreeRTOSThread::~FreeRTOSThread() -{ - ExitThread(); - - { - const dmq::LockGuard lock(GetWatchdogLock()); - FreeRTOSThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } - } - - if (m_exitSem) { - vSemaphoreDelete(m_exitSem); - m_exitSem = nullptr; - } - - if (m_startSem) { - vSemaphoreDelete(m_startSem); - m_startSem = nullptr; - } -} - -//---------------------------------------------------------------------------- -// SetStackMem (Static Stack Configuration) -//---------------------------------------------------------------------------- -void FreeRTOSThread::SetStackMem(StackType_t* stackBuffer, uint32_t stackSizeInWords) -{ - if (stackBuffer && stackSizeInWords > 0) { - m_stackBuffer = stackBuffer; - m_stackSize = stackSizeInWords; - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool FreeRTOSThread::CreateThread(std::optional watchdogTimeout) -{ - if (IsThreadCreated()) - return true; - - // Reset from a previous ExitThread(), so the thread can be created again - m_exit.store(false); - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // No watchdog unless one is given below; set before the task exists - m_watchdogTimeout.store(0); - m_discard.store(false); - - // 1. Create Synchronization Semaphore (Critical for cleanup) - if (!m_exitSem) { - m_exitSem = xSemaphoreCreateBinary(); - DMQ_ASSERT_TRUE(m_exitSem != nullptr); - } - - // 2. Create the Queue NOW (Synchronously) - // We must do this BEFORE creating the task so it's ready for immediate use. - if (!m_queue.IsCreated()) { - if (!m_queue.Create(m_queueSize)) { - printf("Error: Thread '%s' failed to create queue.\n", THREAD_NAME.c_str()); - m_startGate.OnCreateFailed(); - return false; - } - } - - m_lastAliveTime.store(static_cast(Timer::GetNow().time_since_epoch().count())); - - if (watchdogTimeout.has_value()) - { - m_watchdogTimeout.store(static_cast(watchdogTimeout.value().count())); - - const dmq::LockGuard lock(GetWatchdogLock()); - - // Add to watchdog registry if not already present - bool found = false; - FreeRTOSThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - - // If the scheduler is running, CreateThread() waits for the start handler. - // Before vTaskStartScheduler() it cannot block; the start handler then runs - // when the scheduler starts, still before any message is processed. - m_startSync = (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED); - if (m_startSync && !m_startSem) { - m_startSem = xSemaphoreCreateBinary(); - DMQ_ASSERT_TRUE(m_startSem != nullptr); - } - - // 3. Create Task - if (m_stackBuffer != nullptr) - { - // --- STATIC ALLOCATION --- - m_thread = xTaskCreateStatic( - (TaskFunction_t)&FreeRTOSThread::Process, - THREAD_NAME.c_str(), - m_stackSize, - this, - m_priority, - m_stackBuffer, - &m_tcb - ); - } - else - { - // --- DYNAMIC ALLOCATION (Heap) --- - // m_stackSize is the DMQ_FREERTOS_STACK_WORDS default here: SetStackMem() - // changes it only together with a static buffer (the branch above). - BaseType_t xReturn = xTaskCreate( - (TaskFunction_t)&FreeRTOSThread::Process, - THREAD_NAME.c_str(), - m_stackSize, - this, - m_priority, - &m_thread); - - if (xReturn != pdPASS) { - printf("Error: Failed to create task '%s'. OOM?\n", THREAD_NAME.c_str()); - m_watchdogTimeout.store(0); // no task to refresh the heartbeat - m_startGate.OnCreateFailed(); - return false; - } - } - - DMQ_ASSERT_TRUE(m_thread != nullptr); - - if (m_startSync) { - // m_thread is now stored: let Run() proceed to the start handler (see Run()), - // then wait for it to complete. - xTaskNotifyGive(m_thread); - xSemaphoreTake(m_startSem, portMAX_DELAY); - } - return true; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void FreeRTOSThread::ExitThread(ExitPolicy policy) -{ - if (m_queue.IsCreated()) { - // Set before m_exit: Run() reads it for every message ahead of the exit message - m_discard.store(policy == ExitPolicy::DISCARD); - m_exit.store(true); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Check self-exit BEFORE attempting to enqueue the exit message. If - // this thread is destroying itself from within its own dispatched - // callback, it is not consuming its own queue right now -- it is - // blocked here, inside ExitThread(). A blocking Send() would - // deadlock forever if the queue happened to be full. No message needs - // to be queued in that case: Run()'s dispatch loop already checks - // m_selfExitPtr immediately after the current callback invoke - // returns, and unwinds without touching 'this' again. - if (xTaskGetCurrentTaskHandle() == m_thread) { - if (m_selfExitPtr) { *m_selfExitPtr = true; m_selfExitPtr = nullptr; } - m_startGate.Leave(); // exited from its start handler: never reaches the gate - } else { - ThreadMsg* msg = new (std::nothrow) ThreadMsg(MSG_EXIT_THREAD); - - if (msg) { - // Block until message is sent. This ensures the thread WILL receive it. - // If the thread is deadlocked, we hang here, which is better than - // hanging at the semaphore after dropping the message. - if (!m_queue.Send(msg, /*highPriority=*/false, portMAX_DELAY)) { - delete msg; - } - } - - if (m_exitSem) { - xSemaphoreTake(m_exitSem, portMAX_DELAY); - } - } - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(0); - - m_queue.DrainAndDelete(); - m_queue.Destroy(); - m_thread = nullptr; - } -} - -//---------------------------------------------------------------------------- -// Getters / Setters -//---------------------------------------------------------------------------- -TaskHandle_t FreeRTOSThread::GetThreadId() { return m_thread; } -TaskHandle_t FreeRTOSThread::GetCurrentThreadId() { return xTaskGetCurrentTaskHandle(); } -bool FreeRTOSThread::IsCurrentThread() -{ - return GetThreadId() == GetCurrentThreadId(); -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t FreeRTOSThread::GetQueueSize() -{ - return m_queue.Size(); -} - -void FreeRTOSThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -void FreeRTOSThread::SetThreadPriority(int priority) { - m_priority = priority; - if (m_thread) { - vTaskPrioritySet(m_thread, static_cast(m_priority)); - } -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool FreeRTOSThread::DispatchDelegate(std::shared_ptr msg) -{ - if (!m_queue.IsCreated()) { - printf("[Thread] Error: Dispatch called but queue is null (%s)\n", THREAD_NAME.c_str()); - return false; - } - - // If using XALLOCATOR explicit operator new required. See xallocator.h. - ThreadMsg* threadMsg = new (std::nothrow) ThreadMsg(MSG_DISPATCH_DELEGATE, msg); - - if (threadMsg == nullptr) { - printf("[Thread] CRITICAL: 'new ThreadMsg' returned NULL! System Heap full? (%s)\n", THREAD_NAME.c_str()); - return false; - } -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // Compute send timeout based on policy. - TickType_t timeout; - if (FULL_POLICY == FullPolicy::TIMEOUT) - timeout = pdMS_TO_TICKS(std::chrono::duration_cast(m_dispatchTimeout).count()); - else - timeout = 0; // DROP and FAULT: non-blocking - - // High priority routes to the HIGH lane (drained before NORMAL), preserving - // FIFO order within each lane -- see FreeRTOSDelegateQueue.h for why this is - // NOT xQueueSendToFront (that would make HIGH messages LIFO, not FIFO). - bool sent = m_queue.Send(threadMsg, msg->GetPriority() == Priority::HIGH, timeout); - - if (!sent) { - if (FULL_POLICY == FullPolicy::FAULT) { - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(sent); - } else if (FULL_POLICY == FullPolicy::TIMEOUT) { - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } else { // DROP - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } - delete threadMsg; - return false; - } - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - size_t currentDepth = GetQueueSize(); - size_t oldDepth = m_queueDepthMaxWindow.load(); - while (currentDepth > oldDepth && !m_queueDepthMaxWindow.compare_exchange_weak(oldDepth, currentDepth)); - - oldDepth = m_queueDepthMaxAll.load(); - while (currentDepth > oldDepth && !m_queueDepthMaxAll.compare_exchange_weak(oldDepth, currentDepth)); -#endif - - return true; -} - -//---------------------------------------------------------------------------- -// Process & Run -//---------------------------------------------------------------------------- -void FreeRTOSThread::Process(void* instance) -{ - FreeRTOSThread* thread = static_cast(instance); - DMQ_ASSERT_TRUE(thread != nullptr); - thread->Run(); - vTaskDelete(NULL); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void FreeRTOSThread::WatchdogCheckAll() -{ - const dmq::LockGuard lock(GetWatchdogLock()); - FreeRTOSThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void FreeRTOSThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = static_cast(Timer::GetNow().time_since_epoch().count()); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void FreeRTOSThread::ThreadCheck() -{ - m_lastAliveTime.store(static_cast(Timer::GetNow().time_since_epoch().count())); -} - -void FreeRTOSThread::Run() -{ - bool selfExit = false; - m_selfExitPtr = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // xTaskCreateStatic() stores m_thread only after this task may already be - // running; wait for CreateThread() so the start handler can use it. - const bool startSync = m_startSync; - if (startSync) - ulTaskNotifyTake(pdTRUE, portMAX_DELAY); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Reset - // before the exit handler runs (and destroyed before exitGuard on a - // self-exit), so the exit handler sees nullptr. - std::optional currentScope; - currentScope.emplace(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - if (startSync) - xSemaphoreGive(m_startSem); - if (exitedInStart) - return; - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - // Before Passed(): no stale watchdog read - m_lastAliveTime.store(static_cast(Timer::GetNow().time_since_epoch().count())); - m_startGate.Passed(); - // ExitThread() while held: run nothing. Cancel each queued message - // (DISCARD) until the exit message. Consuming them also keeps - // ExitThread()'s blocking send of the exit message from waiting on a - // full queue. - if (!opened) - m_discard.store(true); - } - - ThreadMsg* msg = nullptr; - while (!selfExit) - { - m_lastAliveTime.store(static_cast(Timer::GetNow().time_since_epoch().count())); - auto watchdogTimeout = m_watchdogTimeout.load(); - - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever to save power. - TickType_t waitTicks = portMAX_DELAY; - if (watchdogTimeout > 0) - { - waitTicks = pdMS_TO_TICKS(watchdogTimeout / dmq::WATCHDOG_HEARTBEAT_DIVISOR); - if (waitTicks == 0) waitTicks = 1; - } - if (idle.Enabled()) - { - auto ms = std::chrono::ceil(idle.WaitTime(dmq::Duration(-1))).count(); - TickType_t idleTicks = pdMS_TO_TICKS(ms); - if (ms > 0 && idleTicks == 0) idleTicks = 1; - if (idleTicks < waitTicks) waitTicks = idleTicks; - } - - msg = m_queue.Receive(waitTicks); - if (msg == nullptr) - { - // Exit requested but no exit message arrived (e.g. it could not be allocated) - if (m_exit.load()) - break; - - // Timed out with the queue empty: run the idle handler if it is due - if (idle.IsDue()) - { - idle.Run(); - // The idle handler exited this thread (and may have deleted it): leave - // without touching 'this', as the message path does - if (selfExit) - return; - } - } - else - { - - int msgId = msg->GetId(); - if (msgId == MSG_DISPATCH_DELEGATE && m_discard.load()) - { - // ExitPolicy::DISCARD: skip messages queued ahead of the exit message - CancelThreadMsg(*msg); - } - else if (msgId == MSG_DISPATCH_DELEGATE) - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - int64_t latNs = std::chrono::duration_cast(latency).count(); - - { - const dmq::LockGuard lock(m_statsLock); - m_latencyTotalWindow += latNs; - m_latencyCountWindow += 1; - if (latNs > m_latencyMaxWindow) m_latencyMaxWindow = latNs; - if (latNs > m_latencyMaxAll) m_latencyMaxAll = latNs; - m_dispatchCountAll += 1; - } -#endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - bool success = false; - try { - success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - printf("[Thread:%s] Unhandled exception in delegate callback: %s\n", THREAD_NAME.c_str(), e.what()); - DMQ_ASSERT(); - } - catch (...) { - printf("[Thread:%s] Unhandled unknown exception in delegate callback.\n", THREAD_NAME.c_str()); - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - delete msg; - return; - } - -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - int64_t invokeNs = std::chrono::duration_cast(invokeTime).count(); - { - const dmq::LockGuard lock(m_statsLock); - m_invokeTotalWindow += invokeNs; - m_invokeCountWindow += 1; - if (invokeNs > m_invokeMaxWindow) m_invokeMaxWindow = invokeNs; - if (invokeNs > m_invokeMaxAll) m_invokeMaxAll = invokeNs; - } -#endif - } - - delete msg; - - if (msgId == MSG_EXIT_THREAD) { - break; - } - - // Any message restarts the idle countdown - idle.Restart(); - } - } - - // Run the exit handler before signalling ExitThread(), so it returns only after it - currentScope.reset(); - exitGuard.Fire(); - - // Clear before signalling: once ExitThread() returns, 'this' may be destroyed - m_selfExitPtr = nullptr; - if (m_exitSem) { - xSemaphoreGive(m_exitSem); - } -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -FreeRTOSThread::ThreadStats FreeRTOSThread::SnapshotStats() -{ - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = GetQueueSize(); - stats.queue_depth_max_window = m_queueDepthMaxWindow.exchange(0); - stats.queue_depth_max_all = m_queueDepthMaxAll.load(); - stats.queue_size_limit = m_queueSize; - - { - const dmq::LockGuard lock(m_statsLock); - uint32_t count = m_latencyCountWindow; - m_latencyCountWindow = 0; - int64_t total = m_latencyTotalWindow; - m_latencyTotalWindow = 0; - - if (count > 0) { - stats.latency_avg_ms = (float)total / (static_cast(count) * 1000000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)m_latencyMaxWindow / 1000000.0f; - m_latencyMaxWindow = 0; - stats.latency_max_all_ms = (float)m_latencyMaxAll / 1000000.0f; - - uint32_t iCount = m_invokeCountWindow; - m_invokeCountWindow = 0; - int64_t iTotal = m_invokeTotalWindow; - m_invokeTotalWindow = 0; - - if (iCount > 0) { - stats.invoke_avg_ms = (float)iTotal / (static_cast(iCount) * 1000000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)m_invokeMaxWindow / 1000000.0f; - m_invokeMaxWindow = 0; - stats.invoke_max_all_ms = (float)m_invokeMaxAll / 1000000.0f; - - stats.dispatch_count = m_dispatchCountAll; - } - - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_FREERTOS diff --git a/DelegateMQ/port/os/freertos/FreeRTOSThread.h b/DelegateMQ/port/os/freertos/FreeRTOSThread.h deleted file mode 100644 index fa2df68..0000000 --- a/DelegateMQ/port/os/freertos/FreeRTOSThread.h +++ /dev/null @@ -1,329 +0,0 @@ -#ifndef _THREAD_FREERTOS_H -#define _THREAD_FREERTOS_H - -/// @file FreeRTOSThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief FreeRTOS implementation of the DelegateMQ IThread interface. -/// -/// @details -/// This class provides a concrete implementation of the `IThread` interface using -/// FreeRTOS primitives (Tasks and Queues). It enables DelegateMQ to dispatch -/// asynchronous delegates to a dedicated FreeRTOS task. -/// -/// @note This implementation is a basic port. For reference, the stdlib and win32 -/// implementations provide additional features: -/// 1. Synchronized Startup: CreateThread() blocks until the worker thread is ready. -/// -/// **Key Features:** -/// * **Task Integration:** Wraps a FreeRTOS `xTaskCreate` call to establish a -/// dedicated worker loop. -/// * **FullPolicy Support:** Configurable back-pressure (DROP or TIMEOUT) when the -/// message queue is full. -/// * **Priority Support:** Normal and High priorities, as two FIFO queue lanes drained -/// HIGH first, so same-priority messages keep dispatch order (see -/// `FreeRTOSDelegateQueue` for why one queue + `xQueueSendToFront()` is wrong). -/// * **Queue-Based Dispatch:** Uses `FreeRTOSDelegateQueue` (a thin RAII wrapper -/// around a FreeRTOS `QueueHandle_t`) to receive and process incoming delegate -/// messages in a thread-safe manner. -/// * **Thread Identification:** Implements `GetThreadId()` using `TaskHandle_t` -/// to ensure correct thread context checks (used by `AsyncInvoke` optimizations). -/// * **Graceful Shutdown:** Provides mechanisms (`ExitThread`) to cleanup resources, -/// though typical embedded tasks often run forever. -/// * **Watchdog Integration:** Optional heartbeat mechanism detects stalled or deadlocked -/// threads. Enable by passing a timeout to CreateThread(). Requires -/// Thread::WatchdogCheckAll() to be called periodically from a context that can preempt -/// watched threads -- the highest-priority task in the system, not an ISR. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "extras/util/Timer.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include "FreeRTOSDelegateQueue.h" -#include "FreeRTOS.h" -#include "task.h" -#include "queue.h" -#include "semphr.h" -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the FreeRTOS task queue is full (see dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port). -/// DROP/FAULT map to xQueueSend() with timeout 0; TIMEOUT to a finite timeout. -/// FAULT is the default. For embedded targets where the caller may be an ISR or -/// high-priority task, consider DROP to avoid blocking at an unsafe context. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -class FreeRTOSThread : public dmq::IThread -{ - XALLOCATOR -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Default queue size if 0 is passed - static const size_t DEFAULT_QUEUE_SIZE = dmq::DEFAULT_QUEUE_SIZE; - - /// Constructor - /// @param threadName Name for the FreeRTOS task - /// @param maxQueueSize Max number of messages in queue (0 = Default dmq::DEFAULT_QUEUE_SIZE) - /// @param fullPolicy Action when queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - FreeRTOSThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - FreeRTOSThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : FreeRTOSThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - /// Destructor - ~FreeRTOSThread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Returns true if the thread is created - bool IsThreadCreated() const { return m_thread != nullptr; } - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - /// Get the ID of this thread instance - TaskHandle_t GetThreadId(); - - /// Get the ID of the currently executing thread - static TaskHandle_t GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Get thread name - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get current queue size - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - /// Set the FreeRTOS Task Priority. - /// Can be called before or after CreateThread(). - /// @param priority FreeRTOS priority level (0 to configMAX_PRIORITIES-1) - void SetThreadPriority(int priority); - - /// Optional: Provide a static buffer for the task stack to avoid Heap usage. - /// @param stackBuffer Pointer to a buffer of type StackType_t. - /// @param stackSizeInWords Size of the buffer in WORDS (not bytes). - void SetStackMem(StackType_t* stackBuffer, uint32_t stackSizeInWords); - - // IThread Interface Implementation - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!IsThreadCreated()); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!IsThreadCreated()); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(!IsThreadCreated()); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning FreeRTOSThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!IsThreadCreated()); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!IsThreadCreated()); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!IsThreadCreated()); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!IsThreadCreated()); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Check all registered threads for watchdog expiration. - /// @details Call this from the highest-priority task in the system. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - FreeRTOSThread(const FreeRTOSThread&) = delete; - FreeRTOSThread& operator=(const FreeRTOSThread&) = delete; - - /// Entry point for the thread - static void Process(void* instance); - - // Run loop called by Process - void Run(); - - /// Check watchdog is expired for this instance. - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static FreeRTOSThread*& GetWatchdogHead() - { - static FreeRTOSThread* head = nullptr; - return head; - } - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock() - { - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; - } - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - const FullPolicy FULL_POLICY; - const dmq::Duration m_dispatchTimeout; - size_t m_queueSize; - int m_priority; - - TaskHandle_t m_thread = nullptr; - FreeRTOSDelegateQueue m_queue; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - SemaphoreHandle_t m_exitSem = nullptr; // Synchronization for safe destruction - SemaphoreHandle_t m_startSem = nullptr; // Given by Run() once the start handler has run - bool m_startSync = false; // CreateThread() waits for the start handler (scheduler running) - std::atomic m_exit = false; - std::atomic m_discard = false; // ExitPolicy::DISCARD: cancel queued messages instead of invoking - bool* m_selfExitPtr = nullptr; - - // Static allocation support - StackType_t* m_stackBuffer = nullptr; - uint32_t m_stackSize = dmq::FREERTOS_STACK_WORDS; // Default size (words), see DMQ_FREERTOS_STACK_WORDS - StaticTask_t m_tcb; // TCB storage for static creation - - // Watchdog related members - std::atomic m_lastAliveTime{0}; - std::atomic m_watchdogTimeout{0}; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - FreeRTOSThread* m_watchdogNext = nullptr; - -#if defined(DMQ_DATABUS_TOOLS) - // Monitoring statistics members - std::atomic m_queueDepthMaxWindow{0}; - std::atomic m_queueDepthMaxAll{0}; - - // Use a mutex to protect 64-bit stats on 32-bit platforms without libatomic - dmq::RecursiveMutex m_statsLock; - int64_t m_latencyTotalWindow{0}; - uint32_t m_latencyCountWindow{0}; - int64_t m_latencyMaxWindow{0}; - int64_t m_latencyMaxAll{0}; - - int64_t m_invokeTotalWindow{0}; - uint32_t m_invokeCountWindow{0}; - int64_t m_invokeMaxWindow{0}; - int64_t m_invokeMaxAll{0}; - - uint64_t m_dispatchCountAll{0}; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the FreeRTOS port. -using Thread = FreeRTOSThread; - -} // namespace dmq::os - - -#endif diff --git a/DelegateMQ/port/os/nuttx/NuttXClock.h b/DelegateMQ/port/os/nuttx/NuttXClock.h deleted file mode 100644 index 08c866c..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXClock.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef NUTTX_CLOCK_H -#define NUTTX_CLOCK_H - -/// @file NuttXClock.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief dmq::Clock backing for NuttX, using the POSIX clock_gettime() -/// call NuttX provides directly (CLOCK_MONOTONIC) rather than a kernel- -/// specific tick counter like k_uptime_get()/tx_time_get(). NuttX's POSIX -/// layer already exposes nanosecond resolution, so no k_ticks-to-duration -/// conversion is needed here. - -#include -#include -#include - -namespace dmq::os { - struct NuttXClock { - using rep = int64_t; - using period = std::nano; - using duration = std::chrono::duration; - using time_point = std::chrono::time_point; - static const bool is_steady = true; - - static time_point now() noexcept { - struct timespec ts; - clock_gettime(CLOCK_MONOTONIC, &ts); - rep ns = static_cast(ts.tv_sec) * 1000000000LL + static_cast(ts.tv_nsec); - return time_point(duration(ns)); - } - }; -} // namespace dmq::os - -#endif // NUTTX_CLOCK_H diff --git a/DelegateMQ/port/os/nuttx/NuttXCriticalSection.h b/DelegateMQ/port/os/nuttx/NuttXCriticalSection.h deleted file mode 100644 index c0c0d4d..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXCriticalSection.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef NUTTX_CRITICAL_SECTION_H -#define NUTTX_CRITICAL_SECTION_H - -/// @file NuttXCriticalSection.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ISR-safe critical section for NuttX. -/// -/// @details -/// pthread_mutex_lock() is a priority-inheritance-aware, thread-only -/// primitive on NuttX, like every other RTOS mutex in this library -- it -/// cannot be used from ISR context. This type uses up_irq_save()/ -/// up_irq_restore(flags) instead: NuttX's own architecture-portable -/// interrupt-masking primitive (declared in ), implemented on -/// every supported CPU architecture and used throughout NuttX's own kernel -/// for exactly this purpose -- protecting something tiny that both ISR and -/// thread code touch. This is the same save/disable/restore technique -/// ThreadXCriticalSection and ZephyrCriticalSection use, just NuttX's own -/// primitive instead of a vendor CMSIS-Core intrinsic. -/// -/// @warning up_irq_save()/up_irq_restore() are only reachable from -/// application code in a NuttX FLAT build (the default for most boards, -/// where apps and the kernel share one address space). In a PROTECTED or -/// KERNEL build, application code runs in unprivileged userspace with no -/// access to this call, and dmq::util::Timer::ProcessTimers() must instead -/// be driven from kernel-side code (e.g. a NuttX interrupt handler or a -/// kernel-mode work queue) on those configurations. -/// -/// *** NARROW PURPOSE -- DO NOT USE THIS AS A GENERAL-PURPOSE LOCK *** -/// Holding this masks ALL maskable interrupts on the CPU for as long as it -/// is held. Only use it to protect something genuinely tiny and bounded -/// that may be touched from ISR context. Do NOT use it in place of -/// dmq::Mutex / dmq::RecursiveMutex for ordinary thread-to-thread -/// synchronization (e.g. DataBus internals, a Thread's message queue) -- -/// anything that can block, take a while, or run for an unbounded time -/// must not run with interrupts globally masked; that is a real-time -/// correctness bug on hardware, not just a style issue. -/// -/// *** NOT RE-LOCKABLE ON THE SAME INSTANCE *** -/// Unlike dmq::RecursiveMutex, calling lock() twice on the SAME instance -/// without an intervening unlock() is incorrect: the second lock() call -/// overwrites the single saved irqstate_t with the (already masked) inner -/// state, so the outer unlock() restores the wrong state. There is no -/// "recursive" variant of this type -- it has no ownership concept to make -/// recursion meaningful, and Timer's own usage never nests. Locking two -/// DIFFERENT instances in proper LIFO lock/unlock order is fine: each -/// instance saves and restores its own state independently. - -#include - -namespace dmq::os { - - // ========================================================================= - // NuttXCriticalSection - // See the file-level comment above before using this type anywhere new. - // ========================================================================= - class NuttXCriticalSection { - public: - NuttXCriticalSection() = default; - - void lock() { - m_flags = up_irq_save(); - } - - void unlock() { - up_irq_restore(m_flags); - } - - // No try_lock(): interrupt masking cannot fail to "acquire", so a - // try_lock() here would always trivially succeed and isn't meaningful. - - NuttXCriticalSection(const NuttXCriticalSection&) = delete; - NuttXCriticalSection& operator=(const NuttXCriticalSection&) = delete; - - private: - irqstate_t m_flags = 0; - }; - -} // namespace dmq::os - -#endif // NUTTX_CRITICAL_SECTION_H diff --git a/DelegateMQ/port/os/nuttx/NuttXDelegateQueue.h b/DelegateMQ/port/os/nuttx/NuttXDelegateQueue.h deleted file mode 100644 index a44d3b1..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXDelegateQueue.h +++ /dev/null @@ -1,186 +0,0 @@ -#ifndef NUTTX_DELEGATE_QUEUE_H -#define NUTTX_DELEGATE_QUEUE_H - -/// @file NuttXDelegateQueue.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Thin RAII wrapper around a POSIX mqueue used by dmq::os::Thread -/// to carry pending ThreadMsg pointers, with priority support. -/// -/// @details -/// Unlike Zephyr's k_msgq (strict FIFO, no native priority -- see -/// ZephyrDelegateQueue.h's two-k_msgq workaround), POSIX mq_send() takes a -/// msg_prio argument directly: a higher-priority message is dequeued ahead -/// of lower-priority ones already queued, FIFO within the same priority. -/// A single mqd_t therefore handles both dmq::Priority lanes, the same way -/// CmsisRtos2DelegateQueue.h uses osMessageQueuePut's native msg_prio -- -/// no second queue needed here. This class owns no policy decisions of its -/// own (FullPolicy, timeout computation, and stats stay in Thread.cpp) -- -/// it only knows how to move ThreadMsg* pointers through a named POSIX -/// message queue. -/// -/// Each instance opens its own uniquely-named queue (process id + a -/// monotonic counter) since POSIX message queues live in a global, -/// filesystem-like namespace -- two dmq::os::Thread instances must never -/// collide on the same name. Destroy() closes and unlinks it. - -#include "port/os/common/ThreadMsg.h" -#include "delegate/DelegateOpt.h" -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::os { - -class NuttXDelegateQueue -{ -public: - /// Sentinel meaning "block forever" for Send()/Receive()'s timeout - /// parameter -- dmq::Duration has no dedicated "infinite" value of its - /// own, so this mirrors the K_FOREVER/osWaitForever sentinel every - /// other dmq::os::Thread port already needs. - static constexpr dmq::Duration WAIT_FOREVER = dmq::Duration::max(); - - NuttXDelegateQueue() = default; - ~NuttXDelegateQueue() { Destroy(); } - - NuttXDelegateQueue(const NuttXDelegateQueue&) = delete; - NuttXDelegateQueue& operator=(const NuttXDelegateQueue&) = delete; - - /// Create the underlying queue with room for 'capacity' pointers. - /// @return true on success, false if mq_open() failed. - bool Create(size_t capacity) - { - if (m_mqd != INVALID_MQD) - return true; - - static std::atomic s_counter{0}; - std::snprintf(m_name, sizeof(m_name), "/dmq_q_%u_%u", - static_cast(getpid()), s_counter.fetch_add(1)); - - struct mq_attr attr; - std::memset(&attr, 0, sizeof(attr)); - attr.mq_maxmsg = static_cast(capacity); - attr.mq_msgsize = static_cast(sizeof(ThreadMsg*)); - - m_mqd = mq_open(m_name, O_CREAT | O_RDWR, 0600, &attr); - if (m_mqd != INVALID_MQD) { - mq_unlink(m_name); - } - return m_mqd != INVALID_MQD; - } - - bool IsCreated() const { return m_mqd != INVALID_MQD; } - - /// Send a message pointer. 'highPriority' is passed as mq_send()'s - /// native msg_prio argument -- a higher-priority message is delivered - /// ahead of lower-priority ones already queued, no second queue needed. - /// 'timeout' is Duration::zero() for non-blocking, WAIT_FOREVER to block - /// forever, or a finite duration for a bounded wait. - /// @return true if the message was enqueued. - bool Send(ThreadMsg* msg, bool highPriority, dmq::Duration timeout) - { - unsigned prio = highPriority ? 1u : 0u; - const char* data = reinterpret_cast(&msg); - - if (timeout == WAIT_FOREVER) - return mq_send(m_mqd, data, sizeof(msg), prio) == 0; - - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - AddDuration(ts, timeout); - return mq_timedsend(m_mqd, data, sizeof(msg), prio, &ts) == 0; - } - - /// Receive a message pointer, blocking up to 'timeout'. The - /// high-priority lane is always delivered first since it is the - /// kernel's own mqueue ordering, not something this wrapper implements. - /// @return the message, or nullptr on timeout. - ThreadMsg* Receive(dmq::Duration timeout) - { - char buf[sizeof(ThreadMsg*)]; - unsigned prio = 0; - ssize_t n; - - if (timeout == WAIT_FOREVER) { - n = mq_receive(m_mqd, buf, sizeof(buf), &prio); - } else { - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - AddDuration(ts, timeout); - n = mq_timedreceive(m_mqd, buf, sizeof(buf), &prio, &ts); - } - - if (n == static_cast(sizeof(ThreadMsg*))) { - ThreadMsg* msg = nullptr; - std::memcpy(&msg, buf, sizeof(msg)); - return msg; - } - return nullptr; - } - - /// Current number of messages waiting in the queue. - size_t Size() const - { - if (m_mqd == INVALID_MQD) - return 0; - struct mq_attr attr; - if (mq_getattr(m_mqd, &attr) == 0) - return static_cast(attr.mq_curmsgs); - return 0; - } - - /// Remove and delete every pending message without blocking. Used during - /// shutdown once the owning thread has stopped consuming the queue. - /// Each message is canceled first (CancelThreadMsg()), releasing a sender - /// blocked waiting on it. - void DrainAndDelete() - { - while (true) { - ThreadMsg* msg = Receive(dmq::Duration::zero()); - if (!msg) - break; - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - } - - void Destroy() - { - if (m_mqd != INVALID_MQD) { - mq_close(m_mqd); - mq_unlink(m_name); - m_mqd = INVALID_MQD; - } - } - -private: - static constexpr mqd_t INVALID_MQD = static_cast(-1); - - /// Add 'timeout' (clamped to zero for a non-positive/immediate wait) to - /// 'ts' in place, carrying seconds/nanoseconds correctly. - static void AddDuration(struct timespec& ts, dmq::Duration timeout) - { - if (timeout < dmq::Duration::zero()) - timeout = dmq::Duration::zero(); - auto ns = std::chrono::duration_cast(timeout).count(); - ts.tv_sec += static_cast(ns / 1000000000LL); - ts.tv_nsec += static_cast(ns % 1000000000LL); - if (ts.tv_nsec >= 1000000000L) { - ts.tv_nsec -= 1000000000L; - ts.tv_sec += 1; - } - } - - mqd_t m_mqd = INVALID_MQD; - char m_name[32] = {0}; -}; - -} // namespace dmq::os - -#endif // NUTTX_DELEGATE_QUEUE_H diff --git a/DelegateMQ/port/os/nuttx/NuttXMutex.h b/DelegateMQ/port/os/nuttx/NuttXMutex.h deleted file mode 100644 index 48152ca..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXMutex.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef NUTTX_MUTEX_H -#define NUTTX_MUTEX_H - -/// @file NuttXMutex.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief dmq::Mutex / dmq::RecursiveMutex backing for NuttX, using its -/// native POSIX pthread_mutex_t directly (NuttX implements the real POSIX -/// threading API, unlike FreeRTOS/ThreadX/Zephyr/CMSIS-RTOS2, which each -/// need a bespoke kernel-object wrapper here). - -#include - -namespace dmq::os { - - // ========================================================================= - // NuttXMutex (Non-Recursive) - // ========================================================================= - class NuttXMutex { - public: - NuttXMutex() { - pthread_mutex_init(&m_mutex, nullptr); - } - - ~NuttXMutex() { - pthread_mutex_destroy(&m_mutex); - } - - void lock() { - pthread_mutex_lock(&m_mutex); - } - - // REQUIRED for std::unique_lock compatibility - bool try_lock() { - return pthread_mutex_trylock(&m_mutex) == 0; - } - - void unlock() { - pthread_mutex_unlock(&m_mutex); - } - - NuttXMutex(const NuttXMutex&) = delete; - NuttXMutex& operator=(const NuttXMutex&) = delete; - - private: - pthread_mutex_t m_mutex; - }; - - // ========================================================================= - // NuttXRecursiveMutex (Recursive) - // ========================================================================= - class NuttXRecursiveMutex { - public: - NuttXRecursiveMutex() { - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - pthread_mutex_init(&m_mutex, &attr); - pthread_mutexattr_destroy(&attr); - } - - ~NuttXRecursiveMutex() { - pthread_mutex_destroy(&m_mutex); - } - - void lock() { - pthread_mutex_lock(&m_mutex); - } - - bool try_lock() { - return pthread_mutex_trylock(&m_mutex) == 0; - } - - void unlock() { - pthread_mutex_unlock(&m_mutex); - } - - NuttXRecursiveMutex(const NuttXRecursiveMutex&) = delete; - NuttXRecursiveMutex& operator=(const NuttXRecursiveMutex&) = delete; - - private: - pthread_mutex_t m_mutex; - }; - -} // namespace dmq::os - -#endif // NUTTX_MUTEX_H diff --git a/DelegateMQ/port/os/nuttx/NuttXSemaphore.h b/DelegateMQ/port/os/nuttx/NuttXSemaphore.h deleted file mode 100644 index 1d3e560..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXSemaphore.h +++ /dev/null @@ -1,102 +0,0 @@ -#ifndef NUTTX_SEMAPHORE_H -#define NUTTX_SEMAPHORE_H - -/// @file NuttXSemaphore.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief dmq::Semaphore backing for NuttX, using its native POSIX sem_t -/// directly instead of the generic dmq::ConditionVariable + dmq::Mutex -/// implementation in delegate/Semaphore.h. -/// -/// @details -/// NuttX has no dmq::ConditionVariable port (no DMQ_HAS_CV) -- not because -/// it lacks pthread_cond_t (it has a real one), but because a native -/// sem_t is a more direct fit for what dmq::Semaphore actually needs, the -/// same reasoning ZephyrSemaphore.h and CmsisRtos2Semaphore.h give for -/// their own RTOSes: no need to build a semaphore out of a mutex + -/// condition variable when the platform already has a real one. DelegateOpt.h -/// resolves dmq::Semaphore to this type on NuttX; see the "Semaphore" -/// comment next to DMQ_THREAD_NUTTX's `using Semaphore = ...;` there. -/// -/// @note This header is included from DelegateOpt.h's early port-include -/// block, before "namespace dmq { ... }" opens and dmq::Duration is defined -/// inside it (including it any later would nest as dmq::dmq::os instead of -/// dmq::os) -- so, like ZephyrSemaphore.h and CmsisRtos2Semaphore.h, Wait() -/// is templated on the chrono duration type instead of depending on -/// dmq::Duration directly. A dmq::Duration argument still deduces through -/// it seamlessly at the call site, since dmq::Duration is itself a -/// std::chrono::duration specialization. -/// -/// @note sem_timedwait() takes an ABSOLUTE CLOCK_REALTIME deadline, not a -/// relative duration -- this computes that deadline from clock_gettime() -/// plus the caller's relative timeout, the standard POSIX idiom. - -#include -#include -#include - -namespace dmq::os { - - // ========================================================================= - // NuttXSemaphore - // Binary semaphore (max count 1), matching the semantics of the generic - // dmq::Semaphore this replaces: Signal() when already signaled is a - // no-op (not a counting semaphore), and Wait() consumes exactly one - // pending signal. - // ========================================================================= - class NuttXSemaphore { - public: - NuttXSemaphore() { - sem_init(&m_sem, 0, 0); - } - - ~NuttXSemaphore() { - sem_destroy(&m_sem); - } - - /// Called to wait on a semaphore to be signaled. - /// @param[in] timeout - semaphore timeout - /// @return Return true if semaphore signaled, false if timeout occurred. - template - bool Wait(const std::chrono::duration& timeout) { - using DurationT = std::chrono::duration; - if (timeout == DurationT::max()) { - return sem_wait(&m_sem) == 0; - } - - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - auto ns = std::chrono::duration_cast(timeout).count(); - ts.tv_sec += static_cast(ns / 1000000000LL); - ts.tv_nsec += static_cast(ns % 1000000000LL); - if (ts.tv_nsec >= 1000000000L) { - ts.tv_nsec -= 1000000000L; - ts.tv_sec += 1; - } - return sem_timedwait(&m_sem, &ts) == 0; - } - - /// Called to signal a semaphore. - void Signal() { - int val = 0; - if (sem_getvalue(&m_sem, &val) == 0) { - if (val <= 0) { - sem_post(&m_sem); - } - } else { - // Fallback if sem_getvalue fails - sem_post(&m_sem); - } - } - - NuttXSemaphore(const NuttXSemaphore&) = delete; - NuttXSemaphore& operator=(const NuttXSemaphore&) = delete; - - private: - sem_t m_sem; - }; - -} // namespace dmq::os - -#endif // NUTTX_SEMAPHORE_H diff --git a/DelegateMQ/port/os/nuttx/NuttXThisThread.h b/DelegateMQ/port/os/nuttx/NuttXThisThread.h deleted file mode 100644 index 7d2c54e..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXThisThread.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef NUTTX_THIS_THREAD_H -#define NUTTX_THIS_THREAD_H - -/// @file NuttXThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Portable sleep_for()/yield() for the calling thread, NuttX backend. -/// -/// @details -/// This is dmq::ThisThread for this port (see DelegateOpt.h). GetCurrent() -/// uses RegistryCurrentThread, keyed by the calling thread's id. Exists so -/// library internals that need to delay or yield (e.g. RetryMonitor backoff) -/// aren't forced to pull in the full dmq::os::Thread class -- which also -/// drags in the message queue, watchdog, and stats machinery -- just to -/// sleep. dmq::os::Thread::Sleep() forwards here too, so the NuttX delay -/// call is implemented exactly once. - -#include -#include -#include "NuttXMutex.h" -#include -#include -#include "port/os/common/CurrentThreadStorage.h" -#include - -namespace dmq::os { - - /// @brief Key for RegistryCurrentThread: the calling thread's id plus one (pid 0 - /// is the idle task, and 0 means "none"), or 0 inside an interrupt handler. - inline uintptr_t NuttXCurrentThreadKey() { - if (up_interrupt_context()) - return 0; - return static_cast(pthread_self()) + 1; - } - - struct NuttXThisThread : RegistryCurrentThread { - template - static void sleep_for(std::chrono::duration d) { - const auto ms = std::chrono::duration_cast(d); - struct timespec ts; - ts.tv_sec = static_cast(ms.count() / 1000); - ts.tv_nsec = static_cast((ms.count() % 1000) * 1000000L); - nanosleep(&ts, nullptr); - } - - static void yield() noexcept { - sched_yield(); - } - }; - -} // namespace dmq::os - -#endif // NUTTX_THIS_THREAD_H diff --git a/DelegateMQ/port/os/nuttx/NuttXThread.cpp b/DelegateMQ/port/os/nuttx/NuttXThread.cpp deleted file mode 100644 index da28bb0..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXThread.cpp +++ /dev/null @@ -1,664 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_NUTTX is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_NUTTX) - -#include "DelegateMQ.h" -#include "NuttXThread.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include -#include // for memset -#include - -// Define DMQ_ASSERT_TRUE if not already defined -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(x) assert(x) -#endif - -namespace dmq::os { - -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// Thread Constructor -//---------------------------------------------------------------------------- -NuttXThread::NuttXThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , m_queueSize((maxQueueSize == 0) ? DEFAULT_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - m_priority = dmq::NUTTX_THREAD_PRIORITY; // Default SCHED_FIFO priority (typically 1-255), DMQ_NUTTX_THREAD_PRIORITY - - sem_init(&m_exitSem, 0, 0); - sem_init(&m_goSem, 0, 0); - sem_init(&m_startSem, 0, 0); - -#if defined(DMQ_DATABUS_TOOLS) - pthread_mutex_init(&m_statMutex, nullptr); -#endif -} - -//---------------------------------------------------------------------------- -// Thread Destructor -//---------------------------------------------------------------------------- -NuttXThread::~NuttXThread() -{ - ExitThread(); - - sem_destroy(&m_exitSem); - sem_destroy(&m_goSem); - sem_destroy(&m_startSem); - -#if defined(DMQ_DATABUS_TOOLS) - pthread_mutex_destroy(&m_statMutex); -#endif - - const dmq::LockGuard lock(GetWatchdogLock()); - NuttXThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool NuttXThread::CreateThread(std::optional watchdogTimeout) -{ - if (!m_created.load()) - { - // Reset from a previous ExitThread(), so the thread can be created again - m_exit.store(false); - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - m_discard.store(false); - - // 1. Create the message queue - DMQ_ASSERT_TRUE(m_queue.Create(m_queueSize)); - - // 2. Create the pthread - pthread_attr_t attr; - pthread_attr_init(&attr); - pthread_attr_setstacksize(&attr, STACK_SIZE); - - struct sched_param sp; - sp.sched_priority = m_priority; - pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); - pthread_attr_setschedpolicy(&attr, SCHED_FIFO); - pthread_attr_setschedparam(&attr, &sp); - - int rc = pthread_create(&m_thread, &attr, NuttXThread::Process, this); - pthread_attr_destroy(&attr); - DMQ_ASSERT_TRUE(rc == 0); - -#if defined(PTHREAD_NAME_MAX) || defined(CONFIG_TASK_NAME_SIZE) - // NuttX supports naming a pthread for debugging (non-portable POSIX - // extension); harmless no-op if unsupported on a given configuration. - pthread_setname_np(m_thread, THREAD_NAME.c_str()); -#endif - - // pthread_create() stores m_thread only after the (SCHED_FIFO, possibly - // higher priority) thread may already be running: release Run() to the - // start handler now, then wait for it to complete. - sem_post(&m_goSem); - sem_wait(&m_startSem); - - m_created.store(true); - m_lastAliveTime.store(Timer::GetNow()); - - if (watchdogTimeout.has_value()) - { - - const dmq::LockGuard lock(GetWatchdogLock()); - - // Add to watchdog registry if not already present - bool found = false; - NuttXThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void NuttXThread::ExitThread(ExitPolicy policy) -{ - if (m_created.load()) - { - // Set before m_exit: Run() reads it for every message ahead of the exit message - m_discard.store(policy == ExitPolicy::DISCARD); - m_exit.store(true); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Check self-exit BEFORE attempting to enqueue the exit message. If - // this thread is destroying itself from within its own dispatched - // callback, it is not consuming its own queue right now -- it is - // blocked here, inside ExitThread(). A blocking mq_send() would - // deadlock forever if the queue happened to be full. No message - // needs to be queued in that case: Run()'s dispatch loop already - // checks m_selfExitPtr immediately after the current callback - // invoke returns, and unwinds without touching 'this' again. - // - // Crucially, a self-exiting thread must NOT touch m_queue here: it - // is still physically executing on its own stack (unwinding back - // through Invoke()/Run()), and it cannot pthread_join() itself. Set - // the flag and return immediately; the actual cleanup (queue - // drain/destroy, pthread_join) is deferred to a later ExitThread() - // call made from a different thread context -- typically - // ~NuttXThread() -- once m_selfExited tells that call it's safe to - // skip the message/semaphore handshake below (the thread already - // returned/is returning on its own) and go straight to the join. - if (pthread_equal(pthread_self(), m_thread)) { - m_selfExited.store(true); - if (m_selfExitPtr) { *m_selfExitPtr = true; m_selfExitPtr = nullptr; } - m_startGate.Leave(); // exited from its start handler: never reaches the gate - // Self-exit: this thread runs no more messages, and the object may be - // destroyed once this handler returns. Stop watchdog checks now. - m_watchdogTimeout.store(dmq::Duration(0)); - return; - } - - if (!m_selfExited.load()) - { - // Send exit message - ThreadMsg* msg = new (std::nothrow) ThreadMsg(MSG_EXIT_THREAD); - if (msg) - { - // Wait forever to ensure message is sent - if (!m_queue.Send(msg, /*highPriority=*/false, NuttXDelegateQueue::WAIT_FOREVER)) - { - delete msg; - } - } - - // Wait for thread to actually finish before joining. - sem_wait(&m_exitSem); - } - - // pthread_join() blocks until the kernel has fully torn the thread - // down, the race-free way to wait for that -- sem_wait() above only - // proves Run() is about to return, not that the kernel has finished - // unlinking it from scheduler structures. It is also the right call - // in the deferred self-exit case: the thread has already returned or - // is in the process of returning on its own, so this either returns - // immediately or waits only as long as that natural teardown takes. - pthread_join(m_thread, nullptr); - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - m_queue.DrainAndDelete(); - m_queue.Destroy(); - - // Reset flag to mark as exited. This prevents a double-entry deadlock: - // ~NuttXThread() calls ExitThread() unconditionally, so if ExitThread() - // was already called explicitly, the second call must be a no-op. - m_created.store(false); - - // Allow this object to be reused for a fresh CreateThread()/Run() cycle. - m_selfExited.store(false); - } -} - -//---------------------------------------------------------------------------- -// SetThreadPriority -//---------------------------------------------------------------------------- -void NuttXThread::SetThreadPriority(int priority) -{ - m_priority = priority; - if (m_created.load()) { - struct sched_param sp; - sp.sched_priority = m_priority; - pthread_setschedparam(m_thread, SCHED_FIFO, &sp); - } -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -pthread_t NuttXThread::GetThreadId() -{ - return m_thread; -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -pthread_t NuttXThread::GetCurrentThreadId() -{ - return pthread_self(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool NuttXThread::IsCurrentThread() -{ - if (!m_created.load()) - return false; - return pthread_equal(GetThreadId(), GetCurrentThreadId()) != 0; -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t NuttXThread::GetQueueSize() -{ - return m_queue.Size(); -} - -void NuttXThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool NuttXThread::DispatchDelegate(std::shared_ptr msg) -{ - DMQ_ASSERT_TRUE(m_created.load()); - - // 1. Allocate message container - ThreadMsg* threadMsg = new (std::nothrow) ThreadMsg(MSG_DISPATCH_DELEGATE, msg); - if (!threadMsg) return false; -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // 2. Send pointer to queue - dmq::Duration timeout; - if (FULL_POLICY == FullPolicy::TIMEOUT) - timeout = m_dispatchTimeout; - else - timeout = dmq::Duration::zero(); // DROP and FAULT: non-blocking - - // High priority routes through mq_send()'s native msg_prio argument. - bool sent = m_queue.Send(threadMsg, msg->GetPriority() == dmq::Priority::HIGH, timeout); - if (!sent) - { - if (FULL_POLICY == FullPolicy::FAULT) { - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(sent); - } else if (FULL_POLICY == FullPolicy::TIMEOUT) { - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } else { // DROP - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } - // Failed to enqueue (queue full or timed out) - delete threadMsg; - return false; - } - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - { - pthread_mutex_lock(&m_statMutex); - size_t currentDepth = GetQueueSize(); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - pthread_mutex_unlock(&m_statMutex); - } -#endif - - return true; -} - -//---------------------------------------------------------------------------- -// Process (Static Entry Point) -//---------------------------------------------------------------------------- -void* NuttXThread::Process(void* arg) -{ - NuttXThread* thread = static_cast(arg); - if (thread) - { - thread->Run(); - } - return nullptr; -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void NuttXThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void NuttXThread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void NuttXThread::WatchdogCheckAll() -{ - const dmq::LockGuard lock(GetWatchdogLock()); - NuttXThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -NuttXThread*& NuttXThread::GetWatchdogHead() -{ - static NuttXThread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& NuttXThread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -//---------------------------------------------------------------------------- -// Run (Member Function Loop) -//---------------------------------------------------------------------------- -void NuttXThread::Run() -{ - bool selfExit = false; - m_selfExitPtr = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // Wait for CreateThread() to store m_thread (see CreateThread()) - sem_wait(&m_goSem); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Reset - // before the exit handler runs (and destroyed before exitGuard on a - // self-exit), so the exit handler sees nullptr. - std::optional currentScope; - currentScope.emplace(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - sem_post(&m_startSem); - if (exitedInStart) - return; - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - // ExitThread() while held: run nothing. Cancel each queued message - // (DISCARD) until the exit message. Consuming them also keeps - // ExitThread()'s blocking send of the exit message from waiting on a - // full queue. - if (!opened) - m_discard.store(true); - } - - ThreadMsg* msg = nullptr; - while (!selfExit) - { - dmq::Duration watchdogTimeout; - { - m_lastAliveTime.store(Timer::GetNow()); - watchdogTimeout = m_watchdogTimeout.load(); - } - - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever to save power. - dmq::Duration waitOption = NuttXDelegateQueue::WAIT_FOREVER; - if (watchdogTimeout.count() > 0) - { - waitOption = watchdogTimeout / dmq::WATCHDOG_HEARTBEAT_DIVISOR; - if (waitOption <= dmq::Duration::zero()) - waitOption = std::chrono::duration_cast(std::chrono::milliseconds(1)); - } - if (idle.Enabled()) - waitOption = idle.WaitTime(watchdogTimeout.count() > 0 ? waitOption : dmq::Duration(-1)); - - // Block for a message or timeout - msg = m_queue.Receive(waitOption); - if (msg == nullptr) - { - // Exit requested but no exit message arrived (e.g. it could not be allocated) - if (m_exit.load()) - break; - - // Timed out with the queue empty: run the idle handler if it is due - if (idle.IsDue()) - { - idle.Run(); - // The idle handler exited this thread (and may have deleted it): leave - // without touching 'this', as the message path does - if (selfExit) - return; - } - } - else - { - int msgId = msg->GetId(); - if (msgId == MSG_DISPATCH_DELEGATE && m_discard.load()) - { - // ExitPolicy::DISCARD: skip messages queued ahead of the exit message - CancelThreadMsg(*msg); - } - else if (msgId == MSG_DISPATCH_DELEGATE) - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - pthread_mutex_lock(&m_statMutex); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - pthread_mutex_unlock(&m_statMutex); - } -#endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - bool success = false; - try { - success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - printf("[Thread:%s] Unhandled exception in delegate callback: %s\n", THREAD_NAME.c_str(), e.what()); - DMQ_ASSERT(); - } - catch (...) { - printf("[Thread:%s] Unhandled unknown exception in delegate callback.\n", THREAD_NAME.c_str()); - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - delete msg; - return; - } - -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - { - pthread_mutex_lock(&m_statMutex); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - pthread_mutex_unlock(&m_statMutex); - } -#endif - } - - delete msg; - - if (msgId == MSG_EXIT_THREAD) { - break; - } - - // Any message restarts the idle countdown - idle.Restart(); - } - } - - // Run the exit handler before signalling ExitThread(), so it returns only after it - currentScope.reset(); - exitGuard.Fire(); - - // Clear before signalling: once ExitThread() returns, 'this' may be destroyed - m_selfExitPtr = nullptr; - // Signal that we are about to exit - sem_post(&m_exitSem); -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -NuttXThread::ThreadStats NuttXThread::SnapshotStats() -{ - pthread_mutex_lock(&m_statMutex); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = GetQueueSize(); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = m_queueSize; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = (float)std::chrono::duration_cast(m_latencyTotalWindow).count() / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)std::chrono::duration_cast(m_latencyMaxWindow).count() / 1000.0f; - stats.latency_max_all_ms = (float)std::chrono::duration_cast(m_latencyMaxAll).count() / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = Duration(0); - - m_invokeTotalWindow = Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = Duration(0); - - pthread_mutex_unlock(&m_statMutex); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_NUTTX diff --git a/DelegateMQ/port/os/nuttx/NuttXThread.h b/DelegateMQ/port/os/nuttx/NuttXThread.h deleted file mode 100644 index 1f7a175..0000000 --- a/DelegateMQ/port/os/nuttx/NuttXThread.h +++ /dev/null @@ -1,294 +0,0 @@ -#ifndef _THREAD_NUTTX_H -#define _THREAD_NUTTX_H - -/// @file NuttXThread.h -/// @brief NuttX RTOS implementation of the DelegateMQ IThread interface. -/// -/// @note This implementation is a basic port. For reference, the stdlib and win32 -/// implementations provide additional features: -/// 1. Synchronized Startup: CreateThread() blocks until the worker thread is ready. -/// -/// **Key Features:** -/// * **Task Integration:** Wraps `pthread_create` to establish a dedicated worker loop. -/// NuttX implements the real POSIX threading API, so this port builds on -/// pthread_t/pthread_create/pthread_join directly rather than a bespoke -/// kernel-object wrapper. -/// * **FullPolicy Support:** Configurable back-pressure (DROP or TIMEOUT) when the -/// message queue is full. -/// * **Priority Support:** Normal and High priorities, using POSIX mq_send()'s -/// native msg_prio argument -- see NuttXDelegateQueue.h. -/// * **Queue-Based Dispatch:** Uses `NuttXDelegateQueue` (a thin RAII wrapper -/// around a POSIX mqueue) to receive and process incoming delegate -/// messages in a thread-safe manner. -/// * **Watchdog Integration:** Optional heartbeat mechanism detects stalled or deadlocked -/// threads. Enable by passing a timeout to CreateThread(). Requires -/// Thread::WatchdogCheckAll() to be called periodically from a context that can preempt -/// watched threads -- the highest-priority task in the system, not an ISR. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include "NuttXDelegateQueue.h" -#include "extras/util/Timer.h" -#include -#include -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -class NuttXThread : public dmq::IThread -{ -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Default queue size if 0 is passed - static const size_t DEFAULT_QUEUE_SIZE = dmq::DEFAULT_QUEUE_SIZE; - - /// Constructor - /// @param threadName Name for the NuttX pthread - /// @param maxQueueSize Max number of messages in queue (0 = Default dmq::DEFAULT_QUEUE_SIZE) - /// @param fullPolicy Action when queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - NuttXThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - NuttXThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : NuttXThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - ~NuttXThread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - pthread_t GetThreadId(); - static pthread_t GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Set the pthread scheduling priority (SCHED_FIFO). Can be called - /// before or after CreateThread(). - void SetThreadPriority(int priority); - - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get current queue size - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_created.load()); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_created.load()); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(!m_created.load()); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning NuttXThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_created.load()); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_created.load()); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_created.load()); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_created.load()); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - NuttXThread(const NuttXThread&) = delete; - NuttXThread& operator=(const NuttXThread&) = delete; - - // NuttXThread entry point - static void* Process(void* arg); - void Run(); - - /// Check watchdog is expired. Called by WatchdogCheckAll(). - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static NuttXThread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - const size_t m_queueSize; - const FullPolicy FULL_POLICY; - const dmq::Duration m_dispatchTimeout; - int m_priority; - - pthread_t m_thread{}; - NuttXDelegateQueue m_queue; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - sem_t m_exitSem{}; // Semaphore to signal thread completion - sem_t m_goSem{}; // Posted by CreateThread() once m_thread is stored - sem_t m_startSem{}; // Posted by Run() once the start handler has run - std::atomic m_exit = false; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - std::atomic m_discard = false; // ExitPolicy::DISCARD: cancel queued messages instead of invoking - std::atomic m_created = false; - bool* m_selfExitPtr = nullptr; - - // Set when the thread terminates itself (ExitThread() called from within - // its own dispatched callback). A self-exiting thread cannot join or free - // its own stack, so a later ExitThread() call (typically from - // ~NuttXThread(), made from a different thread context) checks this to - // skip the message-send/semaphore handshake and go straight to the - // pthread_join() cleanup instead. - std::atomic m_selfExited = false; - - // Stack size in bytes, applied via pthread_attr_setstacksize() before - // pthread_create(); NuttX allocates and frees the stack itself, unlike - // the Zephyr/CMSIS-RTOS2 ports which must k_aligned_alloc()/k_free() it - // manually. - static const size_t STACK_SIZE = dmq::NUTTX_STACK_BYTES; // DMQ_NUTTX_STACK_BYTES - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - NuttXThread* m_watchdogNext = nullptr; - -#if defined(DMQ_DATABUS_TOOLS) - pthread_mutex_t m_statMutex; // Mutex to protect statistics - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the NuttX port. -using Thread = NuttXThread; - -} // namespace dmq::os - -#endif // _THREAD_NUTTX_H diff --git a/DelegateMQ/port/os/posix/PosixThread.cpp b/DelegateMQ/port/os/posix/PosixThread.cpp deleted file mode 100644 index 67f7fd0..0000000 --- a/DelegateMQ/port/os/posix/PosixThread.cpp +++ /dev/null @@ -1,723 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_POSIX is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_POSIX) - -#include "DelegateMQ.h" -#include "PosixThread.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include -#include - -// Thread-local pointer into Process()'s stack frame. Set non-null only while -// Process() is running on a given thread. ExitThread() writes true through it -// when the thread destroys its own owning object so Process() can exit without -// touching freed members. -static thread_local bool* t_self_exit = nullptr; - -namespace dmq::os { - -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// MakeAbsTimeout -//---------------------------------------------------------------------------- -void PosixThread::MakeAbsTimeout(dmq::Duration timeout, struct timespec& ts) -{ - clock_gettime(CLOCK_MONOTONIC, &ts); - long long ns = std::chrono::duration_cast(timeout).count(); - ts.tv_sec += static_cast(ns / 1000000000LL); - ts.tv_nsec += static_cast(ns % 1000000000LL); - if (ts.tv_nsec >= 1000000000L) { - ts.tv_nsec -= 1000000000L; - ts.tv_sec += 1; - } -} - -//---------------------------------------------------------------------------- -// Thread -//---------------------------------------------------------------------------- -PosixThread::PosixThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , MAX_QUEUE_SIZE(maxQueueSize == 0 ? dmq::THREAD_DESKTOP_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - pthread_mutex_init(&m_startMutex, nullptr); - pthread_cond_init(&m_startCv, nullptr); - pthread_mutex_init(&m_mutex, nullptr); - - // Both condition variables use CLOCK_MONOTONIC (not the default CLOCK_REALTIME) - // so pthread_cond_timedwait() deadlines are immune to wall-clock jumps (NTP - // steps, manual clock changes) -- consistent with dmq::Clock (std::chrono:: - // steady_clock) being what dmq::Duration/dmq::TimePoint are measured against. - pthread_condattr_t attr; - pthread_condattr_init(&attr); - pthread_condattr_setclock(&attr, CLOCK_MONOTONIC); - pthread_cond_init(&m_cvNotEmpty, &attr); - pthread_cond_init(&m_cvNotFull, &attr); - pthread_condattr_destroy(&attr); -} - -//---------------------------------------------------------------------------- -// ~Thread -//---------------------------------------------------------------------------- -PosixThread::~PosixThread() -{ - ExitThread(); - - { - const std::lock_guard lock(GetWatchdogLock()); - PosixThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } - } - - pthread_cond_destroy(&m_cvNotFull); - pthread_cond_destroy(&m_cvNotEmpty); - pthread_mutex_destroy(&m_mutex); - pthread_cond_destroy(&m_startCv); - pthread_mutex_destroy(&m_startMutex); -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool PosixThread::CreateThread(std::optional watchdogTimeout) -{ - if (!m_threadCreated) - { - m_exit = false; - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - m_started = false; - - // Held until m_thread is stored and named. Process() takes this lock - // before running the start handler, which may call IsCurrentThread() or - // dispatch to this thread (both read m_thread). - pthread_mutex_lock(&m_mutex); - int rc = pthread_create(&m_thread, nullptr, &PosixThread::ThreadEntry, this); - if (rc != 0) { - pthread_mutex_unlock(&m_mutex); - m_watchdogTimeout.store(dmq::Duration(0)); // no thread to refresh the heartbeat - m_startGate.OnCreateFailed(); - return false; - } - m_threadCreated = true; - - // Set the thread name for debugging (glibc extension, name truncated to - // 15 chars + NUL -- Linux's TASK_COMM_LEN limit). Not part of the POSIX - // standard, so this is opportunistic and guarded rather than depended on. -#if defined(__linux__) - pthread_setname_np(m_thread, THREAD_NAME.substr(0, 15).c_str()); -#endif - pthread_mutex_unlock(&m_mutex); - - // Wait for the thread to enter the Process method - pthread_mutex_lock(&m_startMutex); - while (!m_started) - pthread_cond_wait(&m_startCv, &m_startMutex); - pthread_mutex_unlock(&m_startMutex); - - m_lastAliveTime.store(Timer::GetNow()); - - // Caller wants a watchdog timer? - if (watchdogTimeout.has_value()) - { - - // Add to watchdog registry if not already present - { - dmq::LockGuard lock(GetWatchdogLock()); - bool found = false; - PosixThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// ThreadEntry -//---------------------------------------------------------------------------- -void* PosixThread::ThreadEntry(void* arg) -{ - static_cast(arg)->Process(); - return nullptr; -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -pthread_t PosixThread::GetThreadId() -{ - if (!m_threadCreated) - throw std::invalid_argument("Thread pointer is null"); - - return m_thread; -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -pthread_t PosixThread::GetCurrentThreadId() -{ - return pthread_self(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool PosixThread::IsCurrentThread() -{ - if (!m_threadCreated) - return false; - - return pthread_equal(pthread_self(), m_thread) != 0; -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t PosixThread::GetQueueSize() -{ - pthread_mutex_lock(&m_mutex); - size_t size = (m_highQueue.size() + m_normalQueue.size()); - pthread_mutex_unlock(&m_mutex); - return size; -} - -void PosixThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void PosixThread::ExitThread(ExitPolicy policy) -{ - if (!m_threadCreated) return; - - auto threadMsg = xmake_shared(MSG_EXIT_THREAD, nullptr); - - // Messages taken off the queues without being invoked; canceled outside the lock - decltype(m_highQueue) discardedHigh; - decltype(m_normalQueue) discardedNormal; - - pthread_mutex_lock(&m_mutex); - - // Set exit flag INSIDE lock before notifying. - // This ensures that when a blocked producer wakes up, it sees m_exit == true immediately. - m_exit.store(true); - - // DISCARD: empty the queues so the exit message is the next one processed - if (policy == ExitPolicy::DISCARD) - { - discardedHigh.swap(m_highQueue); - discardedNormal.swap(m_normalQueue); - } - - // Explicitly allow Exit message to bypass the MAX_QUEUE_SIZE limit. - // We do not wait on m_cvNotFull here to prevent deadlock during shutdown. - // Queued last, so DRAIN invokes every message already queued first. - m_normalQueue.push_back(threadMsg); - - // Wake up consumers - pthread_cond_signal(&m_cvNotEmpty); - // Wake up blocked producers (DispatchDelegate) - pthread_cond_broadcast(&m_cvNotFull); - - pthread_mutex_unlock(&m_mutex); - - CancelAll(discardedHigh); - CancelAll(discardedNormal); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Prevent deadlock if ExitThread is called from within the thread itself - if (!pthread_equal(pthread_self(), m_thread)) - { - pthread_join(m_thread, nullptr); - } - else - { - // We are killing ourselves. Detach so the OS cleans up the thread naturally. - pthread_detach(m_thread); - // Signal Process() (running on this thread) to exit without touching - // 'this' again — the owning object is about to be freed. - if (t_self_exit) *t_self_exit = true; - m_startGate.Leave(); // exited from its start handler: never reaches the gate - } - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - pthread_mutex_lock(&m_mutex); - m_threadCreated = false; - // Normally empty. After a self-exit the loop returns without draining, - // so anything still queued is discarded here. - discardedHigh.swap(m_highQueue); - discardedNormal.swap(m_normalQueue); - // Final cleanup notification - pthread_cond_broadcast(&m_cvNotFull); - pthread_mutex_unlock(&m_mutex); - - CancelAll(discardedHigh); - CancelAll(discardedNormal); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool PosixThread::DispatchDelegate(std::shared_ptr msg) -{ - if (m_exit.load() || !m_threadCreated) return false; - - pthread_mutex_lock(&m_mutex); - - // [BACK PRESSURE / DROP / FAULT / TIMEOUT LOGIC] - if (MAX_QUEUE_SIZE > 0 && (m_highQueue.size() + m_normalQueue.size()) >= MAX_QUEUE_SIZE) - { - if (FULL_POLICY == FullPolicy::DROP) - { - size_t depth = m_highQueue.size() + m_normalQueue.size(); - pthread_mutex_unlock(&m_mutex); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; // silently discard - } - - if (FULL_POLICY == FullPolicy::FAULT) - { - pthread_mutex_unlock(&m_mutex); - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(false); - return false; - } - - if (FULL_POLICY == FullPolicy::TIMEOUT) - { - struct timespec ts; - MakeAbsTimeout(m_dispatchTimeout, ts); - bool hasSpace = false; - while (true) - { - if ((m_highQueue.size() + m_normalQueue.size()) < MAX_QUEUE_SIZE || m_exit.load()) - { - hasSpace = true; - break; - } - int rc = pthread_cond_timedwait(&m_cvNotFull, &m_mutex, &ts); - if (rc == ETIMEDOUT) - { - hasSpace = false; - break; - } - } - if (!hasSpace) - { - size_t depth = m_highQueue.size() + m_normalQueue.size(); - pthread_mutex_unlock(&m_mutex); - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; - } - // space found (or exit signaled) — fall through to push/abort check below - } - } - - // If using XALLOCATOR explicit operator new required. See xallocator.h. - auto threadMsg = xmake_shared(MSG_DISPATCH_DELEGATE, msg); -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // If we woke up because of exit (or exit happened while waiting), abort - if (m_exit.load()) - { - pthread_mutex_unlock(&m_mutex); - return false; - } - - if (threadMsg->GetPriority() == dmq::Priority::HIGH) - m_highQueue.push_back(threadMsg); - else - m_normalQueue.push_back(threadMsg); - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - size_t currentDepth = (m_highQueue.size() + m_normalQueue.size()); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; -#endif - - pthread_cond_signal(&m_cvNotEmpty); - pthread_mutex_unlock(&m_mutex); - - return true; -} - -//---------------------------------------------------------------------------- -// Process -//---------------------------------------------------------------------------- -void PosixThread::Process() -{ - // selfExit is set by ExitThread() when the thread destroys its own owner. - // It lives on this stack frame so it remains valid even after 'this' is freed. - bool selfExit = false; - t_self_exit = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // Wait for CreateThread() to finish storing m_thread - pthread_mutex_lock(&m_mutex); - pthread_mutex_unlock(&m_mutex); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Declared - // after exitGuard, so it is cleared again before the exit handler runs. - dmq::CurrentThreadScope currentScope(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - // Signal that the thread has started processing to notify CreateThread - pthread_mutex_lock(&m_startMutex); - m_started = true; - pthread_cond_signal(&m_startCv); - pthread_mutex_unlock(&m_startMutex); - if (exitedInStart) { t_self_exit = nullptr; return; } - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - if (!opened) - { - // ExitThread() while held: leave without running any message. - // ExitThread() cancels what is still queued once this thread ends. - t_self_exit = nullptr; - return; - } - } - - while (!selfExit) - { - dmq::Duration watchdogTimeout; - { - m_lastAliveTime.store(Timer::GetNow()); - watchdogTimeout = m_watchdogTimeout.load(); - } - - std::shared_ptr msg; - - pthread_mutex_lock(&m_mutex); - - auto queueReady = [this]() { return !(m_highQueue.empty() && m_normalQueue.empty()) || m_exit.load(); }; - - // Wait for message to be added to the queue. - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever (negative wait time). - dmq::Duration waitTime = idle.WaitTime(watchdogTimeout.count() > 0 ? watchdogTimeout / dmq::WATCHDOG_HEARTBEAT_DIVISOR : dmq::Duration(-1)); - if (waitTime >= dmq::Duration::zero()) - { - struct timespec ts; - MakeAbsTimeout(waitTime, ts); - while (!queueReady()) - { - int rc = pthread_cond_timedwait(&m_cvNotEmpty, &m_mutex, &ts); - if (rc == ETIMEDOUT) - break; // Timeout reached, break to update m_lastAliveTime - } - } - else - { - while (!queueReady()) - pthread_cond_wait(&m_cvNotEmpty, &m_mutex); - } - - // Always update alive time immediately after waking up - m_lastAliveTime.store(Timer::GetNow()); - - // If queue still empty, either exit (if requested), run the idle handler - // if it is due, or loop again (timeout). - if (m_highQueue.empty() && m_normalQueue.empty()) - { - bool doExit = m_exit.load(); - pthread_mutex_unlock(&m_mutex); - if (doExit) { t_self_exit = nullptr; return; } - if (idle.IsDue()) - idle.Run(); - continue; - } - - // Get highest priority message within queue - if (!m_highQueue.empty()) { - msg = m_highQueue.front(); - m_highQueue.pop_front(); - } else { - msg = m_normalQueue.front(); - m_normalQueue.pop_front(); - } - - // Unblock producers now that space is available - if (MAX_QUEUE_SIZE > 0) - pthread_cond_signal(&m_cvNotFull); - - pthread_mutex_unlock(&m_mutex); - - switch (msg->GetId()) - { - case MSG_DISPATCH_DELEGATE: - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - pthread_mutex_lock(&m_mutex); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - pthread_mutex_unlock(&m_mutex); - } -#endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - try { - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled exception in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (...) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled unknown exception in delegate callback." << std::endl; - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - t_self_exit = nullptr; - return; - } -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - if (!selfExit) { - pthread_mutex_lock(&m_mutex); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - pthread_mutex_unlock(&m_mutex); - } -#endif - break; - } - - case MSG_EXIT_THREAD: - { - t_self_exit = nullptr; - return; - } - - default: - { - DMQ_ASSERT(); - break; - } - } - - // Any message restarts the idle countdown - idle.Restart(); - - // msg goes out of scope here — may trigger self-destruction of 'this'. - // After this point do not access any member; check selfExit in while(). - } - t_self_exit = nullptr; -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void PosixThread::WatchdogCheckAll() -{ - const std::lock_guard lock(GetWatchdogLock()); - PosixThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void PosixThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void PosixThread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -PosixThread*& PosixThread::GetWatchdogHead() -{ - static PosixThread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& PosixThread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -PosixThread::ThreadStats PosixThread::SnapshotStats() -{ - pthread_mutex_lock(&m_mutex); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = (m_highQueue.size() + m_normalQueue.size()); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = MAX_QUEUE_SIZE; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = (float)std::chrono::duration_cast(m_latencyTotalWindow).count() / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)std::chrono::duration_cast(m_latencyMaxWindow).count() / 1000.0f; - stats.latency_max_all_ms = (float)std::chrono::duration_cast(m_latencyMaxAll).count() / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = dmq::Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = dmq::Duration(0); - - m_invokeTotalWindow = dmq::Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = dmq::Duration(0); - - pthread_mutex_unlock(&m_mutex); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_POSIX diff --git a/DelegateMQ/port/os/posix/PosixThread.h b/DelegateMQ/port/os/posix/PosixThread.h deleted file mode 100644 index 41d8806..0000000 --- a/DelegateMQ/port/os/posix/PosixThread.h +++ /dev/null @@ -1,329 +0,0 @@ -#ifndef _THREAD_POSIX_H -#define _THREAD_POSIX_H - -/// @file PosixThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Raw POSIX implementation of the DelegateMQ IThread interface. -/// -/// @details -/// This class provides a native POSIX implementation of the `IThread` interface using -/// `pthread_create`/`pthread_mutex_t`/`pthread_cond_t` directly, rather than going through -/// `std::thread`/`std::mutex`/`std::condition_variable` the way `StdlibThread` does. It -/// creates a dedicated worker thread with an event loop capable of processing asynchronous -/// delegates and system messages -- mirroring `Win32Thread`'s relationship to `StdlibThread` -/// (native OS API instead of the C++ standard library), but for POSIX. -/// -/// `dmq::Mutex`, `dmq::ConditionVariable`, `dmq::Clock`, and `dmq::ThisThread` are NOT -/// reimplemented here -- they still resolve to `std::mutex`/`std::condition_variable`/ -/// `std::chrono::steady_clock`/`std::this_thread` (see `DelegateOpt.h`'s -/// `DMQ_THREAD_STDLIB || DMQ_THREAD_WIN32 || DMQ_THREAD_QT || DMQ_THREAD_POSIX` branches), -/// since those are already thin, efficient wrappers over these same POSIX primitives under -/// glibc/libstdc++. This file is the only thing `DMQ_THREAD_POSIX` adds. -/// -/// **Key Features:** -/// * **Priority Queue:** One FIFO `std::deque` per priority level, so high-priority -/// delegate messages (e.g. system signals) are processed before normal ones, and -/// messages of the same priority are processed in the order they were dispatched. -/// * **Queue Full Policy:** Configurable `FullPolicy` (DROP, FAULT, or TIMEOUT), always enforced -- -/// `maxQueueSize == 0` falls back to `dmq::THREAD_DESKTOP_QUEUE_SIZE` rather than disabling -/// the cap, since this port backs its queue with a plain `std::deque` and would otherwise -/// grow without bound if the destination thread is dead/stuck. TIMEOUT waits up to -/// `dispatchTimeout` for the consumer before logging and dropping; DROP silently discards -/// immediately. FAULT (the default) triggers a system fault. -/// * **Monotonic Timed Waits:** The condition variables are created with `pthread_condattr_setclock( -/// CLOCK_MONOTONIC)` so `pthread_cond_timedwait()` deadlines are immune to `CLOCK_REALTIME` -/// jumps (NTP steps, manual clock changes) -- unlike a naive POSIX cv using the default clock. -/// `pthread_condattr_setclock()` itself is a common POSIX extension (present on Linux's glibc -/// and musl) rather than a portable POSIX-standard guarantee -- e.g. not implemented on Darwin/ -/// macOS -- which is the one place this port leans on more than the base POSIX spec. -/// * **Watchdog Integration:** Includes a built-in heartbeat mechanism. If the thread loop -/// stalls (deadlock or infinite loop), the watchdog timer detects the failure. -/// * **Synchronized Start:** Uses a dedicated mutex/condition-variable pair to ensure the -/// thread is fully initialized and running before `CreateThread()` returns. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "./extras/util/Timer.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -/// @brief Raw POSIX (pthreads) thread for Linux and other POSIX systems. -/// @details The PosixThread class creates a worker thread capable of dispatching and -/// invoking asynchronous delegates. -class PosixThread : public dmq::IThread -{ - XALLOCATOR -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Constructor - /// @param threadName The name of the thread for debugging. - /// @param maxQueueSize The maximum number of messages allowed in the queue. - /// 0 falls back to dmq::THREAD_DESKTOP_QUEUE_SIZE -- a high-water-mark - /// safety net, not a throughput limiter, against unbounded growth if - /// the destination thread is dead/stuck. - /// @param fullPolicy When the queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - PosixThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - PosixThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : PosixThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - /// Destructor - virtual ~PosixThread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - /// Get the ID of this thread instance - pthread_t GetThreadId(); - - /// Get the ID of the currently executing thread - static pthread_t GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Get thread name - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get size of thread message queue. - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - /// Dispatch and invoke a delegate target on the destination thread. - /// @param[in] msg - Delegate message containing target function - /// arguments. - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_threadCreated); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_threadCreated); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(!m_threadCreated); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning PosixThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_threadCreated); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_threadCreated); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_threadCreated); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_threadCreated); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Process() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - PosixThread(const PosixThread&) = delete; - PosixThread& operator=(const PosixThread&) = delete; - - /// pthread entry point trampoline - static void* ThreadEntry(void* arg); - - /// Entry point for the thread - void Process(); - - /// Check watchdog is expired. Called by WatchdogCheckAll(), which the application - /// calls periodically, typically from its highest-priority task. Thread-safe. - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static PosixThread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - /// Compute an absolute CLOCK_MONOTONIC deadline `timeout` from now, for pthread_cond_timedwait(). - static void MakeAbsTimeout(dmq::Duration timeout, struct timespec& ts); - - pthread_t m_thread{}; - bool m_threadCreated = false; - - // Startup synchronization: CreateThread() blocks here until Process() signals it has started. - pthread_mutex_t m_startMutex; - pthread_cond_t m_startCv; - bool m_started = false; - - pthread_mutex_t m_mutex; - - // Condition variable to wake up consumers when a message is enqueued - pthread_cond_t m_cvNotEmpty; - - // Condition variable to wake up blocked producers when space is available - pthread_cond_t m_cvNotFull; - -#ifdef DMQ_ALLOCATOR - std::deque, stl_allocator>> m_highQueue; - std::deque, stl_allocator>> m_normalQueue; -#else - std::deque> m_highQueue; - std::deque> m_normalQueue; -#endif - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - - // Max queue size for back pressure (0 = unlimited) - const size_t MAX_QUEUE_SIZE; - - // Policy applied when the thread message queue is full. - const FullPolicy FULL_POLICY; - - // Timeout duration for TIMEOUT policy - const dmq::Duration m_dispatchTimeout; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - - std::atomic m_exit; - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - PosixThread* m_watchdogNext = nullptr; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - -#if defined(DMQ_DATABUS_TOOLS) - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the posix port. -using Thread = PosixThread; - -} // namespace dmq::os - -#endif diff --git a/DelegateMQ/port/os/qt/QtThread.cpp b/DelegateMQ/port/os/qt/QtThread.cpp deleted file mode 100644 index cac25ad..0000000 --- a/DelegateMQ/port/os/qt/QtThread.cpp +++ /dev/null @@ -1,574 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_QT is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_QT) - -#include "DelegateMQ.h" -#include "QtThread.h" -#include "extras/util/Fault.h" -#include -#include - -namespace dmq::os { - -using namespace dmq; -using namespace dmq::util; - -// Define DMQ_ASSERT_TRUE if not already defined -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(x) Q_ASSERT(x) -#endif - -// QTimer takes an int millisecond interval: at least 1, clamped so a very long -// interval (over ~24 days) doesn't overflow -static int ToTimerInterval(long long ms) -{ - if (ms < 1) return 1; - if (ms > std::numeric_limits::max()) return std::numeric_limits::max(); - return static_cast(ms); -} - -// Register the metatype ID once -static int registerId = qRegisterMetaType>(); - -//---------------------------------------------------------------------------- -// Worker::OnDispatch -//---------------------------------------------------------------------------- -void Worker::OnDispatch(std::shared_ptr msg) { - // Watchdog heartbeat: the event loop reached another message - if (m_thread) - m_thread->ThreadCheck(); - - // ExitPolicy::DISCARD: skip messages queued ahead of the event loop's quit - if (m_discard.load()) { - if (msg) - msg->Cancel(); - emit MessageProcessed(); - return; - } - - if (msg) { - auto invoker = msg->GetInvoker(); - if (invoker) { -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - try { - bool success = invoker->Invoke(msg); - DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - qWarning() << "[Thread:" << m_thread->objectName() << "] Unhandled bad_alloc in delegate callback:" << e.what(); - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - qWarning() << "[Thread:" << m_thread->objectName() << "] Unhandled invalid_argument in delegate callback:" << e.what(); - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - qWarning() << "[Thread:" << m_thread->objectName() << "] Unhandled runtime_error in delegate callback:" << e.what(); - DMQ_ASSERT(); - } - catch (const std::exception& e) { - qWarning() << "[Thread:" << m_thread->objectName() << "] Unhandled exception in delegate callback:" << e.what(); - DMQ_ASSERT(); - } - catch (...) { - qWarning() << "[Thread:" << m_thread->objectName() << "] Unhandled unknown exception in delegate callback."; - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(msg); - DMQ_ASSERT_TRUE(success); -#endif -#if defined(DMQ_DATABUS_TOOLS) - if (m_thread) { - dmq::Duration invokeTime = Timer::GetNow() - start; - m_thread->UpdateInvokeStats(invokeTime); - } -#endif - } - } - - // Any message restarts the idle countdown - if (m_idleTimer) - m_idleTimer->start(); - - emit MessageProcessed(); -} - -//---------------------------------------------------------------------------- -// Worker::StartIdleTimer -//---------------------------------------------------------------------------- -void Worker::StartIdleTimer(const dmq::UnicastDelegate& handler, dmq::Duration interval) -{ - m_idleHandler = handler; - auto ms = std::chrono::ceil(interval).count(); - - m_idleTimer = new QTimer(this); - m_idleTimer->setSingleShot(true); - m_idleTimer->setInterval(ToTimerInterval(ms)); - connect(m_idleTimer, &QTimer::timeout, this, [this]() { - m_idleHandler(); - m_idleTimer->start(); - }); - m_idleTimer->start(); -} - -//---------------------------------------------------------------------------- -// Worker::StartHeartbeat -//---------------------------------------------------------------------------- -void Worker::StartHeartbeat(dmq::Duration interval) -{ - auto ms = std::chrono::ceil(interval).count(); - - m_heartbeatTimer = new QTimer(this); - m_heartbeatTimer->setInterval(ToTimerInterval(ms)); - // Fires only while the event loop runs, so a stuck handler stops the heartbeat - connect(m_heartbeatTimer, &QTimer::timeout, this, [this]() { - if (m_thread) - m_thread->ThreadCheck(); - }); - m_heartbeatTimer->start(); -} - -//---------------------------------------------------------------------------- -// Thread Constructor -//---------------------------------------------------------------------------- -QtThread::QtThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : m_threadName(threadName) - , m_cpuName(cpuName) - , m_maxQueueSize((maxQueueSize == 0) ? DEFAULT_QUEUE_SIZE : maxQueueSize) - , m_fullPolicy(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) -{ -} - -//---------------------------------------------------------------------------- -// Thread Destructor -//---------------------------------------------------------------------------- -QtThread::~QtThread() -{ - ExitThread(); - - const std::lock_guard lock(GetWatchdogLock()); - QtThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool QtThread::CreateThread(std::optional watchdogTimeout) -{ - if (!m_thread) - { - m_exiting.store(false); - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - m_thread = new QThread(); - m_thread->setObjectName(QString::fromUtf8(m_threadName.c_str())); - - // Create worker and move it to the new thread - m_worker = new Worker(this); - m_worker->moveToThread(m_thread); - - // Connect the Dispatch signal to the Worker's slot. - // Qt::QueuedConnection is mandatory for cross-thread communication, - // but Qt defaults to AutoConnection which handles this correctly. - connect(this, &QtThread::SignalDispatch, - m_worker, &Worker::OnDispatch, - Qt::QueuedConnection); - - // Track when message is processed to decrement m_queueSize - connect(m_worker, &Worker::MessageProcessed, - this, &QtThread::OnMessageProcessed); - - // Ensure worker is deleted when thread finishes - connect(m_thread, &QThread::finished, m_worker, &QObject::deleteLater); - - // Start handler and idle timer run on the new thread (started is emitted - // there; DirectConnection runs the lambda in place) before its event loop - // processes any dispatched message. - Worker* worker = m_worker; - QSemaphore* startSem = &m_startSem; - dmq::IThread* self = this; - QtThread* qt = this; // start gate state; see the self-exit check below - connect(m_thread, &QThread::started, m_worker, - [worker, self, qt, startSem, startHandler = m_startHandler, - idleHandler = m_idleHandler, idleInterval = m_idleInterval, - watchdog = m_watchdogTimeout.load()]() { - worker->BeginCurrentScope(self); - if (startHandler) - startHandler(); - if (idleHandler) - worker->StartIdleTimer(idleHandler, idleInterval); - if (watchdog.count() > 0) - worker->StartHeartbeat(watchdog / dmq::WATCHDOG_HEARTBEAT_DIVISOR); - - // A start handler that exited this thread (ExitThread() on itself) - // leaves right after the release below: once CreateThread() returns, - // the QtThread may be destroyed, so nothing after it may touch 'qt'. - const bool exitedInStart = qt->m_exiting.load(); - startSem->release(); - if (exitedInStart) - return; - - // Optional start gate: hold here, before the event loop runs any - // dispatched message, until it opens - if (qt->m_startGate.Enabled()) - { - const bool opened = qt->m_startGate.Wait(qt->m_exiting); - qt->m_lastAliveTime.store(Timer::GetNow()); // before Passed() - qt->m_startGate.Passed(); - // ExitThread() while held: the event loop cancels every - // queued message (discard) up to the quit queued behind them - if (!opened) - worker->SetDiscard(true); - } - }, Qt::DirectConnection); - - // Exit handler runs on the worker thread as it finishes (finished is - // emitted there), after GetCurrent() is cleared. Captured by copy so it - // works even if this QtThread was destroyed by a self-exit. - connect(m_thread, &QThread::finished, m_worker, - [worker, exitHandler = m_exitHandler]() { - worker->EndCurrentScope(); - if (exitHandler) - exitHandler(); - }, Qt::DirectConnection); - - // Also delete the QThread object itself when finished (optional, depending on ownership) - // connect(m_thread, &QThread::finished, m_thread, &QObject::deleteLater); - - m_thread->start(); - - // Wait for the start handler to complete - m_startSem.acquire(); - - m_lastAliveTime.store(Timer::GetNow()); - - if (watchdogTimeout.has_value()) - { - - // Add to watchdog registry if not already present - { - dmq::LockGuard lock(GetWatchdogLock()); - bool found = false; - QtThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void QtThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(m_threadName.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void QtThread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void QtThread::WatchdogCheckAll() -{ - const std::lock_guard lock(GetWatchdogLock()); - QtThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -QtThread*& QtThread::GetWatchdogHead() -{ - static QtThread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& QtThread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void QtThread::ExitThread(ExitPolicy policy) -{ - if (m_thread) - { - m_exiting.store(true); - const bool selfExit = (QThread::currentThread() == m_thread); - if (selfExit) - m_startGate.Leave(); // exited from its start handler: never reaches the gate - - // A self-exit always discards: the event loop keeps running after this - // object may be destroyed. - m_worker->SetDiscard(policy == ExitPolicy::DISCARD || selfExit); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Quit queued behind every message already dispatched, so DRAIN invokes - // them first and DISCARD cancels them first. - QThread* thread = m_thread; - QMetaObject::invokeMethod(m_worker, [thread]() { thread->quit(); }, Qt::QueuedConnection); - - // Wake any blocked threads - m_mutex.lock(); - m_cvNotFull.wakeAll(); - m_mutex.unlock(); - - if (!selfExit) { - m_thread->wait(); - delete m_thread; - } else { - m_thread->deleteLater(); - } - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - // Worker thread has fully stopped; null the back-pointer so the Worker - // cannot access this Thread if it is kept alive by deleteLater. - if (m_worker) { - m_worker->ClearThread(); - } - - m_thread = nullptr; - m_worker = nullptr; - } -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -QThread* QtThread::GetThreadId() -{ - return m_thread; -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -QThread* QtThread::GetCurrentThreadId() -{ - return QThread::currentThread(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool QtThread::IsCurrentThread() -{ - return GetThreadId() == GetCurrentThreadId(); -} - -void QtThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool QtThread::DispatchDelegate(std::shared_ptr msg) -{ - // Safety check: Don't emit if thread is tearing down - if (m_thread && m_thread->isRunning() && !m_exiting.load()) - { - m_mutex.lock(); - if (m_queueSize >= m_maxQueueSize) - { - if (m_fullPolicy == FullPolicy::DROP) - { - size_t depth = m_queueSize.load(); - m_mutex.unlock(); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; // silently discard - } - - if (m_fullPolicy == FullPolicy::FAULT) - { - m_mutex.unlock(); - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", m_threadName.c_str()); - DMQ_ASSERT_TRUE(m_queueSize < m_maxQueueSize); - return false; - } - - if (m_fullPolicy == FullPolicy::TIMEOUT) - { - auto ms = static_cast( - std::chrono::duration_cast(m_dispatchTimeout).count()); - while (m_queueSize >= m_maxQueueSize && m_thread->isRunning()) - { - if (!m_cvNotFull.wait(&m_mutex, ms)) - { - size_t depth = m_queueSize.load(); - m_mutex.unlock(); - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", m_threadName.c_str()); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; - } - } - } - } - - // Re-check running status after wait - if (m_thread->isRunning()) - { - m_queueSize++; - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - size_t currentDepth = m_queueSize.load(); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - m_dispatchCountAll++; -#endif - - // Unlike the other thread ports, msg->GetPriority() is ignored here: - // the queued signal goes into Qt's single FIFO event queue, so a - // Priority::HIGH message runs after every message dispatched before - // it. The other ports keep a HIGH and a NORMAL queue and drain HIGH - // first. Supporting priority would need a two-lane queue here, with - // the signal only waking the worker to drain it. - emit SignalDispatch(msg); - m_mutex.unlock(); - return true; - } - m_mutex.unlock(); - } - return false; -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// UpdateInvokeStats -//---------------------------------------------------------------------------- -void QtThread::UpdateInvokeStats(dmq::Duration invokeTime) -{ - m_mutex.lock(); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - m_mutex.unlock(); -} - -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -QtThread::ThreadStats QtThread::SnapshotStats() -{ - m_mutex.lock(); - ThreadStats stats; - stats.cpu_name = m_cpuName; - stats.thread_name = m_threadName; - stats.queue_depth = m_queueSize.load(); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = m_maxQueueSize; - - // Qt port doesn't implement latency yet due to Signal/Slot bridge limitations - stats.latency_avg_ms = 0.0f; - stats.latency_max_window_ms = 0.0f; - stats.latency_max_all_ms = 0.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = Duration(0); - - m_invokeTotalWindow = Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = Duration(0); - - m_mutex.unlock(); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_QT diff --git a/DelegateMQ/port/os/qt/QtThread.h b/DelegateMQ/port/os/qt/QtThread.h deleted file mode 100644 index 3f84ae5..0000000 --- a/DelegateMQ/port/os/qt/QtThread.h +++ /dev/null @@ -1,341 +0,0 @@ -#ifndef _QT_THREAD_H -#define _QT_THREAD_H - -/// @file QtThread.h -/// @brief Qt implementation of the DelegateMQ IThread interface. -/// -/// @note No message priority: dmq::Priority is ignored, and messages run in the -/// order they were dispatched (Qt's event queue). The other thread ports process -/// Priority::HIGH messages before NORMAL ones. -/// -/// **Key Features:** -/// * **QThread Integration:** Wraps `QThread` and uses a Worker object to execute -/// delegates in the target thread's event loop. -/// * **FullPolicy Support:** Configurable back-pressure (DROP, FAULT, or TIMEOUT) using -/// `QMutex` and `QWaitCondition`. -/// * **Signal/Slot Dispatch:** Uses Qt's meta-object system to bridge delegate -/// execution across thread boundaries. -/// * **Watchdog Integration:** Optional heartbeat mechanism detects stalled or deadlocked -/// threads. Enable by passing a timeout to CreateThread(). Requires -/// Thread::WatchdogCheckAll() to be called periodically from a context that can preempt -/// watched threads -- the highest-priority thread in the system, not an ISR. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. -/// - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "port/os/common/StartGate.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -// ---------------------------------------------------------------------------- -// Worker Object -// Lives on the target QThread and executes the slots -// ---------------------------------------------------------------------------- -class QtThread; -class Worker : public QObject -{ - Q_OBJECT -public: - Worker(QtThread* thread = nullptr) : m_thread(thread) {} - void ClearThread() { m_thread = nullptr; } - - /// Start the idle countdown. Must be called on the worker's thread. - void StartIdleTimer(const dmq::UnicastDelegate& handler, dmq::Duration interval); - - /// Refresh the watchdog heartbeat every `interval` while the event loop is - /// idle. Must be called on the worker's thread. - void StartHeartbeat(dmq::Duration interval); - - /// Register `thread` for dmq::ThisThread::GetCurrent() until EndCurrentScope(). - /// Both must be called on the worker's thread. - void BeginCurrentScope(dmq::IThread* thread) { m_currentScope.emplace(thread); } - void EndCurrentScope() { m_currentScope.reset(); } - - /// ExitPolicy::DISCARD: cancel messages instead of invoking them. Set by - /// ExitThread() from any thread before it queues the event loop's quit. - void SetDiscard(bool discard) { m_discard.store(discard); } - -public slots: - void OnDispatch(std::shared_ptr msg); - -signals: - void MessageProcessed(); - -private: - QtThread* m_thread; - - // Idle handler copy and its single-shot timer, restarted by every message. - // Created on the worker's thread by StartIdleTimer(); null if no idle handler. - dmq::UnicastDelegate m_idleHandler; - QTimer* m_idleTimer = nullptr; - - // Watchdog heartbeat: refreshes the alive timestamp while the event loop is - // idle. Created by StartHeartbeat(); null if the thread has no watchdog. - QTimer* m_heartbeatTimer = nullptr; - - // Held for the life of the event loop: a Qt worker has no loop stack frame - std::optional m_currentScope; - - std::atomic m_discard{ false }; -}; - -class QtThread : public QObject, public dmq::IThread -{ - Q_OBJECT - -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Default queue size if 0 is passed - static const size_t DEFAULT_QUEUE_SIZE = dmq::DEFAULT_QUEUE_SIZE; - - /// Constructor - /// @param threadName Name for debugging (QObject::objectName) - /// @param maxQueueSize Max number of messages in queue (0 = Default dmq::DEFAULT_QUEUE_SIZE) - /// @param fullPolicy Action when queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - QtThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - QtThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : QtThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - /// Destructor - ~QtThread(); - - /// Create and start the internal QThread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - /// Get the QThread pointer (used as the ID) - QThread* GetThreadId(); - - /// Get the current executing QThread pointer - static QThread* GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - dmq::xstring GetThreadName() const { return m_threadName; } - - /// Get current queue size - size_t GetQueueSize() const { return m_queueSize.load(); } - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - // IThread Interface Implementation - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_thread); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_thread); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(!m_thread); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning QtThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_thread); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_thread); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_thread); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_thread); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); - - /// @brief Internal method for Worker to update invoke stats. - void UpdateInvokeStats(dmq::Duration invokeTime); -#endif - -signals: - // Internal signal to bridge threads - void SignalDispatch(std::shared_ptr msg); - -private slots: - void OnMessageProcessed() { - m_queueSize--; - m_cvNotFull.wakeAll(); - } - -private: - QtThread(const QtThread&) = delete; - QtThread& operator=(const QtThread&) = delete; - - /// Check watchdog is expired. Called by WatchdogCheckAll(). - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static QtThread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - const dmq::xstring m_threadName; - const dmq::xstring m_cpuName; - const size_t m_maxQueueSize; - const FullPolicy m_fullPolicy; - const dmq::Duration m_dispatchTimeout; - QThread* m_thread = nullptr; - Worker* m_worker = nullptr; - std::atomic m_queueSize{0}; - QMutex m_mutex; - QWaitCondition m_cvNotFull; - - // Released on the worker thread once the start handler has run - QSemaphore m_startSem; - - // Set by ExitThread(): DispatchDelegate() rejects new messages, which would - // otherwise queue behind the event loop's quit and never run - std::atomic m_exiting{ false }; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - QtThread* m_watchdogNext = nullptr; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - -#if defined(DMQ_DATABUS_TOOLS) - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the Qt port. -using Thread = QtThread; - -} // namespace dmq::os - -#endif // _QT_THREAD_H diff --git a/DelegateMQ/port/os/stdlib/StdlibThisThread.h b/DelegateMQ/port/os/stdlib/StdlibThisThread.h deleted file mode 100644 index 1a57fb1..0000000 --- a/DelegateMQ/port/os/stdlib/StdlibThisThread.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef STDLIB_THIS_THREAD_H -#define STDLIB_THIS_THREAD_H - -/// @file StdlibThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief dmq::ThisThread for the desktop ports (stdlib, Win32, Qt, POSIX). -/// -/// @details -/// std::this_thread is already portable on these platforms, so sleep_for() and -/// yield() forward to it. GetCurrent() uses thread_local storage. - -#include "port/os/common/CurrentThreadStorage.h" -#include -#include - -namespace dmq::os { - - struct StdlibThisThread : ThreadLocalCurrentThread { - template - static void sleep_for(std::chrono::duration d) { std::this_thread::sleep_for(d); } - - static void yield() noexcept { std::this_thread::yield(); } - }; - -} // namespace dmq::os - -#endif // STDLIB_THIS_THREAD_H diff --git a/DelegateMQ/port/os/stdlib/StdlibThread.cpp b/DelegateMQ/port/os/stdlib/StdlibThread.cpp deleted file mode 100644 index d4a5e7d..0000000 --- a/DelegateMQ/port/os/stdlib/StdlibThread.cpp +++ /dev/null @@ -1,685 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_STDLIB is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_STDLIB) - -#include "DelegateMQ.h" -#include "StdlibThread.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" - -#ifdef _WIN32 -#include -#endif -#ifdef __linux__ -#include -#endif - -// Thread-local pointer into Process()'s stack frame. Set non-null only while -// Process() is running on a given thread. ExitThread() writes true through it -// when the thread destroys its own owning object so Process() can exit without -// touching freed members. -static thread_local bool* t_self_exit = nullptr; - -namespace dmq::os { - -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// Thread -//---------------------------------------------------------------------------- -StdlibThread::StdlibThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : m_thread(std::nullopt) - , m_exit(false) - , THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , MAX_QUEUE_SIZE(maxQueueSize == 0 ? dmq::THREAD_DESKTOP_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) -{ -} - -//---------------------------------------------------------------------------- -// ~Thread -//---------------------------------------------------------------------------- -StdlibThread::~StdlibThread() -{ - ExitThread(); - - const std::lock_guard lock(GetWatchdogLock()); - StdlibThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool StdlibThread::CreateThread(std::optional watchdogTimeout) -{ - if (!m_thread) - { - m_threadStartPromise.emplace(); - m_threadStartFuture.emplace(m_threadStartPromise->get_future()); - m_exit = false; - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - - { - // Held until m_thread is fully constructed and named. Process() takes - // this lock before running the start handler, which may call - // IsCurrentThread() or dispatch to this thread (both read m_thread). - std::lock_guard lock(m_mutex); - m_thread.emplace(&StdlibThread::Process, this); - - auto handle = m_thread->native_handle(); - SetThreadName(handle, THREAD_NAME); - } - - // Wait for the thread to run the start handler and enter its loop - m_threadStartFuture->get(); - - m_lastAliveTime.store(Timer::GetNow()); - - // Caller wants a watchdog timer? - if (watchdogTimeout.has_value()) - { - - // Add to watchdog registry if not already present - { - dmq::LockGuard lock(GetWatchdogLock()); - bool found = false; - StdlibThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -std::thread::id StdlibThread::GetThreadId() -{ - if (!m_thread.has_value()) - throw std::invalid_argument("Thread pointer is null"); - - return m_thread->get_id(); -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -std::thread::id StdlibThread::GetCurrentThreadId() -{ - return std::this_thread::get_id(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool StdlibThread::IsCurrentThread() -{ - if (!m_thread.has_value()) - return false; - - return GetThreadId() == GetCurrentThreadId(); -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t StdlibThread::GetQueueSize() -{ - std::lock_guard lock(m_mutex); - return (m_highQueue.size() + m_normalQueue.size()); -} - -void StdlibThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// SetThreadName -//---------------------------------------------------------------------------- -void StdlibThread::SetThreadName(std::thread::native_handle_type handle, const dmq::xstring& name) -{ - (void)handle; - (void)name; -#ifdef _WIN32 - // Set the thread name so it shows in the Visual Studio Debug Location toolbar - std::wstring wstr(name.begin(), name.end()); - HRESULT hr = SetThreadDescription(handle, wstr.c_str()); - if (FAILED(hr)) - { - // Handle error if needed - } -#elif defined(__linux__) - // Shown by top -H, ps -L, gdb and perf. Linux limits names to 15 characters. - pthread_setname_np(handle, name.substr(0, 15).c_str()); -#endif -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void StdlibThread::ExitThread(ExitPolicy policy) -{ - if (!m_thread) - return; - - // Create a new ThreadMsg - auto threadMsg = xmake_shared(MSG_EXIT_THREAD, nullptr); - - // Messages taken off the queues without being invoked; canceled outside the lock - decltype(m_highQueue) discardedHigh; - decltype(m_normalQueue) discardedNormal; - - { - std::lock_guard lock(m_mutex); - - // Set exit flag INSIDE lock before notifying. - // This ensures that when a blocked producer wakes up, it sees m_exit == true immediately. - m_exit.store(true); - - // DISCARD: empty the queues so the exit message is the next one processed - if (policy == ExitPolicy::DISCARD) - { - discardedHigh.swap(m_highQueue); - discardedNormal.swap(m_normalQueue); - } - - // Explicitly allow Exit message to bypass the MAX_QUEUE_SIZE limit. - // We do not wait on m_cvNotFull here to prevent deadlock during shutdown. - if (threadMsg->GetPriority() == dmq::Priority::HIGH) - m_highQueue.push_back(threadMsg); - else - m_normalQueue.push_back(threadMsg); - - // Wake up consumers - m_cv.notify_one(); - // Wake up blocked producers (DispatchDelegate) - m_cvNotFull.notify_all(); - } - - CancelAll(discardedHigh); - CancelAll(discardedNormal); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Prevent deadlock if ExitThread is called from within the thread itself - if (m_thread->joinable()) - { - if (std::this_thread::get_id() != m_thread->get_id()) - { - m_thread->join(); - } - else - { - // We are killing ourselves. Detach so the thread object cleans up naturally. - m_thread->detach(); - // Signal Process() (running on this thread) to exit without touching - // 'this' again — the owning object is about to be freed. - if (t_self_exit) *t_self_exit = true; - m_startGate.Leave(); // exited from its start handler: never reaches the gate - } - } - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - { - std::lock_guard lock(m_mutex); - m_thread.reset(); - - // Normally empty. After a self-exit the loop returns without draining, - // so anything still queued is discarded here. - discardedHigh.swap(m_highQueue); - discardedNormal.swap(m_normalQueue); - - // Final cleanup notification - m_cvNotFull.notify_all(); - } - - CancelAll(discardedHigh); - CancelAll(discardedNormal); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool StdlibThread::DispatchDelegate(std::shared_ptr msg) -{ - // Early check, though we re-check inside lock for safety - if (m_exit.load()) - return false; - - if (!m_thread.has_value()) - throw std::invalid_argument("Thread pointer is null"); - - std::unique_lock lk(m_mutex); - - // [BACK PRESSURE / DROP / FAULT / TIMEOUT LOGIC] - if (MAX_QUEUE_SIZE > 0 && (m_highQueue.size() + m_normalQueue.size()) >= MAX_QUEUE_SIZE) - { - if (FULL_POLICY == FullPolicy::DROP) - { - size_t depth = m_highQueue.size() + m_normalQueue.size(); - lk.unlock(); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; // silently discard — caller is not stalled, no allocation wasted - } - - if (FULL_POLICY == FullPolicy::FAULT) - { - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(false); - return false; - } - - if (FULL_POLICY == FullPolicy::TIMEOUT) - { - bool hasSpace = m_cvNotFull.wait_for(lk, m_dispatchTimeout, [this]() { - return (m_highQueue.size() + m_normalQueue.size()) < MAX_QUEUE_SIZE || m_exit.load(); - }); - if (!hasSpace) { - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - size_t depth = m_highQueue.size() + m_normalQueue.size(); - lk.unlock(); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; - } - // space found — fall through to push - } - - } - - // If using XALLOCATOR explicit operator new required. See xallocator.h. - auto threadMsg = xmake_shared(MSG_DISPATCH_DELEGATE, msg); -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // If we woke up because of exit (or exit happened while waiting), abort - if (m_exit.load()) - return false; - - if (threadMsg->GetPriority() == dmq::Priority::HIGH) - m_highQueue.push_back(threadMsg); - else - m_normalQueue.push_back(threadMsg); - -#if defined(DMQ_DATABUS_TOOLS) - // Snapshot size while holding m_mutex - size_t currentDepth = (m_highQueue.size() + m_normalQueue.size()); -#endif - - m_cv.notify_one(); - lk.unlock(); // Release producer-blocking lock early - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats under the separate stats mutex - { - std::lock_guard lock(m_statsMutex); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - } -#endif - - return true; -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void StdlibThread::WatchdogCheckAll() -{ - const std::lock_guard lock(GetWatchdogLock()); - StdlibThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void StdlibThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void StdlibThread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -StdlibThread*& StdlibThread::GetWatchdogHead() -{ - static StdlibThread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& StdlibThread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -//---------------------------------------------------------------------------- -// Process -//---------------------------------------------------------------------------- -void StdlibThread::Process() -{ - // selfExit is set by ExitThread() when the thread destroys its own owner. - // It lives on this stack frame so it remains valid even after 'this' is freed. - bool selfExit = false; - t_self_exit = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // Wait for CreateThread() to finish constructing m_thread - { std::lock_guard lock(m_mutex); } - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Declared - // after exitGuard, so it is cleared again before the exit handler runs. - dmq::CurrentThreadScope currentScope(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - // Signal that the thread has started processing to notify CreateThread. - // From a local: the caller may destroy this object once it is signaled. - std::promise startPromise = std::move(*m_threadStartPromise); - startPromise.set_value(); - if (exitedInStart) { t_self_exit = nullptr; return; } - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - if (!opened) - { - // ExitThread() while held: leave without running any message. - // ExitThread() cancels what is still queued once this thread ends. - t_self_exit = nullptr; - return; - } - } - - while (!selfExit) - { - dmq::Duration watchdogTimeout; - { - m_lastAliveTime.store(Timer::GetNow()); - watchdogTimeout = m_watchdogTimeout.load(); - } - - std::shared_ptr msg; - { - std::unique_lock lk(m_mutex); - - // Wait for message to be added to the queue. - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever. - auto predicate = [this]() { return !(m_highQueue.empty() && m_normalQueue.empty()) || m_exit.load(); }; - // Wake up frequently to ensure heartbeat is updated while idle (negative = forever) - dmq::Duration waitTime = idle.WaitTime(watchdogTimeout.count() > 0 ? watchdogTimeout / dmq::WATCHDOG_HEARTBEAT_DIVISOR : dmq::Duration(-1)); - if (waitTime >= dmq::Duration::zero()) - m_cv.wait_for(lk, waitTime, predicate); - else - m_cv.wait(lk, predicate); - - // Always update alive time immediately after waking up - m_lastAliveTime.store(Timer::GetNow()); - - // If empty and exit is true, we should exit. - if ((m_highQueue.empty() && m_normalQueue.empty())) - { - if (m_exit.load()) { t_self_exit = nullptr; return; } - if (!idle.IsDue()) - continue; - // Idle handler is due: fall through with no message - } - else - { - // Get highest priority message within queue - if (!m_highQueue.empty()) { - msg = m_highQueue.front(); - m_highQueue.pop_front(); - } else { - msg = m_normalQueue.front(); - m_normalQueue.pop_front(); - } - - // Unblock producers now that space is available - if (MAX_QUEUE_SIZE > 0) - { - m_cvNotFull.notify_one(); - } - } - } - - if (!msg) - { - idle.Run(); - continue; - } - - switch (msg->GetId()) - { - case MSG_DISPATCH_DELEGATE: - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - std::lock_guard lock(m_statsMutex); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - } -#endif - - auto delegateMsg = msg->GetData(); - if (delegateMsg) { - auto invoker = delegateMsg->GetInvoker(); - if (invoker) { -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - try { - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled exception in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (...) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled unknown exception in delegate callback." << std::endl; - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - t_self_exit = nullptr; - return; - } -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - if (!selfExit) { - std::lock_guard lock(m_statsMutex); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - } -#endif - } - } - break; - } - - case MSG_EXIT_THREAD: - { - t_self_exit = nullptr; - return; - } - - default: - DMQ_ASSERT(); - break; - } - - // Any message restarts the idle countdown - idle.Restart(); - - // msg goes out of scope here — may trigger self-destruction of 'this'. - // After this point do not access any member; check selfExit in while(). - } - t_self_exit = nullptr; -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -StdlibThread::ThreadStats StdlibThread::SnapshotStats() -{ - // Need m_mutex only for (m_highQueue.size() + m_normalQueue.size()) - size_t currentDepth = GetQueueSize(); - - std::lock_guard lock(m_statsMutex); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = currentDepth; - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = MAX_QUEUE_SIZE; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = (float)std::chrono::duration_cast(m_latencyTotalWindow).count() / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)std::chrono::duration_cast(m_latencyMaxWindow).count() / 1000.0f; - stats.latency_max_all_ms = (float)std::chrono::duration_cast(m_latencyMaxAll).count() / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = dmq::Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = dmq::Duration(0); - - m_invokeTotalWindow = dmq::Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = dmq::Duration(0); - - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_STDLIB diff --git a/DelegateMQ/port/os/stdlib/StdlibThread.h b/DelegateMQ/port/os/stdlib/StdlibThread.h deleted file mode 100644 index e8cb21f..0000000 --- a/DelegateMQ/port/os/stdlib/StdlibThread.h +++ /dev/null @@ -1,311 +0,0 @@ -#ifndef _THREAD_STD_H -#define _THREAD_STD_H - -/// @file StdlibThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Standard C++ implementation of the DelegateMQ IThread interface. -/// -/// @details -/// This class provides a cross-platform implementation of the `IThread` interface using -/// standard C++11 primitives (`std::thread`, `std::mutex`, `std::condition_variable`). -/// It creates a dedicated worker thread with an event loop capable of processing -/// asynchronous delegates and system messages. -/// -/// **Key Features:** -/// * **Priority Queue:** One FIFO `std::deque` per priority level, so high-priority -/// delegate messages (e.g., system signals) are processed before normal ones, and -/// messages of the same priority are processed in the order they were dispatched. -/// * **Queue Full Policy:** Configurable `FullPolicy` (DROP or TIMEOUT), always enforced -- -/// `maxQueueSize == 0` falls back to `dmq::THREAD_DESKTOP_QUEUE_SIZE` rather than disabling -/// the cap, since this port backs its queue with a plain `std::deque` and would otherwise -/// grow without bound if the destination thread is dead/stuck. TIMEOUT waits up to -/// `dispatchTimeout` for the consumer before logging and dropping; DROP silently discards -/// immediately. FAULT (the default) triggers a system fault. -/// * **Watchdog Integration:** Includes a built-in heartbeat mechanism. If the thread loop -/// stalls (deadlock or infinite loop), the watchdog timer detects the failure. -/// * **Synchronized Start:** Uses `std::promise` and `std::future` to ensure the thread -/// is fully initialized and running before `CreateThread()` returns. -/// * **Debug Support:** Sets the native thread name on Windows and Linux to aid -/// debugging in IDEs and tools (Linux truncates names to 15 characters). -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "./extras/util/Timer.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include -#include -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -/// @brief Cross-platform thread for any system supporting C++11 std::thread (e.g. Windows, Linux). -/// @details The StdlibThread class creates a worker thread capable of dispatching and -/// invoking asynchronous delegates. -class StdlibThread : public dmq::IThread -{ - XALLOCATOR -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Constructor - /// @param threadName The name of the thread for debugging. - /// @param maxQueueSize The maximum number of messages allowed in the queue. - /// 0 falls back to dmq::THREAD_DESKTOP_QUEUE_SIZE -- a high-water-mark - /// safety net, not a throughput limiter, against unbounded growth if - /// the destination thread is dead/stuck. - /// @param fullPolicy When the queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - StdlibThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - StdlibThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : StdlibThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - /// Destructor - ~StdlibThread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Called once at program exit to shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - /// Get the ID of this thread instance - std::thread::id GetThreadId(); - - /// Get the ID of the currently executing thread - static std::thread::id GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Get thread name - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get size of thread message queue. - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - /// Dispatch and invoke a delegate target on the destination thread. - /// @param[in] msg - Delegate message containing target function - /// arguments. - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_thread); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_thread); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(!m_thread); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning StdlibThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_thread); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_thread); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_thread); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_thread); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Process() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - StdlibThread(const StdlibThread&) = delete; - StdlibThread& operator=(const StdlibThread&) = delete; - - /// Entry point for the thread - void Process(); - - void SetThreadName(std::thread::native_handle_type handle, const dmq::xstring& name); - - /// Check watchdog is expired. Called by WatchdogCheckAll(), which the application - /// calls periodically, typically from its highest-priority task. Thread-safe. - void WatchdogCheck(); - - /// @brief Returns the head of the watchdog linked list. - static StdlibThread*& GetWatchdogHead(); - - /// @brief Returns the recursive mutex for protecting the watchdog list. - static dmq::RecursiveMutex& GetWatchdogLock(); - - std::optional m_thread; - std::atomic m_exit; - -#ifdef DMQ_ALLOCATOR - std::deque, stl_allocator>> m_highQueue; - std::deque, stl_allocator>> m_normalQueue; -#else - std::deque> m_highQueue; - std::deque> m_normalQueue; -#endif - std::mutex m_mutex; - std::condition_variable m_cv; - - // Condition variable to wake up blocked producers when space is available - std::condition_variable m_cvNotFull; - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - - // Max queue size (0 = unlimited) - const size_t MAX_QUEUE_SIZE; - - // Policy when queue is full - const FullPolicy FULL_POLICY; - - // Timeout duration for TIMEOUT policy - const dmq::Duration m_dispatchTimeout; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - - // Promise and future to synchronize thread start (constructed lazily in CreateThread) - std::optional> m_threadStartPromise; - std::optional> m_threadStartFuture; - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - StdlibThread* m_watchdogNext = nullptr; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - -#if defined(DMQ_DATABUS_TOOLS) - // Separate mutex for statistics to reduce contention on m_mutex - std::mutex m_statsMutex; - - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the stdlib port. -using Thread = StdlibThread; - -} // namespace dmq::os - - -#endif diff --git a/DelegateMQ/port/os/threadx/ThreadXClock.h b/DelegateMQ/port/os/threadx/ThreadXClock.h deleted file mode 100644 index 7cce0ad..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXClock.h +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef THREADX_CLOCK_H -#define THREADX_CLOCK_H - -#include "tx_api.h" -#include -#include - -namespace dmq::os { - struct ThreadXClock { - // 1. Define duration traits - using rep = int64_t; - using period = std::milli; - using duration = std::chrono::duration; - using time_point = std::chrono::time_point; - static const bool is_steady = true; - - // 2. The critical "now()" function - static time_point now() noexcept { - static ULONG last = 0; - static uint64_t high = 0; - - // Enter Critical Section - // This prevents other threads (and ISRs) from interrupting - // the read-modify-write of 'last' and 'high'. - TX_INTERRUPT_SAVE_AREA - TX_DISABLE - - ULONG cur = tx_time_get(); - - constexpr uint64_t TICK_MODULO = static_cast(1ULL) << (sizeof(ULONG) * 8); - - if (cur < last) { - high += TICK_MODULO; - } - - last = cur; - - // Capture value before re-enabling interrupts - uint64_t ticks = high + cur; - - // Exit Critical Section - TX_RESTORE - - // tx_time_get() counts ThreadX ticks (TX_TIMER_TICKS_PER_SECOND - // per second), not milliseconds -- scale before returning, or - // every duration/deadline computed against this clock (e.g. - // dmq::util::Timer expirations) would run TX_TIMER_TICKS_PER_SECOND/1000x - // slower than requested. - uint64_t ms = (ticks * 1000ULL) / TX_TIMER_TICKS_PER_SECOND; - - return time_point(duration(static_cast(ms))); - } - }; -} // namespace dmq::os - -#endif // THREADX_CLOCK_H \ No newline at end of file diff --git a/DelegateMQ/port/os/threadx/ThreadXConditionVariable.h b/DelegateMQ/port/os/threadx/ThreadXConditionVariable.h deleted file mode 100644 index 5a2f699..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXConditionVariable.h +++ /dev/null @@ -1,113 +0,0 @@ -#ifndef THREADX_CONDITION_VARIABLE_H -#define THREADX_CONDITION_VARIABLE_H - -#include "tx_api.h" -#include - -namespace dmq::os { - /// @brief Production-grade wrapper around ThreadX Semaphore to mimic std::condition_variable - /// @details - /// - Uses a Counting Semaphore (initialized to 0). - /// - ISR-safe notification logic (tx_semaphore_put). - /// - Robust tick overflow handling using elapsed time subtraction. - /// - /// @note Limitation: Unlike std::cv, a semaphore retains its signal state. - /// If notify() occurs before wait(), the wait will effectively "fall through". - class ThreadXConditionVariable - { - public: - ThreadXConditionVariable() - { - // Create a semaphore with initial count 0. - // Cast string literal to (CHAR*) to satisfy strict C++ compilers interfacing with C API. - UINT status = tx_semaphore_create(&m_sem, (CHAR*)"DMQ_CondVar", 0); - DMQ_ASSERT_TRUE(status == TX_SUCCESS); - } - - ~ThreadXConditionVariable() - { - tx_semaphore_delete(&m_sem); - } - - ThreadXConditionVariable(const ThreadXConditionVariable&) = delete; - ThreadXConditionVariable& operator=(const ThreadXConditionVariable&) = delete; - - /// @brief Wake up one waiting thread (ISR Safe) - void notify_one() noexcept - { - // ThreadX tx_semaphore_put is ISR-safe. - // It increments the semaphore count. - tx_semaphore_put(&m_sem); - } - - /// @brief Wait indefinitely until predicate is true - template - void wait(Lock& lock, Predicate pred) - { - while (!pred()) - { - lock.unlock(); - // Wait indefinitely - tx_semaphore_get(&m_sem, TX_WAIT_FOREVER); - lock.lock(); - } - } - - /// @brief Wait until predicate is true or timeout expires - template - bool wait_for(Lock& lock, std::chrono::milliseconds timeout, Predicate pred) - { - // 1. Convert timeout to ticks safely - // Use unsigned long long to prevent overflow during multiplication (ms * ticks_per_sec) - const ULONG ticksPerSec = TX_TIMER_TICKS_PER_SECOND; - unsigned long long totalTicks = (static_cast(timeout.count()) * ticksPerSec) / 1000ULL; - - // Ensure at least 1 tick if timeout > 0 to avoid immediate timeout - if (totalTicks == 0 && timeout.count() > 0) totalTicks = 1; - - // Cap at ThreadX max wait if necessary, though unlikely for ms ranges - const ULONG timeoutTicks = (totalTicks > 0xFFFFFFFF) ? 0xFFFFFFFF : (ULONG)totalTicks; - - const ULONG startTick = tx_time_get(); - - while (!pred()) - { - ULONG now = tx_time_get(); - - // Overflow-safe subtraction (works because ULONG is unsigned) - ULONG elapsed = now - startTick; - - if (elapsed >= timeoutTicks) - return pred(); // Timeout expired - - ULONG remaining = timeoutTicks - elapsed; - - lock.unlock(); - - // Wait for the semaphore or timeout - UINT res = tx_semaphore_get(&m_sem, remaining); - - lock.lock(); - - if (res != TX_SUCCESS) - { - // TX_NO_INSTANCE (0x0D) or TX_WAIT_ABORTED means we didn't get the token. - // Timeout occurred or wait aborted. - return pred(); - } - - // If res == TX_SUCCESS, we consumed a token. - // Loop around and check pred() again. - // If pred() is false, we consumed a signal intended for state that isn't ready, - // effectively acting as a "spurious wakeup" handler. - } - - return true; - } - - private: - TX_SEMAPHORE m_sem; - }; -} // namespace dmq::os - -#endif // THREADX_CONDITION_VARIABLE_H \ No newline at end of file diff --git a/DelegateMQ/port/os/threadx/ThreadXCriticalSection.h b/DelegateMQ/port/os/threadx/ThreadXCriticalSection.h deleted file mode 100644 index 35f7ea7..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXCriticalSection.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef THREADX_CRITICAL_SECTION_H -#define THREADX_CRITICAL_SECTION_H - -/// @file ThreadXCriticalSection.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ISR-safe critical section for ThreadX. -/// -/// @details -/// ThreadX's TX_MUTEX cannot be used from a genuine hardware ISR: both -/// tx_mutex_create() and tx_mutex_get() check TX_THREAD_GET_SYSTEM_STATE() -/// and return TX_CALLER_ERROR when called from interrupt context (verified -/// directly against common/src/txe_mutex_create.c and txe_mutex_get.c). -/// This type exists for the narrow set of call sites that must work from -/// BOTH thread and ISR context -- currently dmq::util::Timer's internal -/// list lock, since dmq::util::Timer::ProcessTimers() is documented as -/// callable from the highest-priority context available, including a -/// hardware ISR. -/// -/// It works by disabling/restoring interrupts directly, the same underlying -/// mechanism ThreadXClock.h uses via TX_INTERRUPT_SAVE_AREA / TX_DISABLE / -/// TX_RESTORE. This class can't use those macros themselves, though: they -/// declare a local save-area variable whose NAME is port-specific (e.g. -/// "interrupt_save" on most ARM ports, "tx_saved_posture" on Linux/GNU) and -/// only valid within the function that declared it -- fine for ThreadXClock.h, -/// where disable and restore happen in the same function, but lock() and -/// unlock() here are separate calls, so the saved posture must survive in a -/// member variable across the gap. Instead this uses tx_interrupt_control(), -/// the portable, publicly documented ThreadX service for exactly this: it -/// takes the new posture (TX_INT_DISABLE) and returns the previous one to -/// restore later, with no port-specific local variable involved. It's the -/// same interrupt-lockout primitive TX_DISABLE/TX_RESTORE use internally, so -/// it carries the same ISR-safety guarantee. -/// -/// *** NARROW PURPOSE -- DO NOT USE THIS AS A GENERAL-PURPOSE LOCK *** -/// Holding this masks ALL maskable interrupts on the CPU for as long as it -/// is held. Only use it to protect something genuinely tiny and bounded -/// that may be touched from ISR context. Do NOT use it in place of -/// dmq::Mutex / dmq::RecursiveMutex for ordinary thread-to-thread -/// synchronization (e.g. DataBus internals, a Thread's message queue) -- -/// anything that can block, take a while, or run for an unbounded time -/// must not run with interrupts globally masked; that is a real-time -/// correctness bug on hardware, not just a style issue. -/// -/// *** NOT RE-LOCKABLE ON THE SAME INSTANCE *** -/// Unlike dmq::RecursiveMutex, calling lock() twice on the SAME instance -/// without an intervening unlock() is incorrect: the second lock() call -/// overwrites the single saved-interrupt-state member with the (already -/// disabled) inner posture, so the outer unlock() restores the wrong -/// state and interrupts are left disabled permanently. There is no -/// "recursive" variant of this type -- it has no ownership concept to -/// make recursion meaningful, and Timer's own usage never nests. Locking -/// two DIFFERENT instances in proper LIFO lock/unlock order is fine: each -/// instance saves and restores its own interrupt state independently. - -#include "tx_api.h" - -namespace dmq::os { - - // ========================================================================= - // ThreadXCriticalSection - // See the file-level comment above before using this type anywhere new. - // ========================================================================= - class ThreadXCriticalSection { - public: - ThreadXCriticalSection() = default; - - void lock() { - m_savedPosture = tx_interrupt_control(TX_INT_DISABLE); - } - - void unlock() { - tx_interrupt_control(m_savedPosture); - } - - // No try_lock(): interrupt masking cannot fail to "acquire", so a - // try_lock() here would always trivially succeed and isn't meaningful. - - ThreadXCriticalSection(const ThreadXCriticalSection&) = delete; - ThreadXCriticalSection& operator=(const ThreadXCriticalSection&) = delete; - - private: - UINT m_savedPosture = 0; - }; - -} // namespace dmq::os - -#endif // THREADX_CRITICAL_SECTION_H diff --git a/DelegateMQ/port/os/threadx/ThreadXDelegateQueue.h b/DelegateMQ/port/os/threadx/ThreadXDelegateQueue.h deleted file mode 100644 index 1efd46f..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXDelegateQueue.h +++ /dev/null @@ -1,253 +0,0 @@ -#ifndef THREADX_DELEGATE_QUEUE_H -#define THREADX_DELEGATE_QUEUE_H - -/// @file ThreadXDelegateQueue.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Thin RAII wrapper around a pair of ThreadX TX_QUEUE primitives used -/// by dmq::os::Thread to carry pending ThreadMsg pointers, with priority -/// support. See the Priority enum in delegate/DelegateMsg.h for the -/// cross-port ordering contract this class must uphold. -/// -/// @details -/// *** DO NOT "SIMPLIFY" THIS BACK TO ONE QUEUE + tx_queue_front_send() *** -/// An earlier version of this class used a single TX_QUEUE and called -/// tx_queue_front_send() for HIGH priority messages. That is WRONG: sending -/// to the front of a single queue makes HIGH messages a LIFO stack relative -/// to each other, not a FIFO lane. Concretely, starting from [Normal1]: -/// 1. HIGH-A sent to front -> [HIGH-A, Normal1] -/// 2. HIGH-B sent to front -> [HIGH-B, HIGH-A, Normal1] -/// The consumer then dequeues HIGH-B before HIGH-A, even though A arrived -/// first -- exactly backwards. See DelegateMsg.h's Priority comment for the -/// required contract (HIGH jumps ahead of NORMAL, but FIFO is preserved -/// within each priority). -/// -/// The fix: two independent TX_QUEUE instances, one per priority lane, each -/// always pushed to the BACK (tx_queue_send, never tx_queue_front_send). -/// ThreadX gives no way to block on "either of two queues has data" the way -/// a std::condition_variable can wait on an arbitrary predicate, so a -/// TX_SEMAPHORE counting semaphore is used as a shared "doorbell": every -/// successful Send() (to either lane) puts the semaphore once; Receive() -/// gets the semaphore (the single blocking wait) and then does a -/// non-blocking pop, checking the HIGH lane first so it still drains ahead -/// of NORMAL. This mirrors StdlibThread's two-std::deque + one- -/// condition_variable design and ZephyrDelegateQueue's two-k_msgq + k_poll -/// design -- same shape, RTOS-native primitives. -/// -/// Each lane is sized to the full requested 'capacity' (like -/// ZephyrDelegateQueue), so worst-case combined depth is 2x capacity rather -/// than exactly capacity -- this doubles queue memory relative to the old -/// single-queue design. Unlike FreeRTOS's counting semaphore, ThreadX's -/// tx_semaphore_create() has no "max count" ceiling to size -- a put() only -/// fails on ULONG overflow, which combined lane capacity never approaches. -/// -/// Isolates the native tx_queue_create/tx_queue_send/tx_queue_receive/ -/// tx_queue_delete/tx_semaphore_create/tx_semaphore_put/tx_semaphore_get -/// calls (and the ULONG-word buffer sizing they require) behind a small type -/// so Thread.cpp's DispatchDelegate()/Run() read as policy and dispatch -/// logic, not ThreadX API plumbing. This class owns no policy decisions of -/// its own (FullPolicy, timeout computation, and stats stay in Thread.cpp) -/// -- it only knows how to move ThreadMsg* pointers through two -/// fixed-capacity ThreadX queues in priority order. - -#include -#include "port/os/common/ThreadMsg.h" -#include -#include -#include - -namespace dmq::os { - -class ThreadXDelegateQueue -{ -public: - ThreadXDelegateQueue() - { - memset(&m_highQueue, 0, sizeof(m_highQueue)); - memset(&m_normalQueue, 0, sizeof(m_normalQueue)); - memset(&m_countSem, 0, sizeof(m_countSem)); - } - ~ThreadXDelegateQueue() { Destroy(); } - - ThreadXDelegateQueue(const ThreadXDelegateQueue&) = delete; - ThreadXDelegateQueue& operator=(const ThreadXDelegateQueue&) = delete; - - /// Create the underlying HIGH and NORMAL queues, each with room for - /// 'capacity' pointers, plus the counting semaphore doorbell (initial - /// count 0). - /// @param name Queue/semaphore name; ThreadX stores this pointer, not a - /// copy, so it must outlive the queue (callers pass THREAD_NAME.c_str(), - /// which lives as long as the owning Thread). The same name is shared - /// across both queues and the semaphore -- ThreadX names are purely - /// informational for kernel-aware debuggers and need not be unique. - /// @return true on success, false if any buffer allocation or ThreadX - /// create call failed. - bool Create(size_t capacity, const char* name) - { - if (m_highQueue.tx_queue_id != 0 && m_normalQueue.tx_queue_id != 0 && m_countSem.tx_semaphore_id != 0) - return true; - - // ThreadX queues store "words" (ULONGs). We're passing a pointer - // (ThreadMsg*), so round up to enough words to hold one. - UINT msgSizeWords = (sizeof(ThreadMsg*) + sizeof(ULONG) - 1) / sizeof(ULONG); - ULONG queueMemSizeWords = static_cast(capacity) * msgSizeWords; - - // Queue buffers use new (std::nothrow) for the same reason as the thread - // stack (see ThreadXThread::CreateThread()): ThreadX needs caller-supplied - // memory, and multi-KB buffers don't belong in the fixed-block allocator. - // - // On any failure below, Destroy() deletes whatever was already created - // and frees the buffers, so a later Create() never re-creates a live - // queue or frees memory a live queue still uses. - m_highQueueMemory.reset(new (std::nothrow) ULONG[queueMemSizeWords]); - m_normalQueueMemory.reset(new (std::nothrow) ULONG[queueMemSizeWords]); - if (!m_highQueueMemory || !m_normalQueueMemory) { - Destroy(); - return false; - } - - UINT ret = tx_queue_create(&m_highQueue, - const_cast(name), - msgSizeWords, - m_highQueueMemory.get(), - queueMemSizeWords * sizeof(ULONG)); - if (ret != TX_SUCCESS) { - Destroy(); - return false; - } - - ret = tx_queue_create(&m_normalQueue, - const_cast(name), - msgSizeWords, - m_normalQueueMemory.get(), - queueMemSizeWords * sizeof(ULONG)); - if (ret != TX_SUCCESS) { - Destroy(); - return false; - } - - ret = tx_semaphore_create(&m_countSem, const_cast(name), 0); - if (ret != TX_SUCCESS) { - Destroy(); - return false; - } - return true; - } - - bool IsCreated() const - { - return m_highQueue.tx_queue_id != 0 && m_normalQueue.tx_queue_id != 0 && m_countSem.tx_semaphore_id != 0; - } - - /// Send a message pointer. 'highPriority' routes to the HIGH lane, which - /// Receive() always drains first; otherwise the NORMAL lane. Both lanes - /// are always pushed to the BACK -- see the file-level comment for why - /// "send to front" must never be reintroduced here. 'waitOption' is - /// TX_NO_WAIT for non-blocking, TX_WAIT_FOREVER to block forever, or a - /// finite tick count for a bounded wait; it applies only to the queue - /// push (each lane has its own independent capacity -- there is no - /// combined-depth wait across both). Putting the doorbell semaphore never - /// blocks and cannot realistically fail (only on ULONG overflow, far - /// beyond any real combined lane capacity). - /// @return true if the message was enqueued. - bool Send(ThreadMsg* msg, bool highPriority, ULONG waitOption) - { - TX_QUEUE* q = highPriority ? &m_highQueue : &m_normalQueue; - if (tx_queue_send(q, &msg, waitOption) != TX_SUCCESS) - return false; - tx_semaphore_put(&m_countSem); - return true; - } - - /// Receive a message pointer, blocking up to 'waitOption'. The HIGH lane - /// is always checked -- and drained -- first, so a pending HIGH message - /// is returned even if NORMAL messages arrived earlier. Blocks on the - /// doorbell semaphore (the single native wait), then does a - /// non-blocking pop from whichever lane has data; the semaphore count - /// guarantees at least one lane is non-empty once the get succeeds. - /// @return the message, or nullptr on timeout. - ThreadMsg* Receive(ULONG waitOption) - { - if (tx_semaphore_get(&m_countSem, waitOption) != TX_SUCCESS) - return nullptr; // timed out waiting for either lane - - ThreadMsg* msg = nullptr; - if (tx_queue_receive(&m_highQueue, &msg, TX_NO_WAIT) == TX_SUCCESS) - return msg; - if (tx_queue_receive(&m_normalQueue, &msg, TX_NO_WAIT) == TX_SUCCESS) - return msg; - return nullptr; - } - - /// Combined number of messages waiting across both lanes. - size_t Size() - { - if (m_highQueue.tx_queue_id == 0 || m_normalQueue.tx_queue_id == 0) - return 0; - - ULONG enqueued = 0; - ULONG available = 0; - TX_THREAD* suspension_list = nullptr; - ULONG suspension_count = 0; - TX_QUEUE* next_queue = nullptr; - size_t total = 0; - - if (tx_queue_info_get(&m_highQueue, nullptr, &enqueued, &available, - &suspension_list, &suspension_count, &next_queue) == TX_SUCCESS) { - total += static_cast(enqueued); - } - if (tx_queue_info_get(&m_normalQueue, nullptr, &enqueued, &available, - &suspension_list, &suspension_count, &next_queue) == TX_SUCCESS) { - total += static_cast(enqueued); - } - return total; - } - - /// Remove and delete every pending message in both lanes without - /// blocking. Used during shutdown once the owning thread has stopped - /// consuming the queues. - /// Each message is canceled first (CancelThreadMsg()), releasing a sender - /// blocked waiting on it. - void DrainAndDelete() - { - ThreadMsg* msg = nullptr; - while (tx_queue_receive(&m_highQueue, &msg, TX_NO_WAIT) == TX_SUCCESS) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - while (tx_queue_receive(&m_normalQueue, &msg, TX_NO_WAIT) == TX_SUCCESS) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - } - - void Destroy() - { - if (m_highQueue.tx_queue_id != 0) { - tx_queue_delete(&m_highQueue); - memset(&m_highQueue, 0, sizeof(m_highQueue)); - } - if (m_normalQueue.tx_queue_id != 0) { - tx_queue_delete(&m_normalQueue); - memset(&m_normalQueue, 0, sizeof(m_normalQueue)); - } - if (m_countSem.tx_semaphore_id != 0) { - tx_semaphore_delete(&m_countSem); - memset(&m_countSem, 0, sizeof(m_countSem)); - } - m_highQueueMemory.reset(); - m_normalQueueMemory.reset(); - } - -private: - TX_QUEUE m_highQueue; - TX_QUEUE m_normalQueue; - TX_SEMAPHORE m_countSem; - std::unique_ptr m_highQueueMemory; - std::unique_ptr m_normalQueueMemory; -}; - -} // namespace dmq::os - -#endif // THREADX_DELEGATE_QUEUE_H diff --git a/DelegateMQ/port/os/threadx/ThreadXMutex.h b/DelegateMQ/port/os/threadx/ThreadXMutex.h deleted file mode 100644 index 40cb20c..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXMutex.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef THREADX_MUTEX_H -#define THREADX_MUTEX_H - -#include "tx_api.h" - -namespace dmq::os { - - // ========================================================================= - // ThreadXMutex - // Wraps TX_MUTEX. - // ========================================================================= - class ThreadXMutex { - public: - ThreadXMutex() { - // Cast string literal to (CHAR*) for strict compliance - UINT status = tx_mutex_create(&m_mutex, (CHAR*)"DMQ_Mutex", TX_INHERIT); - DMQ_ASSERT_TRUE(status == TX_SUCCESS); - } - - ~ThreadXMutex() { - tx_mutex_delete(&m_mutex); - } - - void lock() { - tx_mutex_get(&m_mutex, TX_WAIT_FOREVER); - } - - // REQUIRED for std::unique_lock compatibility - bool try_lock() { - return tx_mutex_get(&m_mutex, TX_NO_WAIT) == TX_SUCCESS; - } - - void unlock() { - tx_mutex_put(&m_mutex); - } - - ThreadXMutex(const ThreadXMutex&) = delete; - ThreadXMutex& operator=(const ThreadXMutex&) = delete; - - private: - TX_MUTEX m_mutex; - }; - - // ThreadX Mutexes are recursive by default, so this alias is valid. - using ThreadXRecursiveMutex = ThreadXMutex; -} // namespace dmq::os - -#endif // THREADX_MUTEX_H \ No newline at end of file diff --git a/DelegateMQ/port/os/threadx/ThreadXThisThread.h b/DelegateMQ/port/os/threadx/ThreadXThisThread.h deleted file mode 100644 index 6656685..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXThisThread.h +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef THREADX_THIS_THREAD_H -#define THREADX_THIS_THREAD_H - -/// @file ThreadXThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Portable sleep_for()/yield() for the calling thread, ThreadX backend. -/// -/// @details -/// This is dmq::ThisThread for this port (see DelegateOpt.h). GetCurrent() -/// uses RegistryCurrentThread, keyed by the calling thread's control block. Exists so -/// library internals that need to delay or yield (e.g. RetryMonitor backoff) -/// aren't forced to pull in the full dmq::os::Thread class -- which also -/// drags in the message queue, watchdog, and stats machinery -- just to -/// sleep. dmq::os::Thread::Sleep() forwards here too, so the ThreadX delay -/// call is implemented exactly once. - -#include -#include "ThreadXMutex.h" -#include "port/os/common/CurrentThreadStorage.h" -#include - -namespace dmq::os { - - /// @brief Key for RegistryCurrentThread: the calling thread's control block. - /// @TODO: Return 0 inside an ISR if your target can detect it (e.g. read IPSR on - /// ARM Cortex-M). tx_thread_identify() returns the interrupted thread there, so - /// dmq::ThisThread::GetCurrent() from an ISR returns that thread's IThread - /// instead of nullptr. See docs/PORTING.md, "Current Thread". - inline uintptr_t ThreadXCurrentThreadKey() { - return reinterpret_cast(tx_thread_identify()); - } - - struct ThreadXThisThread : RegistryCurrentThread { - template - static void sleep_for(std::chrono::duration d) { - const auto ms = std::chrono::duration_cast(d); - auto count = ms.count(); - // Round up so a sub-tick sleep still yields the CPU for at least - // one tick rather than returning immediately. - ULONG ticks = static_cast((count * TX_TIMER_TICKS_PER_SECOND) / 1000); - if (ticks == 0 && count > 0) ticks = 1; - tx_thread_sleep(ticks); - } - - static void yield() noexcept { - // ThreadX has no separate "yield" API -- relinquish is the - // documented way to hand the CPU to other ready threads of the - // same priority. - tx_thread_relinquish(); - } - }; - -} // namespace dmq::os - -#endif // THREADX_THIS_THREAD_H diff --git a/DelegateMQ/port/os/threadx/ThreadXThread.cpp b/DelegateMQ/port/os/threadx/ThreadXThread.cpp deleted file mode 100644 index 932445c..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXThread.cpp +++ /dev/null @@ -1,761 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_THREADX is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_THREADX) - -#include "DelegateMQ.h" -#include "ThreadXThread.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include -#include // for memset -#include // for std::nothrow - -// Define DMQ_ASSERT_TRUE if not already defined -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(x) if(!(x)) { while(1); } // Replace with your fault handler -#endif - -namespace dmq::os { - -using namespace dmq; -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// Thread Constructor -//---------------------------------------------------------------------------- -ThreadXThread::ThreadXThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , m_queueSize((maxQueueSize == 0) ? DEFAULT_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - // Zero out control blocks for safety (m_queue zeroes its own control - // block in ThreadXDelegateQueue's constructor) - memset(&m_thread, 0, sizeof(m_thread)); - memset(&m_exitSem, 0, sizeof(m_exitSem)); - memset(&m_startSem, 0, sizeof(m_startSem)); - -#if defined(DMQ_DATABUS_TOOLS) - tx_mutex_create(&m_statMutex, (CHAR*)"StatMutex", TX_NO_INHERIT); -#endif - - // Default Priority - m_priority = static_cast(dmq::THREADX_THREAD_PRIORITY); // DMQ_THREADX_THREAD_PRIORITY -} - -//---------------------------------------------------------------------------- -// Thread Destructor -//---------------------------------------------------------------------------- -ThreadXThread::~ThreadXThread() -{ - // Deleting a ThreadXThread from one of its own callbacks is not supported: the - // destructor would free the stack and control block the thread is still - // running on, and ThreadX/Zephyr (unlike FreeRTOS, whose idle task frees a - // self-deleted task's stack) have no way to free them afterwards. Fault - // immediately instead of corrupting memory. To stop a thread from inside - // its own callback, call ExitThread() and delete the object from another - // thread. - if (m_thread.tx_thread_id != 0 && tx_thread_identify() == &m_thread) - DMQ_ASSERT(); - - ExitThread(); - - const dmq::LockGuard lock(GetWatchdogLock()); - ThreadXThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } - -#if defined(DMQ_DATABUS_TOOLS) - tx_mutex_delete(&m_statMutex); -#endif - - // Guard against deleting invalid semaphore - if (m_exitSem.tx_semaphore_id != 0) { - tx_semaphore_delete(&m_exitSem); - } - if (m_startSem.tx_semaphore_id != 0) { - tx_semaphore_delete(&m_startSem); - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool ThreadXThread::CreateThread(std::optional watchdogTimeout) -{ - // Check if thread is already created (tx_thread_id is non-zero if created) - if (m_thread.tx_thread_id == 0) - { - // Reset from a previous ExitThread(), so the thread can be created again - m_exit.store(false); - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - m_discard.store(false); - - // 0. Create Synchronization Semaphore (Critical for cleanup) - if (m_exitSem.tx_semaphore_id == 0) { - tx_semaphore_create(&m_exitSem, (CHAR*)"ExitSem", 0); - } - if (m_startSem.tx_semaphore_id == 0) { - tx_semaphore_create(&m_startSem, (CHAR*)"StartSem", 0); - } - - // Called from a thread, CreateThread() waits for the start handler. From - // tx_application_define() (no current thread) it cannot block; the start - // handler then runs when the kernel starts, still before any message. - m_startSync = (tx_thread_identify() != TX_NULL); - - // --- 1. Create Queue --- - DMQ_ASSERT_TRUE(m_queue.Create(m_queueSize, THREAD_NAME.c_str())); - - // --- 2. Create Thread --- - // Stack must be ULONG aligned. - - // Stack Size Rounding - ULONG stackSizeWords = (STACK_SIZE + sizeof(ULONG) - 1) / sizeof(ULONG); - - // ThreadX requires the caller to supply this memory. It's allocated with - // new (std::nothrow) on purpose (the CLAUDE.md "no new" rule allows a - // justified exception): the fixed-block allocator is sized for small - // objects and has a limited number of size classes - // (DMQ_XALLOCATOR_MAX_ALLOCATORS), so multi-KB buffers would exhaust it, - // and a ThreadX byte pool would require the application to create one. - // Allocated once per CreateThread(), freed by ExitThread()/the destructor. - m_stackMemory.reset(new (std::nothrow) ULONG[stackSizeWords]); - if (!m_stackMemory) - BAD_ALLOC(); - - UINT ret = tx_thread_create(&m_thread, - (CHAR*)THREAD_NAME.c_str(), - &ThreadXThread::Process, - 0, // Unused: see GetInstanceRegistry() - m_stackMemory.get(), - stackSizeWords * sizeof(ULONG), - m_priority, - m_priority, - TX_NO_TIME_SLICE, - TX_DONT_START); - - if (ret == TX_SUCCESS) { - // Register before resuming: the thread must never be able to run - // (and call Process()) before its registry entry exists. - { - const dmq::LockGuard lock(GetInstanceRegistryLock()); - GetInstanceRegistry()[&m_thread] = this; - } - tx_thread_resume(&m_thread); - - // Wait for the start handler to complete - if (m_startSync) - tx_semaphore_get(&m_startSem, TX_WAIT_FOREVER); - } - - DMQ_ASSERT_TRUE(ret == TX_SUCCESS); - - m_lastAliveTime.store(Timer::GetNow()); - - if (watchdogTimeout.has_value()) - { - - const dmq::LockGuard lock(GetWatchdogLock()); - - // Add to watchdog registry if not already present - bool found = false; - ThreadXThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// SetThreadPriority -//---------------------------------------------------------------------------- -void ThreadXThread::SetThreadPriority(UINT priority) -{ - m_priority = priority; - - // If the thread is already running, update it live - if (m_thread.tx_thread_id != 0) { - UINT oldPriority; - tx_thread_priority_change(&m_thread, m_priority, &oldPriority); - } -} - -//---------------------------------------------------------------------------- -// GetThreadPriority -//---------------------------------------------------------------------------- -UINT ThreadXThread::GetThreadPriority() -{ - return m_priority; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void ThreadXThread::ExitThread(ExitPolicy policy) -{ - if (m_queue.IsCreated()) - { - // Set before m_exit: Run() reads it for every message ahead of the exit message - m_discard.store(policy == ExitPolicy::DISCARD); - m_exit.store(true); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Determine self-exit BEFORE attempting to enqueue the exit message. - // If this thread is destroying itself from within its own dispatched - // callback, it is not consuming its own queue right now -- it is - // blocked here, inside ExitThread(). A blocking tx_queue_send() would - // deadlock forever if the queue happened to be full. No message needs - // to be queued in that case: Run()'s dispatch loop already checks - // m_selfExitPtr immediately after the current callback invoke - // returns, and unwinds without touching 'this' again. - // - // A self-exiting thread must also NOT do the cleanup below: it is still - // running on m_stackMemory with m_thread linked in the kernel, so - // deleting the queue, wiping m_thread or freeing the stack here would - // corrupt ThreadX state. Set the flags and return; the cleanup runs in a - // later ExitThread() from another thread (typically ~ThreadXThread()), - // which sees m_selfExited and waits for the thread to finish instead of - // doing the exit-message handshake. Same approach as ZephyrThread. - TX_THREAD* currentThread = tx_thread_identify(); - bool isSelfExit = (currentThread == &m_thread); - - if (isSelfExit) { - m_selfExited.store(true); - if (m_selfExitPtr) { *m_selfExitPtr = true; m_selfExitPtr = nullptr; } - m_startGate.Leave(); // exited from its start handler: never reaches the gate - // Self-exit: this thread runs no more messages, and the object may be - // destroyed once this handler returns. Stop watchdog checks now. - m_watchdogTimeout.store(dmq::Duration(0)); - return; - } - - if (m_selfExited.load()) { - // The thread self-exited earlier and is returning (or has returned) - // from Run() on its own, possibly still running its exit handler. - // Wait until ThreadX marks it finished before terminating/deleting - // it below. Not from an ISR: there it can't block, as above. - if (currentThread != nullptr) { - UINT state = TX_READY; - while (tx_thread_info_get(&m_thread, nullptr, &state, nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr) == TX_SUCCESS - && state != TX_COMPLETED && state != TX_TERMINATED) { - tx_thread_sleep(1); - } - } - } else { - // Send exit message - ThreadMsg* msg = new (std::nothrow) ThreadMsg(MSG_EXIT_THREAD); - if (msg) - { - // Wait forever to ensure message is sent - if (!m_queue.Send(msg, /*highPriority=*/false, TX_WAIT_FOREVER)) - { - delete msg; // Failed to send, prevent leak - } - } - - // If tx_thread_identify() returns NULL (ISR context), we shouldn't block. - if (currentThread != nullptr) { - // Wait for Run() to signal completion - tx_semaphore_get(&m_exitSem, TX_WAIT_FOREVER); - } - } - - // Force terminate if still running (safety net) - // tx_thread_terminate returns TX_SUCCESS if terminated or TX_THREAD_ERROR if already terminated - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - tx_thread_terminate(&m_thread); - tx_thread_delete(&m_thread); - - m_queue.DrainAndDelete(); - m_queue.Destroy(); - - // Remove the registry entry before clearing/reusing the control block - // (see GetInstanceRegistry() for why this exists). - { - const dmq::LockGuard lock(GetInstanceRegistryLock()); - GetInstanceRegistry().erase(&m_thread); - } - - // Clear control block so CreateThread could potentially be called again - memset(&m_thread, 0, sizeof(m_thread)); - m_selfExited.store(false); - } -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -TX_THREAD* ThreadXThread::GetThreadId() -{ - return &m_thread; -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -TX_THREAD* ThreadXThread::GetCurrentThreadId() -{ - return tx_thread_identify(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool ThreadXThread::IsCurrentThread() -{ - return GetThreadId() == GetCurrentThreadId(); -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t ThreadXThread::GetQueueSize() -{ - return m_queue.Size(); -} - -void ThreadXThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool ThreadXThread::DispatchDelegate(std::shared_ptr msg) -{ - // Safety check if queue is valid - if (!m_queue.IsCreated()) return false; - - // Allocate message container - ThreadMsg* threadMsg = new (std::nothrow) ThreadMsg(MSG_DISPATCH_DELEGATE, msg); - if (!threadMsg) - { - // OOM: drop the message - return false; - } -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // Compute wait option based on policy. - ULONG wait_option; - if (FULL_POLICY == FullPolicy::TIMEOUT) - wait_option = (static_cast(std::chrono::duration_cast(m_dispatchTimeout).count()) * TX_TIMER_TICKS_PER_SECOND) / 1000; - else - wait_option = TX_NO_WAIT; // DROP and FAULT: non-blocking - - // High priority routes to the HIGH lane (drained before NORMAL), preserving - // FIFO order within each lane -- see ThreadXDelegateQueue.h for why this is - // NOT tx_queue_front_send (that would make HIGH messages LIFO, not FIFO). - bool sent = m_queue.Send(threadMsg, msg->GetPriority() == Priority::HIGH, wait_option); - - if (!sent) - { - if (FULL_POLICY == FullPolicy::FAULT) { - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(sent); - } else if (FULL_POLICY == FullPolicy::TIMEOUT) { - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } else { // DROP - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } - delete threadMsg; // Failed to enqueue, prevent leak - return false; - } - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - tx_mutex_get(&m_statMutex, TX_WAIT_FOREVER); - size_t currentDepth = GetQueueSize(); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - tx_mutex_put(&m_statMutex); -#endif - - return true; -} - -//---------------------------------------------------------------------------- -// Process (Static Entry Point) -//---------------------------------------------------------------------------- -void ThreadXThread::Process(ULONG /*instance*/) -{ - ThreadXThread* thread = nullptr; - { - const dmq::LockGuard lock(GetInstanceRegistryLock()); - auto it = GetInstanceRegistry().find(tx_thread_identify()); - if (it != GetInstanceRegistry().end()) - thread = it->second; - } - - DMQ_ASSERT_TRUE(thread != nullptr); - thread->Run(); -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void ThreadXThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void ThreadXThread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void ThreadXThread::WatchdogCheckAll() -{ - const dmq::LockGuard lock(GetWatchdogLock()); - ThreadXThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// GetInstanceRegistry -//---------------------------------------------------------------------------- -dmq::xmap& ThreadXThread::GetInstanceRegistry() -{ - static dmq::xmap registry; - return registry; -} - -//---------------------------------------------------------------------------- -// GetInstanceRegistryLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& ThreadXThread::GetInstanceRegistryLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -ThreadXThread*& ThreadXThread::GetWatchdogHead() -{ - static ThreadXThread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& ThreadXThread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -//---------------------------------------------------------------------------- -// Run (Member Function Loop) -//---------------------------------------------------------------------------- -void ThreadXThread::Run() -{ - bool selfExit = false; - m_selfExitPtr = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Reset - // before the exit handler runs (and destroyed before exitGuard on a - // self-exit), so the exit handler sees nullptr. - std::optional currentScope; - currentScope.emplace(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - if (m_startSync) - tx_semaphore_put(&m_startSem); - if (exitedInStart) - return; - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - // ExitThread() while held: run nothing. Cancel each queued message - // (DISCARD) until the exit message. Consuming them also keeps - // ExitThread()'s blocking send of the exit message from waiting on a - // full queue. - if (!opened) - m_discard.store(true); - } - - ThreadMsg* msg = nullptr; - while (!selfExit) - { - dmq::Duration timeout; - { - m_lastAliveTime.store(Timer::GetNow()); - timeout = m_watchdogTimeout.load(); - } - - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever to save power. - ULONG waitOption = TX_WAIT_FOREVER; - if (timeout.count() > 0) - { - auto ms = std::chrono::duration_cast(timeout).count(); - waitOption = (static_cast(ms / dmq::WATCHDOG_HEARTBEAT_DIVISOR) * TX_TIMER_TICKS_PER_SECOND) / 1000; - if (waitOption == 0) waitOption = 1; - } - if (idle.Enabled()) - { - auto ms = std::chrono::ceil(idle.WaitTime(dmq::Duration(-1))).count(); - ULONG idleTicks = (static_cast(ms) * TX_TIMER_TICKS_PER_SECOND + 999) / 1000; - if (idleTicks < waitOption) waitOption = idleTicks; - } - - msg = m_queue.Receive(waitOption); - if (!msg) - { - // Exit requested but no exit message arrived (e.g. it could not be allocated) - if (m_exit.load()) - break; - - // Timeout or other failure: run the idle handler if it is due - if (idle.IsDue()) - { - idle.Run(); - // The idle handler exited this thread (and may have deleted it): leave - // without touching 'this', as the message path does - if (selfExit) - return; - } - continue; - } - - int msgId = msg->GetId(); - if (msgId == MSG_DISPATCH_DELEGATE && m_discard.load()) - { - // ExitPolicy::DISCARD: skip messages queued ahead of the exit message - CancelThreadMsg(*msg); - } - else if (msgId == MSG_DISPATCH_DELEGATE) - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - tx_mutex_get(&m_statMutex, TX_WAIT_FOREVER); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - tx_mutex_put(&m_statMutex); - } -#endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - bool success = false; - try { - success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - printf("[Thread:%s] Unhandled exception in delegate callback: %s\n", THREAD_NAME.c_str(), e.what()); - DMQ_ASSERT(); - } - catch (...) { - printf("[Thread:%s] Unhandled unknown exception in delegate callback.\n", THREAD_NAME.c_str()); - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - delete msg; - return; - } - -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - { - tx_mutex_get(&m_statMutex, TX_WAIT_FOREVER); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - tx_mutex_put(&m_statMutex); - } -#endif - } - - delete msg; - - if (msgId == MSG_EXIT_THREAD) { - break; - } - - // Any message restarts the idle countdown - idle.Restart(); - } - - // Run the exit handler before signalling ExitThread(), so it returns only after it - currentScope.reset(); - exitGuard.Fire(); - - // Clear before signalling: once ExitThread() returns, 'this' may be destroyed - m_selfExitPtr = nullptr; - // Signal ExitThread() that the loop has exited - tx_semaphore_put(&m_exitSem); -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -ThreadXThread::ThreadStats ThreadXThread::SnapshotStats() -{ - tx_mutex_get(&m_statMutex, TX_WAIT_FOREVER); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = GetQueueSize(); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = m_queueSize; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = (float)std::chrono::duration_cast(m_latencyTotalWindow).count() / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)std::chrono::duration_cast(m_latencyMaxWindow).count() / 1000.0f; - stats.latency_max_all_ms = (float)std::chrono::duration_cast(m_latencyMaxAll).count() / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = Duration(0); - - m_invokeTotalWindow = Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = Duration(0); - - tx_mutex_put(&m_statMutex); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_THREADX diff --git a/DelegateMQ/port/os/threadx/ThreadXThread.h b/DelegateMQ/port/os/threadx/ThreadXThread.h deleted file mode 100644 index a1a0910..0000000 --- a/DelegateMQ/port/os/threadx/ThreadXThread.h +++ /dev/null @@ -1,328 +0,0 @@ -#ifndef _THREAD_THREADX_H -#define _THREAD_THREADX_H - -/// @file ThreadXThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ThreadX implementation of the DelegateMQ IThread interface. -/// -/// @details -/// This class provides a concrete implementation of the `IThread` interface using -/// Azure RTOS ThreadX primitives. It enables DelegateMQ to dispatch asynchronous -/// delegates to a dedicated ThreadX thread. -/// -/// @note This implementation is a basic port. For reference, the stdlib and win32 -/// implementations provide additional features: -/// 1. Synchronized Startup: CreateThread() blocks until the worker thread is ready. -/// -/// **Key Features:** -/// * **Task Integration:** Wraps `tx_thread_create` to establish a dedicated worker loop. -/// * **FullPolicy Support:** Configurable back-pressure (DROP or TIMEOUT) when the -/// message queue is full. -/// * **Priority Support:** Normal and High priorities, as two FIFO queue lanes drained -/// HIGH first, so same-priority messages keep dispatch order (see -/// `ThreadXDelegateQueue` for why one queue + `tx_queue_front_send()` is wrong). -/// * **Queue-Based Dispatch:** Uses `ThreadXDelegateQueue` (a thin RAII wrapper -/// around a ThreadX `TX_QUEUE`) to receive and process incoming delegate -/// messages in a thread-safe manner. -/// * **Priority Control:** Supports runtime priority configuration via `SetThreadPriority`. -/// * **Dynamic Configuration:** Allows configuring stack size and queue depth at construction. -/// * **Graceful Shutdown:** Implements robust termination logic using semaphores to ensure -/// the thread exits cleanly before destruction. -/// * **Watchdog Integration:** Optional heartbeat mechanism detects stalled or deadlocked -/// threads. Enable by passing a timeout to CreateThread(). Requires -/// Thread::WatchdogCheckAll() to be called periodically from a context that can preempt -/// watched threads -- the highest-priority task in the system, not an ISR. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include "ThreadXDelegateQueue.h" -#include "extras/util/Timer.h" -#include -#include -#include -#include -#include - -namespace dmq::os { - -using namespace dmq::util; - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -// Comparator for priority (ThreadX priority is 0 to N-1, where 0 is highest) -// This is used for the priority queue if we had one, but ThreadX uses tx_queue_send/tx_queue_front_send. - -class ThreadXThread : public dmq::IThread -{ -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Default queue size if 0 is passed - static const ULONG DEFAULT_QUEUE_SIZE = dmq::DEFAULT_QUEUE_SIZE; - - /// Constructor - /// @param threadName Name for the ThreadX thread - /// @param maxQueueSize Max number of messages in queue (0 = Default dmq::DEFAULT_QUEUE_SIZE) - /// @param fullPolicy Action when queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - ThreadXThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - ThreadXThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : ThreadXThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - /// Destructor - ~ThreadXThread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - /// Get the ID of this thread instance - TX_THREAD* GetThreadId(); - - /// Get the ID of the currently executing thread - static TX_THREAD* GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Set the ThreadX Priority (0 = Highest). - /// Can be called before or after CreateThread(). - void SetThreadPriority(UINT priority); - - /// Get current priority - UINT GetThreadPriority(); - - /// Get thread name - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get current queue size - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - // IThread Interface Implementation - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning ThreadXThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(m_thread.tx_thread_id == 0); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - ThreadXThread(const ThreadXThread&) = delete; - ThreadXThread& operator=(const ThreadXThread&) = delete; - - /// Entry point for the thread - static void Process(ULONG instance); - - // Run loop called by Process - void Run(); - - /// @brief Registry mapping a ThreadX TX_THREAD control block back to its - /// owning ThreadXThread instance. - /// @details ThreadX's tx_thread_create() entry_input parameter is a - /// ULONG, which cannot safely carry a 64-bit 'this' pointer on hosts - /// where ULONG is 32 bits (e.g. this Linux/GNU simulation port) -- - /// reinterpret_cast(this) would truncate it. Process() instead - /// looks up 'this' via tx_thread_identify() against this registry. - /// Entries are added before tx_thread_resume() is called, so Process() - /// can never observe a not-yet-registered thread. - static dmq::xmap& GetInstanceRegistry(); - static dmq::RecursiveMutex& GetInstanceRegistryLock(); - - /// Check watchdog is expired. Called by WatchdogCheckAll(). - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static ThreadXThread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - const size_t m_queueSize; // Stored queue size - const FullPolicy FULL_POLICY; - const dmq::Duration m_dispatchTimeout; - UINT m_priority; // Stored priority - - // ThreadX Control Blocks - TX_THREAD m_thread; - ThreadXDelegateQueue m_queue; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - TX_SEMAPHORE m_exitSem; // Semaphore to signal thread completion - TX_SEMAPHORE m_startSem; // Put by Run() once the start handler has run - bool m_startSync = false; // CreateThread() waits for the start handler (called from a thread) - std::atomic m_exit = false; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - std::atomic m_discard = false; // ExitPolicy::DISCARD: cancel queued messages instead of invoking - bool* m_selfExitPtr = nullptr; - - // Set when ExitThread() is called from this thread itself (see ExitThread()): - // the cleanup is then deferred to a later ExitThread() from another thread. - std::atomic m_selfExited{false}; - - // Stack memory required by ThreadX (Managed by RAII) - // Using ULONG[] ensures correct alignment for the ThreadX stack - std::unique_ptr m_stackMemory; - - // Configurable stack size (bytes) - static const ULONG STACK_SIZE = static_cast(dmq::THREADX_STACK_BYTES); // DMQ_THREADX_STACK_BYTES - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - ThreadXThread* m_watchdogNext = nullptr; - -#if defined(DMQ_DATABUS_TOOLS) - TX_MUTEX m_statMutex; // Mutex to protect statistics - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the ThreadX port. -using Thread = ThreadXThread; - -} // namespace dmq::os - -#endif // _THREAD_THREADX_H diff --git a/DelegateMQ/port/os/win32/Win32Thread.cpp b/DelegateMQ/port/os/win32/Win32Thread.cpp deleted file mode 100644 index 9aaab2d..0000000 --- a/DelegateMQ/port/os/win32/Win32Thread.cpp +++ /dev/null @@ -1,652 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_WIN32 is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_WIN32) && !defined(_WIN32) -#error "DMQ_THREAD_WIN32 is Windows-only. Select another DMQ_THREAD_* port for this target." -#endif -#if defined(DMQ_THREAD_WIN32) - -#include "DelegateMQ.h" -#include "Win32Thread.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include - -namespace dmq::os { - -using namespace dmq::util; - -// Thread-local pointer into Process()'s stack frame. Set non-null only while -// Process() is running on a given thread. ExitThread() writes true through it -// when the thread destroys its own owning object so Process() can exit without -// touching freed members. -static thread_local bool* t_self_exit = nullptr; - -//---------------------------------------------------------------------------- -// Thread -//---------------------------------------------------------------------------- -Win32Thread::Win32Thread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , MAX_QUEUE_SIZE(maxQueueSize == 0 ? dmq::THREAD_DESKTOP_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - InitializeCriticalSection(&m_cs); - InitializeConditionVariable(&m_cvNotEmpty); - InitializeConditionVariable(&m_cvNotFull); -} - -//---------------------------------------------------------------------------- -// ~Thread -//---------------------------------------------------------------------------- -Win32Thread::~Win32Thread() -{ - ExitThread(); - - const std::lock_guard lock(GetWatchdogLock()); - Win32Thread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } - - DeleteCriticalSection(&m_cs); -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool Win32Thread::CreateThread(std::optional watchdogTimeout) -{ - if (m_hThread == NULL) - { - m_exit = false; - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - - // Manual-reset event for startup synchronization - m_hStartEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - - // Created suspended so m_hThread/m_threadId are stored before the thread - // runs: the start handler may call IsCurrentThread() or dispatch to it. - m_hThread = ::CreateThread(NULL, 0, ThreadProc, this, CREATE_SUSPENDED, &m_threadId); - if (m_hThread == NULL) { - m_watchdogTimeout.store(dmq::Duration(0)); // no thread to refresh the heartbeat - m_startGate.OnCreateFailed(); - CloseHandle(m_hStartEvent); - m_hStartEvent = NULL; - return false; - } - - // Set the thread name so it shows in the Visual Studio Debug Location toolbar - std::wstring wname(THREAD_NAME.begin(), THREAD_NAME.end()); - SetThreadDescription(m_hThread, wname.c_str()); - - ResumeThread(m_hThread); - - // Wait for the thread to enter the Process method - WaitForSingleObject(m_hStartEvent, INFINITE); - CloseHandle(m_hStartEvent); - m_hStartEvent = NULL; - - m_lastAliveTime.store(Timer::GetNow()); - - // Caller wants a watchdog timer? - if (watchdogTimeout.has_value()) - { - - // Add to watchdog registry if not already present - { - dmq::LockGuard lock(GetWatchdogLock()); - bool found = false; - Win32Thread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// ThreadProc -//---------------------------------------------------------------------------- -DWORD WINAPI Win32Thread::ThreadProc(LPVOID lpParam) -{ - static_cast(lpParam)->Process(); - return 0; -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool Win32Thread::DispatchDelegate(std::shared_ptr msg) -{ - if (m_exit.load() || m_hThread == NULL) return false; - - EnterCriticalSection(&m_cs); - - // [BACK PRESSURE / DROP / FAULT / TIMEOUT LOGIC] - if (MAX_QUEUE_SIZE > 0 && (m_highQueue.size() + m_normalQueue.size()) >= MAX_QUEUE_SIZE) - { - if (FULL_POLICY == FullPolicy::DROP) - { - size_t depth = m_highQueue.size() + m_normalQueue.size(); - LeaveCriticalSection(&m_cs); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; // silently discard - } - - if (FULL_POLICY == FullPolicy::FAULT) - { - LeaveCriticalSection(&m_cs); - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(false); - return false; - } - - if (FULL_POLICY == FullPolicy::TIMEOUT) - { - DWORD dwTimeout = static_cast( - std::chrono::duration_cast(m_dispatchTimeout).count()); - while ((m_highQueue.size() + m_normalQueue.size()) >= MAX_QUEUE_SIZE && !m_exit.load()) - { - if (!SleepConditionVariableCS(&m_cvNotFull, &m_cs, dwTimeout)) - { - size_t depth = m_highQueue.size() + m_normalQueue.size(); - LeaveCriticalSection(&m_cs); - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(depth); - return false; - } - } - } - } - - // If using XALLOCATOR explicit operator new required. See xallocator.h. - auto threadMsg = xmake_shared(MSG_DISPATCH_DELEGATE, msg); - #if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); - #endif - - // If we woke up because of exit (or exit happened while waiting), abort - if (!m_exit.load()) - { - if (threadMsg->GetPriority() == dmq::Priority::HIGH) - m_highQueue.push_back(threadMsg); - else - m_normalQueue.push_back(threadMsg); - - #if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - size_t currentDepth = (m_highQueue.size() + m_normalQueue.size()); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - #endif - - WakeConditionVariable(&m_cvNotEmpty); - } - else - { - LeaveCriticalSection(&m_cs); - return false; - } - - LeaveCriticalSection(&m_cs); - return true; -} - -//---------------------------------------------------------------------------- -// Process -//---------------------------------------------------------------------------- -void Win32Thread::Process() -{ - // selfExit is set by ExitThread() when the thread destroys its own owner. - // It lives on this stack frame so it remains valid even after 'this' is freed. - bool selfExit = false; - t_self_exit = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Declared - // after exitGuard, so it is cleared again before the exit handler runs. - dmq::CurrentThreadScope currentScope(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - // Signal that the thread has started processing to notify CreateThread - SetEvent(m_hStartEvent); - if (exitedInStart) { t_self_exit = nullptr; return; } - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - if (!opened) - { - // ExitThread() while held: leave without running any message. - // ExitThread() cancels what is still queued once this thread ends. - t_self_exit = nullptr; - return; - } - } - - while (!selfExit) - { - dmq::Duration watchdogTimeout; - { - m_lastAliveTime.store(Timer::GetNow()); - watchdogTimeout = m_watchdogTimeout.load(); - } - - std::shared_ptr msg; - - EnterCriticalSection(&m_cs); - - // Wait for message to be added to the queue. - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever. - DWORD dwTimeout = INFINITE; - if (watchdogTimeout.count() > 0) - { - auto ms = std::chrono::duration_cast(watchdogTimeout).count(); - dwTimeout = static_cast(ms / dmq::WATCHDOG_HEARTBEAT_DIVISOR); - if (dwTimeout == 0) dwTimeout = 1; - } - if (idle.Enabled()) - { - auto untilIdle = std::chrono::ceil(idle.WaitTime(dmq::Duration(-1))).count(); - if (static_cast(untilIdle) < dwTimeout) - dwTimeout = static_cast(untilIdle); - } - - while ((m_highQueue.empty() && m_normalQueue.empty()) && !m_exit.load()) - { - if (!SleepConditionVariableCS(&m_cvNotEmpty, &m_cs, dwTimeout)) - { - if (GetLastError() == ERROR_TIMEOUT) - break; // Timeout reached, break inner while to update m_lastAliveTime - } - } - - // If empty and exit is true, we should exit. - if ((m_highQueue.empty() && m_normalQueue.empty()) && m_exit.load()) - { - LeaveCriticalSection(&m_cs); - break; - } - - // If queue still empty, it means we timed out. Run the idle handler if it is - // due, then loop again to update m_lastAliveTime. - if ((m_highQueue.empty() && m_normalQueue.empty())) - { - LeaveCriticalSection(&m_cs); - if (idle.IsDue()) - idle.Run(); - continue; - } - - // Get highest priority message within queue - if (!m_highQueue.empty()) { - msg = m_highQueue.front(); - m_highQueue.pop_front(); - } else { - msg = m_normalQueue.front(); - m_normalQueue.pop_front(); - } - - // Unblock producers now that space is available - if (MAX_QUEUE_SIZE > 0) - WakeConditionVariable(&m_cvNotFull); - - LeaveCriticalSection(&m_cs); - - switch (msg->GetId()) - { - case MSG_DISPATCH_DELEGATE: - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - EnterCriticalSection(&m_cs); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - LeaveCriticalSection(&m_cs); - } -#endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - try { - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled exception in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (...) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled unknown exception in delegate callback." << std::endl; - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - t_self_exit = nullptr; - return; - } -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - if (!selfExit) { - EnterCriticalSection(&m_cs); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - LeaveCriticalSection(&m_cs); - } -#endif - break; - } - - case MSG_EXIT_THREAD: - { - t_self_exit = nullptr; - return; - } - - default: - { - break; - } - } - - // Any message restarts the idle countdown - idle.Restart(); - } - t_self_exit = nullptr; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void Win32Thread::ExitThread(ExitPolicy policy) -{ - if (m_hThread == NULL) return; - - // Messages taken off the queues without being invoked; canceled outside the lock - decltype(m_highQueue) discardedHigh; - decltype(m_normalQueue) discardedNormal; - - EnterCriticalSection(&m_cs); - - // Set exit flag INSIDE lock before notifying. - // This ensures that when a blocked producer wakes up, it sees m_exit == true immediately. - m_exit.store(true); - - // DISCARD: empty the queues so the exit message is the next one processed - if (policy == ExitPolicy::DISCARD) - { - discardedHigh.swap(m_highQueue); - discardedNormal.swap(m_normalQueue); - } - - // Explicitly allow Exit message to bypass the MAX_QUEUE_SIZE limit. - // We do not wait on m_cvNotFull here to prevent deadlock during shutdown. - // Queued last, so DRAIN invokes every message already queued first. - m_normalQueue.push_back(xmake_shared(MSG_EXIT_THREAD, nullptr)); - - // Wake up consumers - WakeConditionVariable(&m_cvNotEmpty); - - // Wake up blocked producers (DispatchDelegate) - WakeAllConditionVariable(&m_cvNotFull); - - LeaveCriticalSection(&m_cs); - - CancelAll(discardedHigh); - CancelAll(discardedNormal); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Prevent deadlock if ExitThread is called from within the thread itself - if (::GetCurrentThreadId() != m_threadId) - { - WaitForSingleObject(m_hThread, INFINITE); - } - else - { - if (t_self_exit) *t_self_exit = true; - m_startGate.Leave(); // exited from its start handler: never reaches the gate - } - - // Normally empty. After a self-exit the loop returns without draining, - // so anything still queued is discarded here. - EnterCriticalSection(&m_cs); - discardedHigh.swap(m_highQueue); - discardedNormal.swap(m_normalQueue); - LeaveCriticalSection(&m_cs); - CancelAll(discardedHigh); - CancelAll(discardedNormal); - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - CloseHandle(m_hThread); - m_hThread = NULL; -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -DWORD Win32Thread::GetThreadId() { return m_threadId; } - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -DWORD Win32Thread::GetCurrentThreadId() { return ::GetCurrentThreadId(); } - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool Win32Thread::IsCurrentThread() { return GetThreadId() == GetCurrentThreadId(); } - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t Win32Thread::GetQueueSize() -{ - EnterCriticalSection(&m_cs); - size_t size = (m_highQueue.size() + m_normalQueue.size()); - LeaveCriticalSection(&m_cs); - return size; -} - -void Win32Thread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void Win32Thread::WatchdogCheckAll() -{ - const std::lock_guard lock(GetWatchdogLock()); - Win32Thread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void Win32Thread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void Win32Thread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -Win32Thread*& Win32Thread::GetWatchdogHead() -{ - static Win32Thread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& Win32Thread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -Win32Thread::ThreadStats Win32Thread::SnapshotStats() -{ - EnterCriticalSection(&m_cs); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = (m_highQueue.size() + m_normalQueue.size()); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = MAX_QUEUE_SIZE; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = (float)std::chrono::duration_cast(m_latencyTotalWindow).count() / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)std::chrono::duration_cast(m_latencyMaxWindow).count() / 1000.0f; - stats.latency_max_all_ms = (float)std::chrono::duration_cast(m_latencyMaxAll).count() / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = dmq::Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = dmq::Duration(0); - - m_invokeTotalWindow = dmq::Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = dmq::Duration(0); - - LeaveCriticalSection(&m_cs); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_WIN32 diff --git a/DelegateMQ/port/os/win32/Win32Thread.h b/DelegateMQ/port/os/win32/Win32Thread.h deleted file mode 100644 index 2c9ceb5..0000000 --- a/DelegateMQ/port/os/win32/Win32Thread.h +++ /dev/null @@ -1,314 +0,0 @@ -#ifndef _THREAD_WIN32_H -#define _THREAD_WIN32_H - -/// @file Win32Thread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Win32 API implementation of the DelegateMQ IThread interface. -/// -/// @details -/// This class provides a Windows-native implementation of the `IThread` interface using -/// Win32 synchronization primitives (`CRITICAL_SECTION`, `CONDITION_VARIABLE`, `HANDLE`). -/// It creates a dedicated worker thread with an event loop capable of processing -/// asynchronous delegates and system messages. -/// -/// **Key Features:** -/// * **Priority Queue:** One FIFO `std::deque` per priority level, so high-priority -/// delegate messages (e.g., system signals) are processed before normal ones, and -/// messages of the same priority are processed in the order they were dispatched. -/// * **Queue Full Policy:** Configurable `FullPolicy` (DROP, FAULT, or TIMEOUT), always enforced -- -/// `maxQueueSize == 0` falls back to `dmq::THREAD_DESKTOP_QUEUE_SIZE` rather than disabling -/// the cap, since this port backs its queue with a plain `std::deque` and would otherwise -/// grow without bound if the destination thread is dead/stuck. TIMEOUT waits up to -/// `dispatchTimeout` for the consumer before logging and dropping; DROP silently discards -/// immediately. FAULT (the default) triggers a system fault. -/// * **Watchdog Integration:** Includes a built-in heartbeat mechanism. If the thread loop -/// stalls (deadlock or infinite loop), the watchdog timer detects the failure. -/// * **Synchronized Start:** Uses a Win32 manual-reset event to ensure the thread -/// is fully initialized and running before `CreateThread()` returns. -/// * **Debug Support:** Sets the native thread name via `SetThreadDescription()` to -/// aid debugging in Visual Studio. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "./extras/util/Timer.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include -#include -#include -#include - -#ifdef _WIN32 -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#endif - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -/// @brief Windows-native thread for systems using the Win32 API. -/// @details The Win32Thread class creates a worker thread capable of dispatching and -/// invoking asynchronous delegates. -class Win32Thread : public dmq::IThread -{ - XALLOCATOR -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Constructor - /// @param threadName The name of the thread for debugging. - /// @param maxQueueSize The maximum number of messages allowed in the queue. - /// 0 falls back to dmq::THREAD_DESKTOP_QUEUE_SIZE -- a high-water-mark - /// safety net, not a throughput limiter, against unbounded growth if - /// the destination thread is dead/stuck. - /// @param fullPolicy When the queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - Win32Thread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - Win32Thread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : Win32Thread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - /// Destructor - virtual ~Win32Thread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - /// Get the ID of this thread instance - DWORD GetThreadId(); - - /// Get the ID of the currently executing thread - static DWORD GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Get thread name - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get size of thread message queue. - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - /// Dispatch and invoke a delegate target on the destination thread. - /// @param[in] msg - Delegate message containing target function - /// arguments. - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(m_hThread == NULL); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(m_hThread == NULL); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(m_hThread == NULL); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning Win32Thread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(m_hThread == NULL); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(m_hThread == NULL); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(m_hThread == NULL); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(m_hThread == NULL); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - Win32Thread(const Win32Thread&) = delete; - Win32Thread& operator=(const Win32Thread&) = delete; - - /// Win32 thread proc entry point - static DWORD WINAPI ThreadProc(LPVOID lpParam); - - /// Entry point for the thread - void Process(); - - /// Check watchdog is expired. Called by WatchdogCheckAll(), which the application - /// calls periodically, typically from its highest-priority task. Thread-safe. - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static Win32Thread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - HANDLE m_hThread = NULL; - DWORD m_threadId = 0; - - // Manual-reset event to synchronize thread startup - HANDLE m_hStartEvent = NULL; - - CRITICAL_SECTION m_cs; - - // Condition variable to wake up consumers when a message is enqueued - CONDITION_VARIABLE m_cvNotEmpty; - - // Condition variable to wake up blocked producers when space is available - CONDITION_VARIABLE m_cvNotFull; - - std::deque> m_highQueue; - std::deque> m_normalQueue; - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - - // Max queue size for back pressure (0 = unlimited) - const size_t MAX_QUEUE_SIZE; - - // Policy applied when the thread message queue is full. - const FullPolicy FULL_POLICY; - - // Timeout duration for TIMEOUT policy - const dmq::Duration m_dispatchTimeout; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - - std::atomic m_exit; - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - Win32Thread* m_watchdogNext = nullptr; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - -#if defined(DMQ_DATABUS_TOOLS) - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the Win32 port. -using Thread = Win32Thread; - -} // namespace dmq::os - - -#endif diff --git a/DelegateMQ/port/os/zephyr/ZephyrClock.h b/DelegateMQ/port/os/zephyr/ZephyrClock.h deleted file mode 100644 index 6093a2b..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrClock.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef ZEPHYR_CLOCK_H -#define ZEPHYR_CLOCK_H - -#include -#include - -namespace dmq::os { - struct ZephyrClock { - // Zephyr k_uptime_get() returns milliseconds (int64_t) - using rep = int64_t; - using period = std::milli; - using duration = std::chrono::duration; - using time_point = std::chrono::time_point; - static const bool is_steady = true; - - static time_point now() noexcept { - return time_point(duration(k_uptime_get())); - } - }; -} // namespace dmq::os - -#endif // ZEPHYR_CLOCK_H \ No newline at end of file diff --git a/DelegateMQ/port/os/zephyr/ZephyrCriticalSection.h b/DelegateMQ/port/os/zephyr/ZephyrCriticalSection.h deleted file mode 100644 index 0bf547b..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrCriticalSection.h +++ /dev/null @@ -1,72 +0,0 @@ -#ifndef ZEPHYR_CRITICAL_SECTION_H -#define ZEPHYR_CRITICAL_SECTION_H - -/// @file ZephyrCriticalSection.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ISR-safe critical section for Zephyr. -/// -/// @details -/// k_mutex_lock() is a priority-inheritance-aware, thread-only primitive in -/// Zephyr, like every other RTOS here -- it cannot be used from ISR context. -/// This type uses irq_lock()/irq_unlock(key) instead, which Zephyr documents -/// as safe from both thread and ISR context (it's Zephyr's own primitive for -/// exactly this: protecting something tiny that ISR and thread code both -/// touch). Unlike ThreadX's plain disable/restore, irq_lock() returns a key -/// that must be threaded back into irq_unlock() -- stored here as a member so -/// it survives the gap between the separate lock()/unlock() calls. -/// -/// *** NARROW PURPOSE -- DO NOT USE THIS AS A GENERAL-PURPOSE LOCK *** -/// Holding this masks interrupts on the CPU for as long as it is held. Only -/// use it to protect something genuinely tiny and bounded that may be -/// touched from ISR context. Do NOT use it in place of dmq::Mutex / -/// dmq::RecursiveMutex for ordinary thread-to-thread synchronization (e.g. -/// DataBus internals, a Thread's message queue) -- anything that can block, -/// take a while, or run for an unbounded time must not run with interrupts -/// globally masked; that is a real-time correctness bug on hardware, not -/// just a style issue. -/// -/// *** NOT RE-LOCKABLE ON THE SAME INSTANCE *** -/// Unlike dmq::RecursiveMutex, calling lock() twice on the SAME instance -/// without an intervening unlock() is incorrect: the second lock() call -/// overwrites the single saved key with the (already locked) inner key, so -/// the outer unlock() restores the wrong state. There is no "recursive" -/// variant of this type -- it has no ownership concept to make recursion -/// meaningful, and Timer's own usage never nests. Locking two DIFFERENT -/// instances in proper LIFO lock/unlock order is fine: each instance saves -/// and restores its own key independently. - -#include - -namespace dmq::os { - - // ========================================================================= - // ZephyrCriticalSection - // See the file-level comment above before using this type anywhere new. - // ========================================================================= - class ZephyrCriticalSection { - public: - ZephyrCriticalSection() = default; - - void lock() { - m_key = irq_lock(); - } - - void unlock() { - irq_unlock(m_key); - } - - // No try_lock(): interrupt masking cannot fail to "acquire", so a - // try_lock() here would always trivially succeed and isn't meaningful. - - ZephyrCriticalSection(const ZephyrCriticalSection&) = delete; - ZephyrCriticalSection& operator=(const ZephyrCriticalSection&) = delete; - - private: - unsigned int m_key = 0; - }; - -} // namespace dmq::os - -#endif // ZEPHYR_CRITICAL_SECTION_H diff --git a/DelegateMQ/port/os/zephyr/ZephyrDelegateQueue.h b/DelegateMQ/port/os/zephyr/ZephyrDelegateQueue.h deleted file mode 100644 index 9e077eb..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrDelegateQueue.h +++ /dev/null @@ -1,187 +0,0 @@ -#ifndef ZEPHYR_DELEGATE_QUEUE_H -#define ZEPHYR_DELEGATE_QUEUE_H - -/// @file ZephyrDelegateQueue.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Thin RAII wrapper around a pair of Zephyr k_msgq primitives used by -/// dmq::os::Thread to carry pending ThreadMsg pointers, with priority support. -/// -/// @details -/// Zephyr's k_msgq has no native "send to front" / priority-put primitive -/// (unlike FreeRTOS's xQueueSendToFront, ThreadX's tx_queue_front_send, or -/// CMSIS-RTOS2's osMessageQueuePut msg_prio argument) -- a single k_msgq is -/// strict FIFO, which previously meant dmq::Priority::HIGH was silently -/// treated as NORMAL on this port. To give HIGH the same "jumps the FIFO" -/// semantics here as on every other RTOS port, this wrapper keeps two -/// independent k_msgq instances (mirroring the desktop stdlib/win32/qt ports' -/// two-deque model) and Receive() always drains the high-priority queue -/// first. -/// -/// This doubles queue memory relative to a single-k_msgq design (each lane -/// gets its own 'capacity'-sized buffer, so worst-case combined depth is -/// 2x capacity rather than exactly capacity) and Receive() uses k_poll() to -/// block efficiently on whichever queue gets data first, rather than a -/// single native blocking receive. This class owns no policy decisions of -/// its own (FullPolicy, timeout computation, and stats stay in Thread.cpp) -/// -- it only knows how to move ThreadMsg* pointers through the two queues. -/// -/// @warning Unverified: written against the documented Zephyr k_msgq/k_poll -/// API but never compiled or run against a real Zephyr SDK/west workspace -/// (none is available in this development environment). The k_poll()-based -/// dual-queue wait is more novel API surface than the plain k_msgq_put/get -/// calls used elsewhere in this port, so review this file with extra care -/// and exercise it on a real target or simulator before relying on it in -/// production -- consistent with the existing caveat on this port's -/// CriticalSection implementation. - -#include -#include "port/os/common/ThreadMsg.h" -#include -#include - -namespace dmq::os { - -class ZephyrDelegateQueue -{ -public: - ZephyrDelegateQueue() - { - memset(&m_highMsgq, 0, sizeof(m_highMsgq)); - memset(&m_normalMsgq, 0, sizeof(m_normalMsgq)); - } - ~ZephyrDelegateQueue() { Destroy(); } - - ZephyrDelegateQueue(const ZephyrDelegateQueue&) = delete; - ZephyrDelegateQueue& operator=(const ZephyrDelegateQueue&) = delete; - - /// Create both queues, each sized to hold up to 'capacity' pointers. - /// @return true on success, false if either buffer allocation failed. - bool Create(size_t capacity) - { - if (m_created) - return true; - - size_t bufBytes = MSG_SIZE * capacity; - - char* highBuf = (char*)k_aligned_alloc(sizeof(void*), bufBytes); - if (!highBuf) - return false; - m_highBuffer.reset(highBuf); - k_msgq_init(&m_highMsgq, m_highBuffer.get(), MSG_SIZE, capacity); - - char* normalBuf = (char*)k_aligned_alloc(sizeof(void*), bufBytes); - if (!normalBuf) { - m_highBuffer.reset(); - return false; - } - m_normalBuffer.reset(normalBuf); - k_msgq_init(&m_normalMsgq, m_normalBuffer.get(), MSG_SIZE, capacity); - - m_created = true; - return true; - } - - bool IsCreated() const { return m_created; } - - /// Send a message. 'highPriority' routes to the high-priority queue, - /// which Receive() always drains first; otherwise the normal queue. - /// 'waitOption' is K_NO_WAIT for non-blocking, K_FOREVER to block - /// forever, or a finite k_timeout_t for a bounded wait -- applied only - /// to the one queue the message is routed to (each lane has its own - /// independent capacity; there is no combined-depth wait across both). - /// @return true if the message was enqueued. - bool Send(ThreadMsg* msg, bool highPriority, k_timeout_t waitOption) - { - struct k_msgq* q = highPriority ? &m_highMsgq : &m_normalMsgq; - return k_msgq_put(q, &msg, waitOption) == 0; - } - - /// Receive a message pointer, blocking up to 'waitOption'. The - /// high-priority queue is always checked -- and drained -- first, so a - /// pending HIGH message is returned even if NORMAL messages arrived - /// earlier. Uses k_poll() to block efficiently on both queues at once - /// rather than polling in a loop. - /// @return the message, or nullptr on timeout. - ThreadMsg* Receive(k_timeout_t waitOption) - { - ThreadMsg* msg = nullptr; - - // Fast path: don't pay for k_poll() if something is already pending. - if (k_msgq_get(&m_highMsgq, &msg, K_NO_WAIT) == 0) - return msg; - if (k_msgq_get(&m_normalMsgq, &msg, K_NO_WAIT) == 0) - return msg; - - if (K_TIMEOUT_EQ(waitOption, K_NO_WAIT)) - return nullptr; - - struct k_poll_event events[2]; - k_poll_event_init(&events[0], K_POLL_TYPE_MSGQ_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &m_highMsgq); - k_poll_event_init(&events[1], K_POLL_TYPE_MSGQ_DATA_AVAILABLE, K_POLL_MODE_NOTIFY_ONLY, &m_normalMsgq); - - if (k_poll(events, 2, waitOption) != 0) - return nullptr; // timed out waiting for either queue - - // k_poll only signals readiness; re-check high first so a HIGH - // message still jumps the FIFO even if NORMAL became ready too. - if (k_msgq_get(&m_highMsgq, &msg, K_NO_WAIT) == 0) - return msg; - if (k_msgq_get(&m_normalMsgq, &msg, K_NO_WAIT) == 0) - return msg; - return nullptr; - } - - /// Combined number of messages waiting across both queues. - size_t Size() - { - if (!m_created) - return 0; - return static_cast(k_msgq_num_used_get(&m_highMsgq)) - + static_cast(k_msgq_num_used_get(&m_normalMsgq)); - } - - /// Remove and delete every pending message in both queues without - /// blocking. Used during shutdown once the owning thread has stopped - /// consuming the queues. - /// Each message is canceled first (CancelThreadMsg()), releasing a sender - /// blocked waiting on it. - void DrainAndDelete() - { - ThreadMsg* msg = nullptr; - while (k_msgq_get(&m_highMsgq, &msg, K_NO_WAIT) == 0) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - while (k_msgq_get(&m_normalMsgq, &msg, K_NO_WAIT) == 0) { - CancelThreadMsg(*msg); // Release a sender blocked on it - delete msg; - } - } - - void Destroy() - { - m_highBuffer.reset(); - m_normalBuffer.reset(); - m_created = false; - } - -private: - using ZephyrDeleter = void(*)(void*); - - static const size_t MSG_SIZE = sizeof(ThreadMsg*); - - struct k_msgq m_highMsgq; - struct k_msgq m_normalMsgq; - - // Dynamically allocated queue buffers, freed via k_free. - std::unique_ptr m_highBuffer{nullptr, k_free}; - std::unique_ptr m_normalBuffer{nullptr, k_free}; - - bool m_created = false; -}; - -} // namespace dmq::os - -#endif // ZEPHYR_DELEGATE_QUEUE_H diff --git a/DelegateMQ/port/os/zephyr/ZephyrMutex.h b/DelegateMQ/port/os/zephyr/ZephyrMutex.h deleted file mode 100644 index 0d916d6..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrMutex.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef ZEPHYR_MUTEX_H -#define ZEPHYR_MUTEX_H - -#include - -namespace dmq::os { - - // ========================================================================= - // ZephyrMutex - // Wraps k_mutex. - // ========================================================================= - class ZephyrMutex { - public: - ZephyrMutex() { - k_mutex_init(&m_mutex); - } - - ~ZephyrMutex() { } - - void lock() { - k_mutex_lock(&m_mutex, K_FOREVER); - } - - // REQUIRED for std::unique_lock compatibility - bool try_lock() { - return k_mutex_lock(&m_mutex, K_NO_WAIT) == 0; - } - - void unlock() { - k_mutex_unlock(&m_mutex); - } - - ZephyrMutex(const ZephyrMutex&) = delete; - ZephyrMutex& operator=(const ZephyrMutex&) = delete; - - private: - struct k_mutex m_mutex; - }; - - using ZephyrRecursiveMutex = ZephyrMutex; -} // namespace dmq::os - -#endif // ZEPHYR_MUTEX_H \ No newline at end of file diff --git a/DelegateMQ/port/os/zephyr/ZephyrSemaphore.h b/DelegateMQ/port/os/zephyr/ZephyrSemaphore.h deleted file mode 100644 index 3693c19..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrSemaphore.h +++ /dev/null @@ -1,77 +0,0 @@ -#ifndef ZEPHYR_SEMAPHORE_H -#define ZEPHYR_SEMAPHORE_H - -/// @file ZephyrSemaphore.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief dmq::Semaphore backing for Zephyr, using Zephyr's native k_sem -/// directly instead of the generic dmq::ConditionVariable + dmq::Mutex -/// implementation in delegate/Semaphore.h. -/// -/// @details -/// Zephyr has no dmq::ConditionVariable port (no DMQ_HAS_CV), so the -/// generic Semaphore implementation isn't available here -- but Zephyr -/// already provides a native binary semaphore, which is a more direct fit -/// anyway (no need to build one out of a mutex + condition variable when -/// the RTOS already has a real one). DelegateOpt.h resolves dmq::Semaphore -/// to this type on Zephyr; see the "Semaphore" comment next to -/// DMQ_THREAD_ZEPHYR's `using Semaphore = ...;` there. -/// -/// @note This header is included from DelegateOpt.h's early port-include -/// block, before "namespace dmq { ... }" opens and dmq::Duration is defined -/// inside it (including it any later would nest as dmq::dmq::os instead of -/// dmq::os) -- so, like ThreadXConditionVariable.h and -/// FreeRTOSConditionVariable.h, Wait() is templated on the chrono duration -/// type instead of depending on dmq::Duration directly. A dmq::Duration -/// argument still deduces through it seamlessly at the call site, since -/// dmq::Duration is itself a std::chrono::duration specialization. - -#include -#include - -namespace dmq::os { - - // ========================================================================= - // ZephyrSemaphore - // Binary semaphore (max count 1), matching the semantics of the generic - // dmq::Semaphore this replaces: Signal() when already signaled is a - // no-op (not a counting semaphore), and Wait() consumes exactly one - // pending signal. - // ========================================================================= - class ZephyrSemaphore { - public: - ZephyrSemaphore() { - k_sem_init(&m_sem, 0, 1); - } - - ~ZephyrSemaphore() = default; - - /// Called to wait on a semaphore to be signaled. - /// @param[in] timeout - semaphore timeout - /// @return Return true if semaphore signaled, false if timeout occurred. - template - bool Wait(const std::chrono::duration& timeout) { - using DurationT = std::chrono::duration; - if (timeout == DurationT::max()) { - return k_sem_take(&m_sem, K_FOREVER) == 0; - } - auto ms = std::chrono::duration_cast(timeout).count(); - return k_sem_take(&m_sem, K_MSEC(ms)) == 0; - } - - /// Called to signal a semaphore. - void Signal() { - k_sem_give(&m_sem); - } - - ZephyrSemaphore(const ZephyrSemaphore&) = delete; - ZephyrSemaphore& operator=(const ZephyrSemaphore&) = delete; - - private: - struct k_sem m_sem; - }; - -} // namespace dmq::os - -#endif // ZEPHYR_SEMAPHORE_H diff --git a/DelegateMQ/port/os/zephyr/ZephyrThisThread.h b/DelegateMQ/port/os/zephyr/ZephyrThisThread.h deleted file mode 100644 index 5ac9c95..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrThisThread.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef ZEPHYR_THIS_THREAD_H -#define ZEPHYR_THIS_THREAD_H - -/// @file ZephyrThisThread.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Portable sleep_for()/yield() for the calling thread, Zephyr backend. -/// -/// @details -/// This is dmq::ThisThread for this port (see DelegateOpt.h). GetCurrent() -/// uses RegistryCurrentThread, keyed by the calling thread's id. Exists so -/// library internals that need to delay or yield (e.g. RetryMonitor backoff) -/// aren't forced to pull in the full dmq::os::Thread class -- which also -/// drags in the message queue, watchdog, and stats machinery -- just to -/// sleep. dmq::os::Thread::Sleep() forwards here too, so the Zephyr delay -/// call is implemented exactly once. - -#include -#include "ZephyrMutex.h" -#include "port/os/common/CurrentThreadStorage.h" -#include - -namespace dmq::os { - - /// @brief Key for RegistryCurrentThread: the calling thread's id, or 0 inside an ISR. - inline uintptr_t ZephyrCurrentThreadKey() { - if (k_is_in_isr()) - return 0; - return reinterpret_cast(k_current_get()); - } - - struct ZephyrThisThread : RegistryCurrentThread { - template - static void sleep_for(std::chrono::duration d) { - const auto ms = std::chrono::duration_cast(d); - k_sleep(K_MSEC(ms.count())); - } - - static void yield() noexcept { - k_yield(); - } - }; - -} // namespace dmq::os - -#endif // ZEPHYR_THIS_THREAD_H diff --git a/DelegateMQ/port/os/zephyr/ZephyrThread.cpp b/DelegateMQ/port/os/zephyr/ZephyrThread.cpp deleted file mode 100644 index eda46e8..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrThread.cpp +++ /dev/null @@ -1,684 +0,0 @@ -// Compiles to nothing unless DMQ_THREAD_ZEPHYR is selected, so every DelegateMQ source -// file can be added to a build (see src/DelegateMQ.cpp). -#include "delegate/DelegateSelect.h" -#if defined(DMQ_THREAD_ZEPHYR) - -#include "DelegateMQ.h" -#include "ZephyrThread.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/ThreadHooks.h" -#include "extras/util/Fault.h" -#include -#include // for memset - -// Define DMQ_ASSERT_TRUE if not already defined -#ifndef DMQ_ASSERT_TRUE -#define DMQ_ASSERT_TRUE(x) __ASSERT(x, "DelegateMQ Assertion Failed") -#endif - -namespace dmq::os { - -using namespace dmq::util; - -//---------------------------------------------------------------------------- -// Thread Constructor -//---------------------------------------------------------------------------- -ZephyrThread::ZephyrThread(const char* threadName, size_t maxQueueSize, FullPolicy fullPolicy, dmq::Duration dispatchTimeout, const char* cpuName) - : THREAD_NAME(threadName) - , CPU_NAME(cpuName) - , m_queueSize((maxQueueSize == 0) ? DEFAULT_QUEUE_SIZE : maxQueueSize) - , FULL_POLICY(fullPolicy) - , m_dispatchTimeout(dispatchTimeout) - , m_exit(false) -{ - m_priority = K_PRIO_PREEMPT(dmq::ZEPHYR_THREAD_PRIORITY); // Default priority, DMQ_ZEPHYR_THREAD_PRIORITY - - // Initialize objects to zero (m_queue zeroes its own control blocks in - // ZephyrDelegateQueue's constructor) - memset(&m_thread, 0, sizeof(m_thread)); - - // Initialize exit semaphore (Initial count 0, Limit 1) - k_sem_init(&m_exitSem, 0, 1); - k_sem_init(&m_startSem, 0, 1); - -#if defined(DMQ_DATABUS_TOOLS) - k_mutex_init(&m_statMutex); -#endif -} - -//---------------------------------------------------------------------------- -// Thread Destructor -//---------------------------------------------------------------------------- -ZephyrThread::~ZephyrThread() -{ - // Deleting a ZephyrThread from one of its own callbacks is not supported: the - // destructor would free the stack and control block the thread is still - // running on, and ThreadX/Zephyr (unlike FreeRTOS, whose idle task frees a - // self-deleted task's stack) have no way to free them afterwards. Fault - // immediately instead of corrupting memory. To stop a thread from inside - // its own callback, call ExitThread() and delete the object from another - // thread. - if (m_stackMemory && k_current_get() == &m_thread) - DMQ_ASSERT(); - - ExitThread(); - - const dmq::LockGuard lock(GetWatchdogLock()); - ZephyrThread** pp = &GetWatchdogHead(); - while (*pp != nullptr) - { - if (*pp == this) - { - *pp = this->m_watchdogNext; - this->m_watchdogNext = nullptr; - break; - } - pp = &((*pp)->m_watchdogNext); - } -} - -//---------------------------------------------------------------------------- -// CreateThread -//---------------------------------------------------------------------------- -bool ZephyrThread::CreateThread(std::optional watchdogTimeout) -{ - // Check if thread is already created (dummy check on stack ptr) - if (!m_stackMemory) - { - // Reset from a previous ExitThread(), so the thread can be created again - m_exit.store(false); - // Held from creation, so the watchdog never sees a gated thread as hung - // before it reaches the gate (e.g. created before the scheduler runs) - m_startGate.OnCreate(); - // Set before the thread exists: its loop reads the timeout before its - // first queue wait, and an idle thread waits forever with no timeout - m_lastAliveTime.store(Timer::GetNow()); - m_watchdogTimeout.store(watchdogTimeout.value_or(dmq::Duration(0))); - m_discard.store(false); - - // 1. Create Message Queues - DMQ_ASSERT_TRUE(m_queue.Create(m_queueSize)); - - // 2. Create Thread - // CRITICAL: Stacks must be aligned to Z_KERNEL_STACK_OBJ_ALIGN for MPU/Arch reasons. - // We use k_aligned_alloc instead of new char[]. - // K_THREAD_STACK_LEN calculates the correct size including guard pages/metadata. - size_t stackBytes = K_THREAD_STACK_LEN(STACK_SIZE); - char* stackBuf = (char*)k_aligned_alloc(Z_KERNEL_STACK_OBJ_ALIGN, stackBytes); - if (!stackBuf) - BAD_ALLOC(); - - m_stackMemory.reset(stackBuf); // Ownership passed to unique_ptr - - // Called from a thread, CreateThread() waits for the start handler. - // Pre-kernel or from an ISR it cannot block; the start handler then runs - // when the thread is first scheduled, still before any message. - m_startSync = !k_is_pre_kernel() && !k_is_in_isr(); - - k_tid_t tid = k_thread_create(&m_thread, - (k_thread_stack_t*)m_stackMemory.get(), - STACK_SIZE, - (k_thread_entry_t)ZephyrThread::Process, - this, NULL, NULL, - m_priority, - 0, - K_NO_WAIT); - - DMQ_ASSERT_TRUE(tid != nullptr); - - // Optional: Set thread name for debug - k_thread_name_set(tid, THREAD_NAME.c_str()); - - // Wait for the start handler to complete - if (m_startSync) - k_sem_take(&m_startSem, K_FOREVER); - - m_lastAliveTime.store(Timer::GetNow()); - - if (watchdogTimeout.has_value()) - { - - const dmq::LockGuard lock(GetWatchdogLock()); - - // Add to watchdog registry if not already present - bool found = false; - ZephyrThread* p = GetWatchdogHead(); - while (p != nullptr) - { - if (p == this) - { - found = true; - break; - } - p = p->m_watchdogNext; - } - - if (!found) - { - m_watchdogNext = GetWatchdogHead(); - GetWatchdogHead() = this; - } - } - } - return true; -} - -//---------------------------------------------------------------------------- -// ExitThread -//---------------------------------------------------------------------------- -void ZephyrThread::ExitThread(ExitPolicy policy) -{ - if (m_stackMemory) - { - // Set before m_exit: Run() reads it for every message ahead of the exit message - m_discard.store(policy == ExitPolicy::DISCARD); - m_exit.store(true); - - // A thread held at its start gate isn't waiting on its queue: wake it so it - // sees the exit flag (set above) and leaves. Never touches the gate itself, - // which may be destroyed once the thread is released. - m_startGate.Wake(); - - // Check self-exit BEFORE attempting to enqueue the exit message. If - // this thread is destroying itself from within its own dispatched - // callback, it is not consuming its own queue right now -- it is - // blocked here, inside ExitThread(). A blocking k_msgq_put() would - // deadlock forever if the queue happened to be full. No message needs - // to be queued in that case: Run()'s dispatch loop already checks - // m_selfExitPtr immediately after the current callback invoke - // returns, and unwinds without touching 'this' again. - // - // Crucially, a self-exiting thread must NOT touch m_queue or - // m_stackMemory here: it is still physically executing on - // m_stackMemory (unwinding back through Invoke()/Run()), and it - // cannot k_thread_join() itself. Set the flag and return immediately; - // the actual cleanup (queue drain/destroy, k_thread_join, stack free) - // is deferred to a later ExitThread() call made from a different - // thread context -- typically ~ZephyrThread(), which must itself run on - // another thread (it faults if run on this one) -- once m_selfExited - // tells that call it's safe to skip the message/semaphore handshake - // below (the thread already returned/is returning on its own) and go - // straight to the join+free. - if (k_current_get() == &m_thread) { - m_selfExited.store(true); - if (m_selfExitPtr) { *m_selfExitPtr = true; m_selfExitPtr = nullptr; } - m_startGate.Leave(); // exited from its start handler: never reaches the gate - // Self-exit: this thread runs no more messages, and the object may be - // destroyed once this handler returns. Stop watchdog checks now. - m_watchdogTimeout.store(dmq::Duration(0)); - return; - } - - if (!m_selfExited.load()) - { - // Send exit message - ThreadMsg* msg = new (std::nothrow) ThreadMsg(MSG_EXIT_THREAD); - if (msg) - { - // Wait forever to ensure message is sent - if (!m_queue.Send(msg, /*highPriority=*/false, K_FOREVER)) - { - delete msg; - } - } - - // Wait for thread to actually finish to avoid use-after-free of the stack. - k_sem_take(&m_exitSem, K_FOREVER); - } - - // k_sem_give() in Run() fires just before it returns -- taking the - // semaphore only proves Run() is about to return, not that the - // kernel has finished tearing the thread down (unlinking it from - // scheduler structures) after the entry function exits. Freeing - // m_thread's memory (this object may be stack-allocated) or - // m_stackMemory below before that teardown completes leaves the - // kernel with a dangling reference into memory about to be reused - // -- observed as a newly created thread at the same address never - // getting scheduled. k_thread_join() blocks until the kernel - // itself has marked the thread fully dead, which is the - // documented, race-free way to wait for this. It is also the right - // call in the deferred self-exit case: the thread has already - // returned or is in the process of returning on its own, so this - // either returns immediately or waits only as long as that natural - // teardown takes -- there is no risk of deadlock. - k_thread_join(&m_thread, K_FOREVER); - - // The thread has finished (or, on a self-exit, is in its last handler): - // stop watchdog checks. Not earlier, so a thread that hangs while - // ExitThread() waits for it is still reported. - m_watchdogTimeout.store(dmq::Duration(0)); - - m_queue.DrainAndDelete(); - m_queue.Destroy(); - - // Reset buffer to mark as exited. This prevents a double-entry deadlock: - // ~Thread() calls ExitThread() unconditionally, so if ExitThread() was already - // called explicitly, the second call must be a no-op (m_stackMemory is null). - m_stackMemory.reset(); - - // Allow this object to be reused for a fresh CreateThread()/Run() cycle. - m_selfExited.store(false); - - // Note: k_thread_abort is not needed because the thread will - // return from Run() and terminate naturally. - } -} - -//---------------------------------------------------------------------------- -// SetThreadPriority -//---------------------------------------------------------------------------- -void ZephyrThread::SetThreadPriority(int priority) -{ - m_priority = priority; - if (m_stackMemory) { - k_thread_priority_set(&m_thread, m_priority); - } -} - -//---------------------------------------------------------------------------- -// GetThreadId -//---------------------------------------------------------------------------- -k_tid_t ZephyrThread::GetThreadId() -{ - return &m_thread; -} - -//---------------------------------------------------------------------------- -// GetCurrentThreadId -//---------------------------------------------------------------------------- -k_tid_t ZephyrThread::GetCurrentThreadId() -{ - return k_current_get(); -} - -//---------------------------------------------------------------------------- -// IsCurrentThread -//---------------------------------------------------------------------------- -bool ZephyrThread::IsCurrentThread() -{ - return GetThreadId() == GetCurrentThreadId(); -} - -//---------------------------------------------------------------------------- -// GetQueueSize -//---------------------------------------------------------------------------- -size_t ZephyrThread::GetQueueSize() -{ - return m_queue.Size(); -} - -void ZephyrThread::Sleep(dmq::Duration timeout) { - dmq::ThisThread::sleep_for(timeout); -} - -//---------------------------------------------------------------------------- -// DispatchDelegate -//---------------------------------------------------------------------------- -bool ZephyrThread::DispatchDelegate(std::shared_ptr msg) -{ - DMQ_ASSERT_TRUE(m_stackMemory != nullptr); - - // 1. Allocate message container - ThreadMsg* threadMsg = new (std::nothrow) ThreadMsg(MSG_DISPATCH_DELEGATE, msg); - if (!threadMsg) return false; -#if defined(DMQ_DATABUS_TOOLS) - threadMsg->SetEnqueueTime(Timer::GetNow()); -#endif - - // 2. Send pointer to queue - k_timeout_t timeout; - if (FULL_POLICY == FullPolicy::TIMEOUT) - timeout = K_MSEC(std::chrono::duration_cast(m_dispatchTimeout).count()); - else - timeout = K_NO_WAIT; // DROP and FAULT: non-blocking - - // High priority routes to the queue Receive() always drains first. - bool sent = m_queue.Send(threadMsg, msg->GetPriority() == dmq::Priority::HIGH, timeout); - if (!sent) - { - if (FULL_POLICY == FullPolicy::FAULT) { - printf("[Thread] CRITICAL: Queue full on thread '%s'! TRIGGERING FAULT.\n", THREAD_NAME.c_str()); - DMQ_ASSERT_TRUE(sent); - } else if (FULL_POLICY == FullPolicy::TIMEOUT) { - printf("[Thread] WARNING: Queue post timed out on '%s' — possible deadlock. Message dropped.\n", THREAD_NAME.c_str()); - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } else { // DROP - if (m_droppedHandler) - m_droppedHandler(GetQueueSize()); - } - // Failed to enqueue (queue full or timed out) - delete threadMsg; - return false; - } - -#if defined(DMQ_DATABUS_TOOLS) - // Update monitoring stats - { - k_mutex_lock(&m_statMutex, K_FOREVER); - size_t currentDepth = GetQueueSize(); - if (currentDepth > m_queueDepthMaxWindow) m_queueDepthMaxWindow = currentDepth; - if (currentDepth > m_queueDepthMaxAll) m_queueDepthMaxAll = currentDepth; - k_mutex_unlock(&m_statMutex); - } -#endif - - return true; -} - -//---------------------------------------------------------------------------- -// Process (Static Entry Point) -//---------------------------------------------------------------------------- -void ZephyrThread::Process(void* p1, void* p2, void* p3) -{ - ZephyrThread* thread = static_cast(p1); - if (thread) - { - thread->Run(); - } - // Returning from entry point automatically terminates the thread in Zephyr -} - -//---------------------------------------------------------------------------- -// Run (Member Function Loop) -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- -// WatchdogCheck -//---------------------------------------------------------------------------- -void ZephyrThread::WatchdogCheck() -{ - if (m_startGate.IsHeld()) - return; // held at its start gate by design, not hung - - auto now = Timer::GetNow(); - auto lastAlive = m_lastAliveTime.load(); - auto watchdogTimeout = m_watchdogTimeout.load(); - - if (watchdogTimeout.count() > 0) - { - auto delta = now - lastAlive; - if (delta > watchdogTimeout) - { - WatchdogHandler(THREAD_NAME.c_str()); - } - } -} - -//---------------------------------------------------------------------------- -// ThreadCheck -//---------------------------------------------------------------------------- -void ZephyrThread::ThreadCheck() -{ - m_lastAliveTime.store(Timer::GetNow()); -} - -//---------------------------------------------------------------------------- -// WatchdogCheckAll -//---------------------------------------------------------------------------- -void ZephyrThread::WatchdogCheckAll() -{ - const dmq::LockGuard lock(GetWatchdogLock()); - ZephyrThread* p = GetWatchdogHead(); - while (p != nullptr) - { - p->WatchdogCheck(); - p = p->m_watchdogNext; - } -} - -//---------------------------------------------------------------------------- -// GetWatchdogHead -//---------------------------------------------------------------------------- -ZephyrThread*& ZephyrThread::GetWatchdogHead() -{ - static ZephyrThread* head = nullptr; - return head; -} - -//---------------------------------------------------------------------------- -// GetWatchdogLock -//---------------------------------------------------------------------------- -dmq::RecursiveMutex& ZephyrThread::GetWatchdogLock() -{ - static dmq::RecursiveMutex* lock = new dmq::RecursiveMutex(); - return *lock; -} - -//---------------------------------------------------------------------------- -// Run (Member Function Loop) -//---------------------------------------------------------------------------- -void ZephyrThread::Run() -{ - bool selfExit = false; - m_selfExitPtr = &selfExit; - - // Exit and idle handlers are copied onto this stack frame so they work on - // every return path, including a self-exit where 'this' may already be freed. - ThreadExitGuard exitGuard(m_exitHandler); - ThreadIdleTimer idle(m_idleHandler, m_idleInterval); - - // dmq::ThisThread::GetCurrent() returns this thread from here on. Reset - // before the exit handler runs (and destroyed before exitGuard on a - // self-exit), so the exit handler sees nullptr. - std::optional currentScope; - currentScope.emplace(this); - - if (m_startHandler) - m_startHandler(); - - // A start handler that exited this thread (ExitThread() on itself) leaves - // right after the signal below: once CreateThread() returns, the Thread may - // be destroyed, so nothing after the signal may touch 'this'. - const bool exitedInStart = selfExit; - - if (m_startSync) - k_sem_give(&m_startSem); - if (exitedInStart) - return; - - // Optional start gate: wait here, ready but processing nothing, until it opens - if (m_startGate.Enabled()) - { - const bool opened = m_startGate.Wait(m_exit); - m_lastAliveTime.store(Timer::GetNow()); // before Passed(): no stale watchdog read - m_startGate.Passed(); - // ExitThread() while held: run nothing. Cancel each queued message - // (DISCARD) until the exit message. Consuming them also keeps - // ExitThread()'s blocking send of the exit message from waiting on a - // full queue. - if (!opened) - m_discard.store(true); - } - - ThreadMsg* msg = nullptr; - while (!selfExit) - { - dmq::Duration watchdogTimeout; - { - m_lastAliveTime.store(Timer::GetNow()); - watchdogTimeout = m_watchdogTimeout.load(); - } - - // If watchdog active, use a finite timeout so we can periodically update - // m_lastAliveTime while idle. If an idle handler is set, wake no later - // than when it is due. Otherwise, block forever to save power. - dmq::Duration waitTime = idle.WaitTime(watchdogTimeout.count() > 0 ? watchdogTimeout / dmq::WATCHDOG_HEARTBEAT_DIVISOR : dmq::Duration(-1)); - k_timeout_t waitOption = K_FOREVER; - if (waitTime >= dmq::Duration::zero()) - { - // Rounded up, so only an idle handler that is already due waits 0 - waitOption = K_MSEC(std::chrono::ceil(waitTime).count()); - } - - // Block for a message or timeout - msg = m_queue.Receive(waitOption); - if (msg == nullptr) - { - // Exit requested but no exit message arrived (e.g. it could not be allocated) - if (m_exit.load()) - break; - - // Timed out with the queue empty: run the idle handler if it is due - if (idle.IsDue()) - { - idle.Run(); - // The idle handler exited this thread (and may have deleted it): leave - // without touching 'this', as the message path does - if (selfExit) - return; - } - } - else - { - int msgId = msg->GetId(); - if (msgId == MSG_DISPATCH_DELEGATE && m_discard.load()) - { - // ExitPolicy::DISCARD: skip messages queued ahead of the exit message - CancelThreadMsg(*msg); - } - else if (msgId == MSG_DISPATCH_DELEGATE) - { -#if defined(DMQ_DATABUS_TOOLS) - // Update latency stats before invoking - dmq::Duration latency = Timer::GetNow() - msg->GetEnqueueTime(); - { - k_mutex_lock(&m_statMutex, K_FOREVER); - m_latencyTotalWindow += latency; - m_latencyCountWindow++; - if (latency > m_latencyMaxWindow) m_latencyMaxWindow = latency; - if (latency > m_latencyMaxAll) m_latencyMaxAll = latency; - m_dispatchCountAll++; - k_mutex_unlock(&m_statMutex); - } -#endif - - auto delegateMsg = msg->GetData(); - DMQ_ASSERT_TRUE(delegateMsg); - auto invoker = delegateMsg->GetInvoker(); - DMQ_ASSERT_TRUE(invoker); - -#if defined(DMQ_DATABUS_TOOLS) - dmq::TimePoint start = Timer::GetNow(); -#endif -#if defined(__cpp_exceptions) && !defined(DMQ_ASSERTS) - bool success = false; - try { - success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); - } - catch (const std::bad_alloc& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled bad_alloc in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::invalid_argument& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled invalid_argument in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::runtime_error& e) { - std::cerr << "[Thread:" << THREAD_NAME << "] Unhandled runtime_error in delegate callback: " << e.what() << std::endl; - DMQ_ASSERT(); - } - catch (const std::exception& e) { - printf("[Thread:%s] Unhandled exception in delegate callback: %s\n", THREAD_NAME.c_str(), e.what()); - DMQ_ASSERT(); - } - catch (...) { - printf("[Thread:%s] Unhandled unknown exception in delegate callback.\n", THREAD_NAME.c_str()); - DMQ_ASSERT(); - } -#else - bool success = invoker->Invoke(delegateMsg); - if (!selfExit) DMQ_ASSERT_TRUE(success); -#endif - if (selfExit) { - delete msg; - return; - } - -#if defined(DMQ_DATABUS_TOOLS) - dmq::Duration invokeTime = Timer::GetNow() - start; - { - k_mutex_lock(&m_statMutex, K_FOREVER); - m_invokeTotalWindow += invokeTime; - m_invokeCountWindow++; - if (invokeTime > m_invokeMaxWindow) m_invokeMaxWindow = invokeTime; - if (invokeTime > m_invokeMaxAll) m_invokeMaxAll = invokeTime; - k_mutex_unlock(&m_statMutex); - } -#endif - } - - delete msg; - - if (msgId == MSG_EXIT_THREAD) { - break; - } - - // Any message restarts the idle countdown - idle.Restart(); - } - } - - // Run the exit handler before signalling ExitThread(), so it returns only after it - currentScope.reset(); - exitGuard.Fire(); - - // Clear before signalling: once ExitThread() returns, 'this' may be destroyed - m_selfExitPtr = nullptr; - // Signal that we are about to exit - k_sem_give(&m_exitSem); -} - -#if defined(DMQ_DATABUS_TOOLS) -//---------------------------------------------------------------------------- -// SnapshotStats -//---------------------------------------------------------------------------- -ZephyrThread::ThreadStats ZephyrThread::SnapshotStats() -{ - k_mutex_lock(&m_statMutex, K_FOREVER); - ThreadStats stats; - stats.cpu_name = CPU_NAME; - stats.thread_name = THREAD_NAME; - stats.queue_depth = GetQueueSize(); - stats.queue_depth_max_window = m_queueDepthMaxWindow; - stats.queue_depth_max_all = m_queueDepthMaxAll; - stats.queue_size_limit = m_queueSize; - - if (m_latencyCountWindow > 0) { - stats.latency_avg_ms = (float)std::chrono::duration_cast(m_latencyTotalWindow).count() / (static_cast(m_latencyCountWindow) * 1000.0f); - } else { - stats.latency_avg_ms = 0.0f; - } - - stats.latency_max_window_ms = (float)std::chrono::duration_cast(m_latencyMaxWindow).count() / 1000.0f; - stats.latency_max_all_ms = (float)std::chrono::duration_cast(m_latencyMaxAll).count() / 1000.0f; - - if (m_invokeCountWindow > 0) { - stats.invoke_avg_ms = (float)std::chrono::duration_cast(m_invokeTotalWindow).count() / (static_cast(m_invokeCountWindow) * 1000.0f); - } else { - stats.invoke_avg_ms = 0.0f; - } - - stats.invoke_max_window_ms = (float)std::chrono::duration_cast(m_invokeMaxWindow).count() / 1000.0f; - stats.invoke_max_all_ms = (float)std::chrono::duration_cast(m_invokeMaxAll).count() / 1000.0f; - - stats.dispatch_count = m_dispatchCountAll; - - // Reset windowed stats - m_queueDepthMaxWindow = 0; - m_latencyTotalWindow = Duration(0); - m_latencyCountWindow = 0; - m_latencyMaxWindow = Duration(0); - - m_invokeTotalWindow = Duration(0); - m_invokeCountWindow = 0; - m_invokeMaxWindow = Duration(0); - - k_mutex_unlock(&m_statMutex); - return stats; -} -#endif - -} // namespace dmq::os - -#endif // DMQ_THREAD_ZEPHYR diff --git a/DelegateMQ/port/os/zephyr/ZephyrThread.h b/DelegateMQ/port/os/zephyr/ZephyrThread.h deleted file mode 100644 index bcc9d6d..0000000 --- a/DelegateMQ/port/os/zephyr/ZephyrThread.h +++ /dev/null @@ -1,298 +0,0 @@ -#ifndef _THREAD_ZEPHYR_H -#define _THREAD_ZEPHYR_H - -/// @file ZephyrThread.h -/// @brief Zephyr RTOS implementation of the DelegateMQ IThread interface. -/// -/// @note This implementation is a basic port. For reference, the stdlib and win32 -/// implementations provide additional features: -/// 1. Synchronized Startup: CreateThread() blocks until the worker thread is ready. -/// -/// **Key Features:** -/// * **Task Integration:** Wraps `k_thread_create` to establish a dedicated worker loop. -/// * **FullPolicy Support:** Configurable back-pressure (DROP or TIMEOUT) when the -/// message queue is full. -/// * **Priority Support:** Normal and High priorities. Since Zephyr's `k_msgq` has -/// no native "send to front", `ZephyrDelegateQueue` keeps two `k_msgq` instances -/// (mirroring the desktop two-deque model) and always drains the high-priority -/// one first -- see ZephyrDelegateQueue.h for the tradeoffs this implies. -/// * **Queue-Based Dispatch:** Uses `ZephyrDelegateQueue` (a thin RAII wrapper -/// around a pair of `k_msgq` instances) to receive and process incoming -/// delegate messages in a thread-safe manner. -/// * **Watchdog Integration:** Optional heartbeat mechanism detects stalled or deadlocked -/// threads. Enable by passing a timeout to CreateThread(). Requires -/// Thread::WatchdogCheckAll() to be called periodically from a context that can preempt -/// watched threads -- the highest-priority task in the system, not an ISR. -/// * **Start Gate:** Optional `SetStartGate(StartGate*)`, called before `CreateThread()`, -/// holds the thread ready but processing no messages, at any priority, until -/// `StartGate::Open()` releases every thread sharing the gate at once. - -#include "delegate/IThread.h" -#include "delegate/UnicastDelegate.h" -#include "port/os/common/ThreadMsg.h" -#include "port/os/common/StartGate.h" -#include "ZephyrDelegateQueue.h" -#include "extras/util/Timer.h" -#include -#include -#include -#include -#include - -namespace dmq::os { - -/// @brief Policy applied when the thread message queue is full. See dmq::FullPolicy -/// in DelegateOpt.h for the canonical definition, shared by every dmq::os::Thread port. -using FullPolicy = dmq::FullPolicy; - -/// @brief What ExitThread() does with queued messages. See dmq::ExitPolicy in DelegateOpt.h. -using ExitPolicy = dmq::ExitPolicy; - -class ZephyrThread : public dmq::IThread -{ -public: -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Statistics captured for thread monitoring. - struct ThreadStats { - dmq::xstring cpu_name; - dmq::xstring thread_name; - size_t queue_depth; // Current depth - size_t queue_depth_max_window;// Max depth since last snapshot - size_t queue_depth_max_all; // All-time max depth - size_t queue_size_limit; // Max allowed - float latency_avg_ms; // Avg wait in window - float latency_max_window_ms; // Max wait since last snapshot - float latency_max_all_ms; // All-time max wait - float invoke_avg_ms; // Avg execution in window - float invoke_max_window_ms; // Max execution since last snapshot - float invoke_max_all_ms; // All-time max execution - uint64_t dispatch_count; // Total dispatches (all-time) - }; -#endif - - /// Default queue size if 0 is passed - static const size_t DEFAULT_QUEUE_SIZE = dmq::DEFAULT_QUEUE_SIZE; - - /// Constructor - /// @param threadName Name for the Zephyr thread - /// @param maxQueueSize Max number of messages in queue (0 = Default dmq::DEFAULT_QUEUE_SIZE) - /// @param fullPolicy Action when queue is full: FAULT (default), DROP, or TIMEOUT. - /// @param dispatchTimeout Duration to wait before giving up when policy is TIMEOUT. - /// @param cpuName Optional CPU/Core name grouping for monitoring tools. - ZephyrThread(const char* threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const char* cpuName = ""); - - ZephyrThread(const std::string& threadName, size_t maxQueueSize = 0, FullPolicy fullPolicy = FullPolicy::FAULT, - dmq::Duration dispatchTimeout = dmq::DEFAULT_DISPATCH_TIMEOUT, const std::string& cpuName = "") - : ZephyrThread(threadName.c_str(), maxQueueSize, fullPolicy, dispatchTimeout, cpuName.c_str()) {} - - ~ZephyrThread(); - - /// Called once to create the worker thread. If watchdogTimeout value - /// provided, the maximum watchdog interval is used. Otherwise no watchdog. - /// @param[in] watchdogTimeout - optional watchdog timeout. - /// @return TRUE if thread is created. FALSE otherwise. - bool CreateThread(std::optional watchdogTimeout = std::nullopt); - - /// Shut down the worker thread. - /// @param[in] policy - DRAIN (default) invokes every message queued before this - /// call first; DISCARD invokes only the message already running and cancels - /// the rest (see dmq::ExitPolicy). Called from the thread's own message - /// handler (a self-exit), queued messages are always discarded. - void ExitThread(ExitPolicy policy = ExitPolicy::DRAIN); - - // Note: k_tid_t is a struct k_thread* in Zephyr - k_tid_t GetThreadId(); - static k_tid_t GetCurrentThreadId(); - - /// Returns true if the calling thread is this thread - virtual bool IsCurrentThread() override; - - /// Set the Zephyr Priority. - /// Can be called before or after CreateThread(). - void SetThreadPriority(int priority); - - dmq::xstring GetThreadName() { return THREAD_NAME; } - - /// Get current queue size - size_t GetQueueSize(); - - /// Sleep for a duration. - /// @param[in] timeout - the duration to sleep. - static void Sleep(dmq::Duration timeout); - - virtual bool DispatchDelegate(std::shared_ptr msg) override; - - /// @brief Register a handler invoked when DispatchDelegate() drops a message: - /// under FullPolicy::DROP (queue full, discarded immediately) or - /// FullPolicy::TIMEOUT (queue stayed full for dispatchTimeout, discarded). - /// Optional; unset by default. Called synchronously on the calling (producer) - /// thread, with the queue depth at the time of the drop. - void SetDroppedHandler(const dmq::UnicastDelegate& handler) { m_droppedHandler = handler; } - void SetDroppedHandler(dmq::UnicastDelegate&& handler) { m_droppedHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread before it processes - /// any message. Use it for per-thread setup (COM, a language runtime attach, - /// thread-local state, affinity). CreateThread() returns only after it completes. - /// @details Must be called while the thread is not running (before CreateThread(), - /// or after ExitThread()); calling it on a running thread faults. It runs again - /// on each CreateThread(). Messages dispatched meanwhile are queued, not lost. - void SetStartHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_stackMemory); m_startHandler = handler; } - void SetStartHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_stackMemory); m_startHandler = std::move(handler); } - - /// @brief Optional: hold this thread at `gate` once it is created, until - /// `gate->Open()`. Pass nullptr (the default) to start at once. - /// @details CreateThread() still runs the start handler and returns when the - /// thread is ready; the thread then processes nothing, at any priority, until - /// the gate opens. Use one gate for a group of threads so they all start - /// together after setup. See port/os/common/StartGate.h. Must be called while - /// the thread is not running; calling it on a running thread faults. - void SetStartGate(StartGate* gate) { DMQ_ASSERT_TRUE(!m_stackMemory); m_startGate.Set(gate); } - - /// @brief Register a handler invoked on the worker thread after it processes - /// its last message, as the thread exits. Use it to undo SetStartHandler() setup. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler is copied when the thread starts. - /// ExitThread() from another thread returns after it completes. If the thread - /// exits itself (ExitThread() from a handler on this thread), it runs after the - /// owning ZephyrThread may already be destroyed, so it must not touch that object. - void SetExitHandler(const dmq::UnicastDelegate& handler) { DMQ_ASSERT_TRUE(!m_stackMemory); m_exitHandler = handler; } - void SetExitHandler(dmq::UnicastDelegate&& handler) { DMQ_ASSERT_TRUE(!m_stackMemory); m_exitHandler = std::move(handler); } - - /// @brief Register a handler invoked on the worker thread when its queue has - /// been empty for `interval`, then again every `interval` while it stays empty. - /// Any message processed restarts the countdown. Use it for background work that - /// should yield to messages: polling, housekeeping, entering low power. - /// @details Must be called while the thread is not running; calling it on a - /// running thread faults. The handler and interval are copied when the thread - /// starts. Not called once ExitThread() has been requested. - /// @param[in] handler - the idle handler, or an empty delegate to disable. - /// @param[in] interval - quiet time before each call. Must be greater than zero. - /// Defaults to dmq::THREAD_IDLE_INTERVAL (DMQ_THREAD_IDLE_INTERVAL). - void SetIdleHandler(const dmq::UnicastDelegate& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_stackMemory); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = handler; - m_idleInterval = interval; - } - void SetIdleHandler(dmq::UnicastDelegate&& handler, dmq::Duration interval = dmq::THREAD_IDLE_INTERVAL) - { - DMQ_ASSERT_TRUE(!m_stackMemory); - DMQ_ASSERT_TRUE(interval > dmq::Duration::zero()); - m_idleHandler = std::move(handler); - m_idleInterval = interval; - } - - /// @brief Manually update the watchdog alive timestamp. - /// @details The Run() loop refreshes the timestamp automatically on every iteration. - /// Call this from inside long-running message handlers to prevent a false watchdog - /// alarm when a handler legitimately takes longer than watchdogTimeout. - void ThreadCheck(); - - /// @brief Static method to check all registered threads for watchdog expiration. - static void WatchdogCheckAll(); - -#if defined(DMQ_DATABUS_TOOLS) - /// @brief Capture and reset windowed statistics. - ThreadStats SnapshotStats(); -#endif - -private: - ZephyrThread(const ZephyrThread&) = delete; - ZephyrThread& operator=(const ZephyrThread&) = delete; - - // ZephyrThread entry point - static void Process(void* p1, void* p2, void* p3); - void Run(); - - /// Check watchdog is expired. Called by WatchdogCheckAll(). - void WatchdogCheck(); - - /// Get registry head using the "Immortal" Pattern - static ZephyrThread*& GetWatchdogHead(); - - /// Get registry lock using the "Immortal" Pattern - static dmq::RecursiveMutex& GetWatchdogLock(); - - const dmq::xstring THREAD_NAME; - const dmq::xstring CPU_NAME; - const size_t m_queueSize; - const FullPolicy FULL_POLICY; - const dmq::Duration m_dispatchTimeout; - int m_priority; - - // Zephyr Kernel Objects - struct k_thread m_thread; - ZephyrDelegateQueue m_queue; - - // Optional handler invoked when a message is dropped (FullPolicy::DROP or TIMEOUT) - dmq::UnicastDelegate m_droppedHandler; - - // Optional handlers invoked on the worker thread at start, exit and when idle - dmq::UnicastDelegate m_startHandler; - dmq::UnicastDelegate m_exitHandler; - dmq::UnicastDelegate m_idleHandler; - dmq::Duration m_idleInterval = dmq::Duration::zero(); - struct k_sem m_exitSem; // Semaphore to signal thread completion - struct k_sem m_startSem; // Given by Run() once the start handler has run - bool m_startSync = false; // CreateThread() waits for the start handler (called from a thread) - std::atomic m_exit = false; - - // Optional start gate (SetStartGate()): its state, and whether the thread is - // held at it (the watchdog doesn't report a thread waiting by design) - StartGateClient m_startGate; - std::atomic m_discard = false; // ExitPolicy::DISCARD: cancel queued messages instead of invoking - bool* m_selfExitPtr = nullptr; - - // Set when the thread terminates itself (ExitThread() called from within - // its own dispatched callback). A self-exiting thread cannot join or free - // its own stack, so a later ExitThread() call (typically from ~ZephyrThread(), - // made from a different thread context) checks this to skip the - // message-send/semaphore handshake and go straight to the k_thread_join() - // + stack-free cleanup instead. - std::atomic m_selfExited = false; - - // Custom deleter for Zephyr kernel memory (wraps k_free) - using ZephyrDeleter = void(*)(void*); - - // Dynamically allocated stack, managed by unique_ptr but allocated via - // k_aligned_alloc and freed via k_free. Also doubles as the - // "is thread created" sentinel checked throughout this class. - std::unique_ptr m_stackMemory{nullptr, k_free}; - - // Stack size in bytes - static const size_t STACK_SIZE = dmq::ZEPHYR_STACK_BYTES; // DMQ_ZEPHYR_STACK_BYTES - - // Watchdog related members - std::atomic m_lastAliveTime{dmq::TimePoint()}; - std::atomic m_watchdogTimeout{dmq::Duration(0)}; - ZephyrThread* m_watchdogNext = nullptr; - -#if defined(DMQ_DATABUS_TOOLS) - struct k_mutex m_statMutex; // Mutex to protect statistics - // Monitoring statistics members - size_t m_queueDepthMaxWindow = 0; - size_t m_queueDepthMaxAll = 0; - - dmq::Duration m_latencyTotalWindow = dmq::Duration(0); - uint32_t m_latencyCountWindow = 0; - dmq::Duration m_latencyMaxWindow = dmq::Duration(0); - dmq::Duration m_latencyMaxAll = dmq::Duration(0); - - dmq::Duration m_invokeTotalWindow = dmq::Duration(0); - uint32_t m_invokeCountWindow = 0; - dmq::Duration m_invokeMaxWindow = dmq::Duration(0); - dmq::Duration m_invokeMaxAll = dmq::Duration(0); - - uint64_t m_dispatchCountAll = 0; -#endif -}; - -/// @brief Backward-compatible name: existing code referencing dmq::os::Thread -/// keeps compiling unchanged against the Zephyr port. -using Thread = ZephyrThread; - -} // namespace dmq::os - -#endif // _THREAD_ZEPHYR_H diff --git a/DelegateMQ/port/serialize/README.md b/DelegateMQ/port/serialize/README.md deleted file mode 100644 index 13af0f8..0000000 --- a/DelegateMQ/port/serialize/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# Serializers (DelegateMQ Abstraction Layer) - -This directory contains the serializer part of the **DelegateMQ Abstraction Layer**: the `ISerializer` adapters responsible for marshaling function arguments into binary or text formats for remote transmission. - -DelegateMQ is designed to be **serialization-agnostic**. You can choose the serializer that best fits your project's performance, size, or compatibility requirements. - -## Supported Serializers - -The following subdirectories contain adapters for popular C++ serialization libraries: - -* **`serialize`**: The built-in, header-only **MessageSerialize** library. - * *Best for:* Zero dependencies, simple projects, and built-in STL container support. - * *Features:* Endianness handling, versioning, and no external requirements. -* **`msgpack`**: Adapter for **MessagePack** (msgpack-c). - * *Best for:* High-performance binary serialization and compact data size. -* **`rapidjson`**: Adapter for **RapidJSON**. - * *Best for:* Human-readable JSON output and web API integration. -* **`cereal`**: Adapter for **Cereal**. - * *Best for:* Modern C++11/17 features and robust object serialization. -* **`bitsery`**: Adapter for **Bitsery**. - * *Best for:* Ultra-fast, zero-buffer serialization for real-time applications. - -Alternatively, you can implement your own adapter by inheriting from the `dmq::ISerializer` interface and injecting it into your `dmq::DelegateRemote` instance. - -## Embedded Tradeoffs - -Choosing a serializer for an embedded target involves constraints that do not apply on Linux or Windows: limited heap, no or restricted exception support, code-size budgets, and endianness differences between the MCU and any host it communicates with. - -| Serializer | Embedded suitability | Notes | -|---|---|---| -| `serialize` | Good | Zero external dependencies, automatic endianness handling, builds without exceptions (errors are reported through the stream state). Structs must inherit `serialize::I` and implement `read()`/`write()`. Slightly larger wire format due to size-prefix versioning. | -| `bitsery` | Best for tight constraints | Header-only, designed for real-time/embedded use, produces the smallest payloads of all supported options. Plain structs work with a `serialize()` annotation — no base class required. Endianness is configured at the adapter level rather than handled automatically, so cross-architecture communication requires explicit configuration. | -| `msgpack` | Linux/Windows only | The msgpack-c library allocates dynamically (`msgpack::sbuffer`, `std::vector`) and carries an external dependency. These characteristics are manageable on a host but are a significant concern on a MCU with a constrained FreeRTOS heap. | -| `cereal` | Poor | Heavy template machinery and reliance on `` and `` increases code size considerably. Rarely justified on a Cortex-M or similar resource-constrained target. | -| `rapidjson` | Poor | JSON payload overhead (field names, brackets, quotes) is typically 3–10× larger than an equivalent binary format. Appropriate when a host-side consumer needs human-readable output or REST interoperability, not for high-rate sensor data loops on an MCU. | - -### Guidance - -- **Default embedded choice**: `serialize` — works out of the box with no external dependencies and handles the endianness problem automatically, which matters when an MCU (commonly big-endian capable) communicates with an x86 host. -- **Upgrade path**: `bitsery` — if wire payload size or serialization throughput is a priority on real hardware, bitsery is the natural next step. Only the struct annotations in the message definitions change; `dmq::databus::DataBus` API calls are unaffected. -- **Host-side only**: `msgpack`, `cereal`, and `rapidjson` are appropriate for Linux/Windows nodes in a mixed system but should not be the embedded node's serializer on a resource-constrained target. -- **Message field types**: on the MCU, prefer `std::array`, `xlist`/`xmap`/`xset` and `xstring` over `std::vector`. See [Choosing Containers on Embedded Targets](serialize/README.md#choosing-containers-on-embedded-targets). diff --git a/DelegateMQ/port/serialize/bitsery/BitserySerializer.h b/DelegateMQ/port/serialize/bitsery/BitserySerializer.h deleted file mode 100644 index 472d7c2..0000000 --- a/DelegateMQ/port/serialize/bitsery/BitserySerializer.h +++ /dev/null @@ -1,84 +0,0 @@ -#ifndef DMQ_BITSERY_SERIALIZER_H -#define DMQ_BITSERY_SERIALIZER_H - -/// @file BitserySerializer.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Serialize callable argument data using Bitsery for transport -/// to a remote. Bitsery provides fast, compact binary serialization. - -#include "delegate/ISerializer.h" - -#if defined(DMQ_SERIALIZE_BITSERY) - -// Core Bitsery -#include -#include - -// Common Traits (Include these so standard types work out of the box) -#include -#include -#include - -#include -#include -#include - -namespace dmq::serialization::bitsery { - -template -struct Serializer; // Not defined - -template -class Serializer : public dmq::ISerializer -{ -public: - // Bitsery Adapters for std::ostream / std::istream - using OutputAdapter = ::bitsery::OutputStreamAdapter; - using InputAdapter = ::bitsery::InputStreamAdapter; - - // No try/catch here: this adapter must build without exceptions (-fno-exceptions), - // the common embedded setting. Failures are reported through the stream state, - // which DelegateRemote checks (ERR_DESERIALIZE / ERR_STREAM_NOT_GOOD). - virtual std::ostream& Write(std::ostream& os, const Args&... args) override { - // Reset stream position. - os.seekp(0, std::ios::beg); - - // Clear stringstreams explicitly to avoid appending new data to old data. - // DelegateMQ often reuses the stream object. - if (auto* ss = dynamic_cast(&os)) { - ss->str(""); - } - - // Construct the adapter properly passing the stream - ::bitsery::Serializer writer{ OutputAdapter{os} }; - - // Serialize each argument using C++17 fold expression - (writer.object(args), ...); - - // Ensure buffer is flushed to the stream - writer.adapter().flush(); - return os; - } - - virtual std::istream& Read(std::istream& is, Args&... args) override { - // Construct the adapter properly passing the stream - ::bitsery::Deserializer reader{ InputAdapter{is} }; - - // Deserialize each argument using fold expression - (reader.object(args), ...); - - // A truncated or malformed message: fail the stream. - if (reader.adapter().error() != ::bitsery::ReaderError::NoError) { - is.setstate(std::ios::failbit); - } - return is; - } -}; - -} // namespace dmq::serialization::bitsery - -#endif // DMQ_SERIALIZE_BITSERY - -#endif // DMQ_BITSERY_SERIALIZER_H diff --git a/DelegateMQ/port/serialize/cereal/CerealSerializer.h b/DelegateMQ/port/serialize/cereal/CerealSerializer.h deleted file mode 100644 index efcd304..0000000 --- a/DelegateMQ/port/serialize/cereal/CerealSerializer.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef DMQ_CEREAL_SERIALIZER_H -#define DMQ_CEREAL_SERIALIZER_H - -/// @file CerealSerializer.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Serialize callable argument data using Cereal library for transport -/// to a remote. Endianness handled internally by Cereal. -/// -/// Cereal reports errors by throwing; the exception propagates to -/// DelegateRemote, which reports ERR_SERIALIZE / ERR_DESERIALIZE_EXCEPTION. - -#include -#include -#include -#include "delegate/ISerializer.h" -#include -#include -#include - -namespace dmq::serialization::cereal { - -template -struct Serializer; // Not defined - -// Serialize all target function argument data using Cereal -template -class Serializer : public dmq::ISerializer -{ -public: - // Write arguments to a stream - virtual std::ostream& Write(std::ostream& os, const Args&... args) override { - os.seekp(0); - if (auto* ss = dynamic_cast(&os)) - ss->str(""); - ::cereal::BinaryOutputArchive archive(os); - (archive(args), ...); // C++17 fold expression to serialize each argument - return os; - } - - // Read arguments from a stream - virtual std::istream& Read(std::istream& is, Args&... args) override { - ::cereal::BinaryInputArchive archive(is); - (archive(args), ...); // C++17 fold expression to deserialize - return is; - } -}; - -} // namespace dmq::serialization::cereal - - -#endif // DMQ_CEREAL_SERIALIZER_H diff --git a/DelegateMQ/port/serialize/msgpack/MsgpackSerializer.h b/DelegateMQ/port/serialize/msgpack/MsgpackSerializer.h deleted file mode 100644 index 7485155..0000000 --- a/DelegateMQ/port/serialize/msgpack/MsgpackSerializer.h +++ /dev/null @@ -1,92 +0,0 @@ -#ifndef DMQ_MSGPACK_SERIALIZER_H -#define DMQ_MSGPACK_SERIALIZER_H - -/// @file MsgpackSerializer.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Serialize callable argument data using MessagePack library for transport -/// to a remote. Endianness correctly handled by MessagePack library. -/// -/// MessagePack reports errors by throwing (e.g. msgpack::type_error); the -/// exception propagates to DelegateRemote, which reports ERR_SERIALIZE / -/// ERR_DESERIALIZE_EXCEPTION. - -#include "msgpack.hpp" -#include "delegate/ISerializer.h" -#include -#include -#include // Needed for dynamic_cast check -#include -#include - -namespace dmq::serialization::msgpack { - -// make_serialized serializes each remote function argument -template -void make_serialized(::msgpack::sbuffer& buffer, Args&&... args) { - (::msgpack::pack(buffer, args), ...); // C++17 fold expression to serialize -} - -template -struct Serializer; // Not defined - -// Serialize all target function argument data using MessagePack library -template -class Serializer : public dmq::ISerializer -{ -public: - // Write arguments to a stream - virtual std::ostream& Write(std::ostream& os, const Args&... args) override { - // Reset stream position. DelegateMQ reuses the stream instance. - // If we don't reset, we append new data to old data, sending [Old][New] - // and the receiver will always deserialize [Old]. - os.seekp(0, std::ios::beg); - - // Optimization: If it's a stringstream, clear it completely to avoid - // sending "tail garbage" if the new packet is smaller than the previous one. - // (Note: Even with garbage tail, msgpack works because it stops reading - // after the valid object, but clearing saves network bandwidth). - if (auto* ss = dynamic_cast(&os)) { - ss->str(""); - } - - ::msgpack::sbuffer buffer; - make_serialized(buffer, args...); - os.write(buffer.data(), buffer.size()); - return os; - } - - // Read arguments from a stream - virtual std::istream& Read(std::istream& is, Args&... args) override { - // Read entire stream into memory buffer - std::vector buffer_data((std::istreambuf_iterator(is)), std::istreambuf_iterator()); - - // No data for the arguments: fail, so the caller reports a - // deserialize error instead of invoking with default values. - if (buffer_data.empty() && sizeof...(Args) > 0) { - is.setstate(std::ios::failbit); - return is; - } - - size_t offset = 0; - - // Helper lambda to unpack one argument at a time from the buffer - auto unpack_one = [&](auto& arg) { - // msgpack::unpack parses one object and updates 'offset' to point to the next byte - ::msgpack::object_handle oh = ::msgpack::unpack(buffer_data.data(), buffer_data.size(), offset); - - // Convert msgpack object to specific C++ type - arg = oh.get().as>(); - }; - - // Use C++17 fold expression to call unpack_one for each argument in 'args' - (unpack_one(args), ...); - return is; - } -}; - -} // namespace dmq::serialization::msgpack - - -#endif // DMQ_MSGPACK_SERIALIZER_H diff --git a/DelegateMQ/port/serialize/rapidjson/RapidJsonSerializer.h b/DelegateMQ/port/serialize/rapidjson/RapidJsonSerializer.h deleted file mode 100644 index a2dab15..0000000 --- a/DelegateMQ/port/serialize/rapidjson/RapidJsonSerializer.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef DMQ_RAPIDJSON_SERIALIZER_H -#define DMQ_RAPIDJSON_SERIALIZER_H - -/// @file RapidJsonSerializer.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Serialize callable argument data using RapidJSON for transport -/// to a remote. JSON is text, so endianness doesn't apply. -/// -/// Errors are reported through the stream state (and any exception from an -/// argument's Write()/Read() propagates); DelegateRemote reports them as -/// ERR_SERIALIZE / ERR_DESERIALIZE. - -#include "delegate/ISerializer.h" -#include -#include -#include "rapidjson/document.h" -#include "rapidjson/prettywriter.h" -#include - -namespace dmq::serialization::rapidjson { - -template -struct Serializer; // Not defined - -// Serialize all target function argument data using serialize class -template -class Serializer : public dmq::ISerializer -{ -public: - // Write arguments to a stream - virtual std::ostream& Write(std::ostream& os, const Args&... args) override { - os.seekp(0, std::ios::beg); - // Empty a reused stream: transports send the whole buffer, so bytes left - // over from a longer previous message would follow the JSON and fail - // the receiver's parse. - if (auto* ss = dynamic_cast(&os)) - ss->str(""); - ::rapidjson::StringBuffer sb; - ::rapidjson::PrettyWriter<::rapidjson::StringBuffer> writer(sb); - (args.Write(writer, os), ...); // C++17 fold expression to write each argument - if (writer.IsComplete()) - os << sb.GetString(); - else - os.setstate(std::ios::failbit); - return os; - } - - // Read arguments from a stream - virtual std::istream& Read(std::istream& is, Args&... args) override { - // Get stream length - std::streampos current_pos = is.tellg(); - is.seekg(0, std::ios::end); - std::streampos end_pos = is.tellg(); - is.seekg(current_pos, std::ios::beg); - - if (end_pos < 0 || !is.good()) - { - is.setstate(std::ios::failbit); - return is; - } - - std::streamsize length = static_cast(end_pos); - - // Allocate storage buffer (null terminator appended for RapidJSON) - std::vector buf(static_cast(length) + 1); - is.rdbuf()->sgetn(buf.data(), length); - buf[length] = 0; // null terminate incoming data - - // Parse JSON; a parse error fails the stream (ERR_DESERIALIZE) - ::rapidjson::Document doc; - doc.Parse(buf.data()); - if (doc.HasParseError()) - { - is.setstate(std::ios::failbit); - return is; - } - - (args.Read(doc, is), ...); // C++17 fold expression to read each argument - return is; - } -}; - -} // namespace dmq::serialization::rapidjson - - -#endif // DMQ_RAPIDJSON_SERIALIZER_H diff --git a/DelegateMQ/port/serialize/serialize/DmqSerializer.h b/DelegateMQ/port/serialize/serialize/DmqSerializer.h deleted file mode 100644 index 6dfcbac..0000000 --- a/DelegateMQ/port/serialize/serialize/DmqSerializer.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef DMQ_DMQ_SERIALIZER_H -#define DMQ_DMQ_SERIALIZER_H - -/// @file DmqSerializer.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Serialize callable argument data using serialize class for transport -/// to a remote. Endianness correctly handled by serialize class. -/// -/// Errors are reported through the stream state (and any exception from a -/// user type's read()/write() propagates); DelegateRemote reports them as -/// ERR_SERIALIZE / ERR_DESERIALIZE. No try/catch here, per the library rules. - -#include "delegate/ISerializer.h" -#include -#include -#include "msg_serialize.h" - -namespace dmq::serialization::serializer { - -template -struct Serializer; // Not defined - -// Serialize all target function argument data using serialize class -template -class Serializer : public dmq::ISerializer -{ -public: - // Write arguments to a stream - virtual std::ostream& Write(std::ostream& os, const Args&... args) override { - os.seekp(0, std::ios::beg); - if (auto* ss = dynamic_cast(&os)) - ss->str(""); - ::serialize ser; - (ser.write(os, args), ...); // C++17 fold expression to serialize each argument - return os; - } - - // Read arguments from a stream - virtual std::istream& Read(std::istream& is, Args&... args) override { - ::serialize ser; - (ser.read(is, args), ...); // C++17 fold expression to unserialize each argument - return is; - } -}; - -} // namespace dmq::serialization::serializer - - -#endif // DMQ_DMQ_SERIALIZER_H diff --git a/DelegateMQ/port/serialize/serialize/README.md b/DelegateMQ/port/serialize/serialize/README.md deleted file mode 100644 index 890fa73..0000000 --- a/DelegateMQ/port/serialize/serialize/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# MessageSerialize - -A robust, header-only C++ binary serialization library designed for DelegateMQ. It provides a simple yet powerful framework for marshaling C++ objects, primitives, and STL containers into binary streams. - -## Features - -- **Header-Only**: No external dependencies beyond the C++ Standard Library. -- **Endianness Aware**: Uses a little-endian wire format. Automatically handles byte-swapping on big-endian hosts. -- **STL Support**: Native support for `std::vector`, `std::array`, `std::list`, `std::map`, `std::set`, `std::string`, and `std::wstring`, including nested containers (e.g. `std::vector>`, `std::map>`). -- **Custom Allocators**: Fully compatible with custom allocators, including DelegateMQ's `xstring`, `xlist`, `xmap` and `xset`. Declare message fields with these types and `DMQ_ALLOCATOR` switches them between the fixed-block allocator and the heap, with no serializer changes. -- **Versioning**: Supports forward and backward compatibility for user-defined objects. -- **Type Safety**: Uses compile-time checks to ensure only supported types are serialized. -- **Pointer Support**: Supports serializing containers of pointers with automatic memory allocation during deserialization. -- **Stream Verification**: Includes runtime and compile-time checks (via `is_seekable` trait) to ensure streams support the required seeking operations. - -## Stream Requirements - -- **Seekable**: The library requires seekable streams (e.g., `std::stringstream`, `std::fstream`) to handle object versioning and size backfilling. Non-seekable streams (like sockets or `std::cout`) will trigger a runtime error. -- **Binary Mode**: Always open files or streams in **binary mode** (`std::ios::binary`). Failure to do so may lead to data corruption due to automatic newline translations (especially on Windows). - -## Limits - -Set in `DelegateMQConfig.h` (defaults in `DelegateMQConfig_Default.h`). They apply on write and on read, so a received message can't make the receiver allocate more than this. Exceeding one fails the stream with the error shown. - -| Setting | Default | Limits | Error | -|---|---|---|---| -| `DMQ_SERIALIZE_MAX_STRING_SIZE` | 1024 | String length in bytes, not counting a terminator (none is sent); at most 65535 | `STRING_TOO_LONG` | -| `DMQ_SERIALIZE_MAX_CONTAINER_SIZE` | 64 | Elements in a vector, list, set or map; at most 65535 | `CONTAINER_TOO_MANY` | -| `DMQ_SERIALIZE_MAX_NESTING` | 5 | Depth of `serialize::I` objects nested inside each other | `NESTING_TOO_DEEP` | - -## Basic Usage - -### Serializing Primitives - -```cpp -#include "msg_serialize.h" -#include - -serialize ms; -int value = 123; -std::stringstream ss; - -// Write to stream -ms.write(ss, value); - -// Read from stream -int outValue; -ms.read(ss, outValue); -``` - -### Custom Serializable Objects - -User-defined types must inherit from `serialize::I` and implement the `read()` and `write()` methods. - -```cpp -struct MyData : public serialize::I { - int id = 0; - std::string name; - - // Serialize object to stream - std::ostream& write(serialize& ms, std::ostream& os) const override { - ms.write(os, id); - ms.write(os, name); - return os; - } - - // Deserialize object from stream - std::istream& read(serialize& ms, std::istream& is) override { - ms.read(is, id); - ms.read(is, name); - return is; - } -}; -``` - -### STL Containers and Custom Allocators - -The library handles standard containers and those using custom allocators (like fixed-block pools) automatically. - -```cpp -xlist myList = {1, 2, 3}; -std::stringstream ss; -serialize ms; - -ms.write(ss, myList); - -xlist outList; -ms.read(ss, outList); -``` - -### Choosing Containers on Embedded Targets - -What a message type's fields allocate matters more on an MCU than how they're serialized. With `DMQ_ALLOCATOR`, memory comes from fixed-block pools, one pool per power-of-two block size, and blocks are kept for reuse rather than returned to the heap. - -| Field type | Allocation | Embedded use | -|---|---|---| -| `std::array`, `char[N]` | None | **Best.** Fixed size, no heap and no pool. | -| `xlist`, `xmap`, `xset` | One same-size node per element, from one fixed-block pool | **Good.** Freed nodes are reused exactly. | -| `xstring` | One block sized to the string, from a fixed-block pool | **Good**, bounded by `DMQ_SERIALIZE_MAX_STRING_SIZE`. | -| `std::vector` | One contiguous block that is reallocated larger as it grows | **Host-side only.** Each growth step needs a new, larger block size, so a vector touches several pools and each keeps its blocks. In static-pool mode the largest block is 4096 bytes. | - -- On the MCU, declare message fields with `std::array`, `xlist`/`xmap`/`xset` and `xstring`. On desktop or gateway nodes, `std::vector` is fine. -- `std::array` deliberately uses the vector type marker rather than a separate array type, so its bytes match a vector's (marker, count, elements) and one node can use `std::vector` while the other uses `std::array` for the same field. The count on the wire catches a mismatch: reading into a `std::array` fails with `INVALID_INPUT` unless exactly `N` elements arrive, and a list, set or map fails with `TYPE_MISMATCH`. As with vectors, the marker identifies the container kind, not the element type. -- Reading into a `std::vector` reserves the received count first, so it makes one allocation of the final size rather than regrowing per element. - -## Advanced Features - -### Versioning & Compatibility - -When serializing objects derived from `serialize::I`, the library records the object size in the stream. -- **Forward Compatibility**: If a receiver gets a newer (larger) version of an object, it reads what it knows and safely skips the remaining bytes. -- **Backward Compatibility**: If a receiver gets an older (smaller) version, it reads the available data and leaves the remaining members at their default values. - -### Pointer Containers - -When serializing `std::vector` or `std::list`, the library: -1. Writes a boolean flag for each element indicating if it's null. -2. For non-null elements, it serializes the pointed-to object. -3. During deserialization, it calls `new T` to recreate the objects. - -*Note: The caller is responsible for managing the memory of objects created during pointer container deserialization.* diff --git a/DelegateMQ/port/serialize/serialize/msg_serialize.h b/DelegateMQ/port/serialize/serialize/msg_serialize.h deleted file mode 100644 index 8d2c005..0000000 --- a/DelegateMQ/port/serialize/serialize/msg_serialize.h +++ /dev/null @@ -1,1874 +0,0 @@ -/// @file msg_serialize.h -/// @see https://github.com/endurodave/MessageSerialize -/// @author David Lafreniere -/// @date 2024 -/// -/// @brief A robust, header-only C++ binary serialization library. -/// -/// @details -/// This library provides a framework for marshaling C++ objects, primitives, and STL -/// containers into binary streams (std::ostream) and demarshaling them back (std::istream). -/// It is designed for network communication and data persistence where binary compatibility -/// and protocol evolution are required. -/// -/// **CRITICAL REQUIREMENTS:** -/// * **Binary Mode:** Streams MUST be opened in binary mode (std::ios::binary). Text-mode -/// streams will corrupt binary data (e.g., newline conversion on Windows). -/// * **Seekable Streams:** User-defined objects (inheriting from `serialize::I`) require -/// seekable streams (e.g., `std::stringstream`, `std::fstream`) to backfill object sizes. -/// Non-seekable streams (like `std::cout` or sockets) will trigger a `NON_SEEKABLE_STREAM` error. -/// -/// **Key Features:** -/// * **Single Header:** A self-contained, header-only library with no external dependencies -/// beyond the standard C++ library (STL). -/// * **Endianness Handling:** Wire format is little-endian. Automatic byte-swapping on -/// big-endian hosts ensures compatibility between mixed-endian architectures. -/// * **STL Container Support:** Native serialization for std::vector, std::list, std::map, -/// std::set, std::string, and std::wstring. -/// * **Protocol Versioning:** Supports "Forward/Backward Compatibility" by handling -/// size mismatches. If a received user-defined object is larger than expected (newer version), -/// the parser safely discards the extra data. -/// * **Type Safety:** Uses SFINAE and compile-time static assertions to prevent -/// serialization of unsupported types or unsafe pointers. -/// * **Deep Copying:** Supports serializing containers of pointers, automatically -/// allocating memory upon deserialization. -/// * **Error Handling:** Includes a callback-based error reporting mechanism for -/// stream errors, type mismatches, and boundary violations. -/// -/// **Usage:** -/// User-defined classes must inherit from `serialize::I` and implement the `read()` -/// and `write()` methods. - -#ifndef MSG_SERIALIZE_H_ -#define MSG_SERIALIZE_H_ - -#include -#include -#include -#include "delegate/DelegateOpt.h" // DMQ_ASSERT_TRUE, dmq::SERIALIZE_* limits -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace serialize_traits -{ - template - struct is_shared_ptr : std::false_type {}; - - template - struct is_shared_ptr> : std::true_type {}; - - template - struct is_unsupported_container : std::false_type {}; - - /// @brief Trait to check if a stream type is seekable. - template - struct is_seekable : std::false_type {}; - - template - struct is_seekable().seekp(std::declval())), - decltype(std::declval().tellp()) - >> : std::true_type {}; -} - -// Define to enable compile-time checking of unsupported container types -// Undefine for less compile-time include file dependencies -#define CHECK_UNSUPPORTED_CONTAINER -#ifdef CHECK_UNSUPPORTED_CONTAINER - -#include -#include -#include -#include -#include -#include - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container>> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; - - template - struct serialize_traits::is_unsupported_container> : std::true_type {}; -#endif // CHECK_UNSUPPORTED_CONTAINER - -/// @brief The serialize class binary serializes and deserializes C++ objects. -/// @details Each class need to implement the serialize::I abstract interface -/// to allow binary serialization to any stream. A default constructor is required -/// for the serialized object. Most container elements can be stored by value or -/// by pointer. C++ containers supported are: -/// -/// vector -/// array (std::array, uses the VECTOR type so it interoperates with vector) -/// list -/// map -/// set -/// string -/// wstring -/// char[] -/// -/// Always check the input stream or output stream to ensure no errors -/// before using data. e.g. -/// -/// if (ss.good()) -/// // Do something with input or output data -/// -/// This serialization class is not thread safe and a serialize instance should -/// only be accessed from a single task. -/// -/// The serialize class support receiving objects that have more or less data fields -/// than what is currently being parsed. If more data is received after parsing an -/// object, the extra data is discarded. If less data is received, the parsing of the -/// extra data fields does not occur. This supports the protocol changing by adding new -/// data elements to an object. Once the protocol is released at a particular version, -/// new data elements can be added but existing ones cannot be removed/changed. -/// -/// @note write() requires a seekable stream (i.e. std::ostringstream). The size field -/// for user-defined objects is backfilled via seekp() after the object is written. -/// Using a non-seekable stream produces a corrupt size field and triggers an error. -class serialize -{ -public: - /// @brief Abstract interface that all serialized user defined classes inherit. - class I - { - public: - virtual ~I() = default; - - /// Inheriting class implements the write function. Write each - /// class member to the ostream. Write in the same order as read(). - /// Each level within the hierarchy must implement. Ensure base - /// write() implementation is called if necessary. - /// @param[in] ms - the message serialize instance - /// @param[in] os - the output stream - /// @return The output stream - virtual std::ostream& write(serialize& ms, std::ostream& os) = 0; - - /// Inheriting class implements the read function. Read each - /// class member from the istream. Read in the same order as write(). - /// Each level within the hierarchy must implement. Ensure base - /// read() implementation is called if necessary. - /// @param[in] ms - the message serialize instance - /// @param[in] is - the input stream - /// @return The input stream - virtual std::istream& read(serialize& ms, std::istream& is) = 0; - }; - - enum class Type - { - UNKNOWN = 0, - LITERAL = 1, - STRING = 8, - WSTRING = 9, - VECTOR = 20, - MAP = 21, - LIST = 22, - SET = 23, - ENDIAN = 30, - USER_DEFINED = 31, - }; - - enum class ParsingError - { - NONE, - TYPE_MISMATCH, - STREAM_ERROR, - NON_SEEKABLE_STREAM, // Stream does not support tellp/seekp (required for objects) - STRING_TOO_LONG, - CONTAINER_TOO_MANY, - INVALID_INPUT, - END_OF_FILE, - NESTING_TOO_DEEP // USER_DEFINED nesting exceeded MAX_PARSE_STACK_DEPTH - }; - - serialize() = default; - ~serialize() = default; - - /// Returns true if the host is little-endian. - /// @return Returns true if little-endian. - static bool LE() - { - const static int n = 1; - const static bool le = (*reinterpret_cast(&n) == 1); - return le; - } - - /// Read endian from stream. - /// @param[in] is - input stream - /// @param[out] littleEndian - set to true if stream was written on a little-endian host - /// @return The input stream. - std::istream& readEndian(std::istream& is, bool& littleEndian) - { - if (read_type(is, Type::ENDIAN)) - { - is.read(reinterpret_cast(&littleEndian), sizeof(littleEndian)); - } - return is; - } - - /// Write current CPU endian to stream. - /// @param[in] os - output stream - void writeEndian(std::ostream& os) - { - bool littleEndian = LE(); - write_type(os, Type::ENDIAN); - os.write(reinterpret_cast(&littleEndian), sizeof(littleEndian)); - } - - /// Read a user defined object implementing the serialize::I interface from a stream. - /// Normally the sender and receiver object is the same size. However, if a newer version of - /// the object is introduced on one side the sizes will differ. If received object is smaller - /// than sent object, the extra data in the sent object is discarded. - /// @param[in] is - the input stream - /// @param[in] t_ - the object to read - /// @return The input stream - std::istream& read(std::istream& is, I* t_) - { - if (check_stop_parse(is)) - return is; - - if (check_pointer(is, t_)) - { - if (read_type(is, Type::USER_DEFINED)) - { - uint16_t size = 0; - std::streampos startPos = is.tellg(); - if (startPos == std::streampos(-1)) - { - raiseError(ParsingError::NON_SEEKABLE_STREAM, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - - read(is, size, false); - - std::streampos targetStopPos = startPos + std::streampos(size); - - // Bounds check: ensure size does not exceed stream EOF - std::streampos dataPos = is.tellg(); - is.seekg(0, std::ios::end); - std::streampos endPosStream = is.tellg(); - is.seekg(dataPos); - - if (targetStopPos > endPosStream) { - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - - // Bounds check: ensure size does not exceed parent object's bounds - if (stopParsePosIdx > 0 && targetStopPos > stopParsePosStack[stopParsePosIdx - 1]) { - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - - parseStatus(typeid(*t_), size); - - // Save the stop parsing position to prevent parsing overrun - if (!push_stop_parse_pos(targetStopPos)) { - raiseError(ParsingError::NESTING_TOO_DEEP, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - - t_->read(*this, is); - - pop_stop_parse_pos(); - - if (is.good()) - { - std::streampos endPos = is.tellg(); - uint16_t rcvdSize = static_cast(endPos - startPos); - - // Did sender send a larger object than what receiver parsed? - if (rcvdSize < size) - { - // Skip over the extra received data - uint16_t seekOffset = size - rcvdSize; - is.seekg(seekOffset, std::ios_base::cur); - } - } - return is; - } - } - return is; - } - - /// Read a std::string from a stream. - /// @param[in] is - the input stream - /// @param[in] s - the string to read - /// @return The input stream - template - std::istream& read(std::istream& is, std::basic_string& s) - { - if (check_stop_parse(is)) - return is; - - if (read_type(is, Type::STRING)) - { - uint16_t size = 0; - read(is, size, false); - s.clear(); - if (check_stream(is) && check_slength(is, size)) - { - s.resize(size); - parseStatus(typeid(s), s.size()); - read_internal(is, &s[0], size, true); - } - } - return is; - } - - /// Read a std::wstring from a stream. - /// @param[in] is - the input stream - /// @param[in] s - the string to read - /// @return The input stream - template - std::istream& read(std::istream& is, std::basic_string& s) - { - if (check_stop_parse(is)) - return is; - - if (read_type(is, Type::WSTRING)) - { - uint16_t size = 0; - read(is, size, false); - s.clear(); - if (check_stream(is) && check_slength(is, size)) - { - s.resize(size); - parseStatus(typeid(s), s.size()); - for (uint16_t ii = 0; ii < size; ii++) - { - wchar_t c = 0; - int offset = LE() ? 0 : (sizeof(wchar_t) - WCHAR_SIZE); - read_internal(is, reinterpret_cast(&c) + offset, WCHAR_SIZE); - s[ii] = c; - } - } - } - return is; - } - - /// Read a character string from a stream. - /// @param[in] is - the input stream - /// @param[in] str - the character string to read into - /// @param[in] maxLen - the capacity of str in bytes (including null terminator) - /// @return The input stream - std::istream& read(std::istream& is, char* str, size_t maxLen) - { - if (check_stop_parse(is)) - return is; - - if (read_type(is, Type::STRING)) - { - uint16_t size = 0; - read(is, size, false); - if (!check_stream(is) || !check_pointer(is, str)) - return is; - if (maxLen == 0) - { - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - // Leave str a valid (empty) C string on every early return below. - // An empty std::string is sent with size 0 and no bytes. - str[0] = '\0'; - if (size == 0) - return is; - if (!check_slength(is, size)) - return is; - if (size > maxLen) - { - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - parseStatus(typeid(str), size); - read_internal(is, str, size, true); - - // Truncated stream: is.read() stopped early, so str[gcount()..size-1] - // is uninitialized. Report the stream error, not STRING_TOO_LONG. - if (!check_stream(is)) - { - str[0] = '\0'; - return is; - } - - // Strings go out without a terminator (older versions sent one with - // a const char*). Terminate here if the data didn't, failing if - // there's no room. - if (str[size - 1] != '\0') - { - if (size < maxLen) - { - str[size] = '\0'; - } - else - { - str[maxLen - 1] = '\0'; - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - } - } - } - return is; - } - - /// Read a vector container from a stream. The vector items are - /// stored differently and therefore need special handling to serialize. - /// Unlike other specializations of vector, std::vector does not manage a - /// dynamic array of bool objects. Instead, it is supposed to pack the boolean - /// values into a single bit each. - /// @param[in] is - the input stream - /// @param[in] container - the vector container to read into - /// @return The input stream - std::istream& read(std::istream& is, std::vector& container) - { - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::VECTOR)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - // One allocation of the final size instead of regrowing per element. - container.reserve(size); - for (uint16_t i = 0; i < size; ++i) - { - bool t; - read(is, t); - container.push_back(t); - } - } - } - return is; - } - - /// Write a user defined object implementing the serialize::I interface to a stream. - /// @note The stream must support seekp(). The object size is backfilled after writing. - /// @param[in] os - the output stream - /// @param[in] t_ - the object to write - /// @return The output stream - std::ostream& write(std::ostream& os, I* t_) - { - if (check_pointer(os, t_)) - { - uint16_t elementSize = 0; - - write_type(os, Type::USER_DEFINED); - std::streampos elementSizePos = os.tellp(); - if (elementSizePos == std::streampos(-1)) - { - raiseError(ParsingError::NON_SEEKABLE_STREAM, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - write(os, elementSize, false); - - // Write user defined object - t_->write(*this, os); - - if (os.good()) - { - // Backfill the object size into the stream (requires seekable stream) - std::streampos currentPos = os.tellp(); - os.seekp(elementSizePos); - auto sizeDiff = currentPos - elementSizePos; - if (sizeDiff > UINT16_MAX) { - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - elementSize = static_cast(sizeDiff); - write(os, elementSize, false); - os.seekp(currentPos); - } - return os; - } - return os; - } - - /// Write a const std::string to a stream. - /// @param[in] os - the output stream - /// @param[in] s - the string to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::basic_string& s) - { - if (s.size() > MAX_STRING_SIZE) { - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(s.size()); - write_type(os, Type::STRING); - write(os, size, false); - if (check_stream(os) && check_slength(os, size)) - { - write_internal(os, s.c_str(), size, true); - } - return os; - } - - /// Write a std::string to a stream. - /// @param[in] os - the output stream - /// @param[in] s - the string to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, std::basic_string& s) - { - return write(os, static_cast&>(s)); - } - - /// Write a const std::wstring to a stream. - /// @param[in] os - the output stream - /// @param[in] s - the string to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::basic_string& s) - { - if (s.size() > MAX_STRING_SIZE) { - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(s.size()); - write_type(os, Type::WSTRING); - write(os, size, false); - if (check_stream(os) && check_slength(os, size)) - { - for (uint16_t ii = 0; ii < size; ii++) - { - wchar_t c = s[ii]; - int offset = LE() ? 0 : (sizeof(wchar_t) - WCHAR_SIZE); - write_internal(os, reinterpret_cast(&c) + offset, WCHAR_SIZE); - } - } - return os; - } - - /// Write a std::wstring to a stream. - /// @param[in] os - the output stream - /// @param[in] s - the string to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, std::basic_string& s) - { - return write(os, static_cast&>(s)); - } - - /// Write a character string to a stream. - /// @param[in] os - the output stream - /// @param[in] str - the character string to write. - /// @return The output stream - std::ostream& write(std::ostream& os, char* str) - { - return write(os, static_cast(str)); - } - - /// Write a const character string to a stream. - /// @param[in] os - the output stream - /// @param[in] str - the character string to write. - /// @return The output stream - std::ostream& write(std::ostream& os, const char* str) - { - if (check_pointer(os, str)) - { - // Check before narrowing: a length over 65535 would wrap the 16-bit - // size and silently send a truncated string. - const size_t len = strlen(str); - if (len > MAX_STRING_SIZE) - { - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - // No terminator on the wire, the same as std::string: the reader - // adds one for a char buffer, and a std::string keeps every byte. - uint16_t size = static_cast(len); - write_type(os, Type::STRING); - write(os, size, false); - if (check_stream(os) && check_slength(os, size)) - { - write_internal(os, str, size, true); - } - } - return os; - } - - /// Write a vector container to a stream. The vector items are - /// stored differently and therefore need special handling to serialize. - /// Unlike other specializations of vector, std::vector does not manage a - /// dynamic array of bool objects. Instead, it is supposed to pack the boolean - /// values into a single bit each. - /// @param[in] os - the output stream - /// @param[in] container - the vector container to write - /// @return The output stream - std::ostream& write(std::ostream& os, const std::vector& container) - { - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::VECTOR); - write(os, size, false); - if (check_stream(os) && check_container_size(os, size)) - { - for (const bool& c : container) - { - write(os, c); - } - } - return os; - } - - /// Read an object from a stream. - /// @param[in] is - the input stream - /// @param[in] t_ - the object to read into - /// @return The input stream - template - std::istream& read(std::istream& is, T& t_, bool readPrependedType = true) - { - static_assert(!serialize_traits::is_unsupported_container::value, "Unsupported C++ container type"); - - static_assert(!(std::is_pointer::value && - (std::is_arithmetic::type>::value || - std::is_class::type>::value)), - "T cannot be a pointer to a built-in or custom data type. Use values instead."); - - // Same check as write(): any other class type would be cast to I* below. - static_assert(!std::is_class::value || std::is_base_of::value, - "T must inherit from serialize::I"); - - if (check_stop_parse(is)) - return is; - - // If C++17 or higher -#if defined(_MSVC_LANG) && _MSVC_LANG >= 201703L || __cplusplus >= 201703L - // Check if T is a user-defined class - if constexpr (std::is_class::value) - { - // C-style cast required: T may be const-qualified (e.g. const AlarmMsg) - // when called from a const context, and neither static_cast nor - // reinterpret_cast can strip const. A C-style cast combines const_cast - // with the pointer conversion in one step. The static_assert above - // guarantees T derives from I whenever this branch is executed. - read(is, (serialize::I*)(&t_)); - return is; - } - else - { - // If T is not a class, handle built-in data types - if constexpr (std::is_pointer::value == false) - { - if (readPrependedType) - { - if (!read_type(is, Type::LITERAL)) - { - return is; - } - } - - if (readPrependedType) - parseStatus(typeid(t_), sizeof(t_)); - read_internal(is, reinterpret_cast(&t_), sizeof(t_)); - return is; - } - else - { - // Can't read pointers to built-in types - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - } -#else - // Is T a built-in data type (e.g. float, int, ...)? -#if defined(_MSC_VER) -#pragma warning(push) -#pragma warning(disable: 6326) -#endif - if (std::is_class::value == false) - { - // Is T is not a pointer type - if (std::is_pointer::value == false) - { - if (readPrependedType) - { - if (!read_type(is, Type::LITERAL)) - { - return is; - } - } - - if (readPrependedType) - parseStatus(typeid(t_), sizeof(t_)); - read_internal(is, reinterpret_cast(&t_), sizeof(t_)); - return is; - } - else - { - // Can't read pointers to built-in type - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - } - // Else T is a user defined data type (e.g. MyData) - else - { - // C-style cast required: without if constexpr (C++14) this branch is - // compiled for all T including primitives, so static_cast is rejected - // for non-class types. The branch is only reached when is_class is - // true, making the cast safe at runtime. - read(is, (serialize::I*)(&t_)); - return is; - } -#if defined(_MSC_VER) -#pragma warning(pop) -#endif -#endif - } - - /// Write an object to a stream. - /// @param[in] os - the output stream - /// @param[in] t_ - the object to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, T& t_, bool prependType = true) - { - static_assert(!serialize_traits::is_unsupported_container::value, "Unsupported C++ container type"); - - static_assert(!(std::is_pointer::value && - (std::is_arithmetic::type>::value || - std::is_class::type>::value)), - "T cannot be a pointer to a built-in or custom data type. Use values instead."); - - // When T is a class it must inherit from serialize::I. - // The combined form (!is_class || is_base_of) is valid for all T — non-class - // types satisfy the first clause so the assertion always passes for them. - static_assert(!std::is_class::value || std::is_base_of::value, - "T must inherit from serialize::I"); - - // If C++17 or higher -#if defined(_MSVC_LANG) && _MSVC_LANG >= 201703L || __cplusplus >= 201703L - // Check if T is a user-defined class - if constexpr (std::is_class::value) - { - // C-style cast required: T may be const-qualified (e.g. const AlarmMsg) - // when called from a const context, and neither static_cast nor - // reinterpret_cast can strip const. A C-style cast combines const_cast - // with the pointer conversion in one step. The static_assert above - // guarantees T derives from I whenever this branch is executed. - return write(os, (serialize::I*)(&t_)); - } - else - { - // If T is not a class, handle built-in data types - if constexpr (std::is_pointer::value == false) - { - if (prependType) - { - write_type(os, Type::LITERAL); - } - return write_internal(os, reinterpret_cast(&t_), sizeof(t_)); - } - else - { - // Can't write pointers to built-in types - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - } -#else - // Is T type a built-in data type (e.g. float, int, ...)? -#if defined(_MSC_VER) -#pragma warning(push) -#pragma warning(disable: 6326) -#endif - if (std::is_class::value == false) - { - // Is T is not a pointer type - if (std::is_pointer::value == false) - { - if (prependType) - { - write_type(os, Type::LITERAL); - } - return write_internal(os, reinterpret_cast(&t_), sizeof(t_)); - } - else - { - // Can't write pointers to built-in type - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - } - // Else T type is a user defined data type (e.g. MyData) - else - { - // C-style cast required: without if constexpr (C++14) this branch is - // compiled for all T including primitives, so static_cast and static_assert - // are rejected for non-class types. The branch is only reached when - // is_class is true, making the cast safe at runtime. - return write(os, (serialize::I*)(&t_)); - } -#if defined(_MSC_VER) -#pragma warning(pop) -#endif -#endif - } - - /// Write a vector container to a stream. The items in vector are stored - /// by value. - /// @param[in] os - the output stream - /// @param[in] container - the vector container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::vector& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type T must not be a shared_ptr type"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::VECTOR); - write(os, size, false); - if (check_stream(os) && check_container_size(os, size)) - { - for (const auto& item : container) - { - write_element(os, item); - } - } - return os; - } - - /// Read into a vector container from a stream. Items in vector are stored - /// by value. - /// @param[in] is - the input stream - /// @param[in] container - the vector container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::vector& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type T must not be a shared_ptr type"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::VECTOR)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - // One allocation of the final size instead of regrowing per element. - container.reserve(size); - for (uint16_t i = 0; i < size; ++i) - { - T t; - read_element(is, t); - container.push_back(t); - } - } - } - return is; - } - - /// Write a vector container to a stream. The items in vector are stored - /// by pointer. - /// @param[in] os - the output stream - /// @param[in] container - the vector container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::vector& container) - { - static_assert(std::is_base_of::value, "Type T must be derived from serialize::I"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::VECTOR); - write(os, size, false); - - if (check_stream(os) && check_container_size(os, size)) - { - for (auto* ptr : container) - { - if (ptr != nullptr) - { - bool notNULL = true; - write(os, notNULL, false); - - auto* i = static_cast(ptr); - write(os, i); - } - else - { - bool notNULL = false; - write(os, notNULL, false); - } - } - - } - return os; - } - - /// Read into a vector container from a stream. Items in vector stored - /// by pointer. Operator new called to create object instances. - /// @param[in] is - the input stream - /// @param[in] container - the vector container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::vector& container) - { - static_assert(std::is_base_of::value, "Type T must be derived from serialize::I"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::VECTOR)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - // One allocation of the final size instead of regrowing per element. - container.reserve(size); - for (uint16_t i = 0; i < size; ++i) - { - bool notNULL = false; - read(is, notNULL, false); - - if (notNULL) - { - T* object = new T; - auto* iface = static_cast(object); - read(is, iface); - container.push_back(object); - } - else - { - container.push_back(nullptr); - } - } - } - } - return is; - } - - /// Write a map container to a stream. The items in map are stored - /// by value. - /// @param[in] os - the output stream - /// @param[in] container - the map container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::map& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type V must not be a shared_ptr type"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::MAP); - write(os, size, false); - if (check_stream(os) && check_container_size(os, size)) - { - for (const auto& entry : container) - { - write_element(os, entry.first); - write_element(os, entry.second); - } - } - return os; - } - - /// Read into a map container from a stream. Items in map are stored - /// by value. - /// @param[in] is - the input stream - /// @param[in] container - the map container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::map& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type V must not be a shared_ptr type"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::MAP)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - for (uint16_t i = 0; i < size; ++i) - { - K key; - V value; - read_element(is, key); - read_element(is, value); - container[key] = value; - } - } - } - return is; - } - - /// Write a map container to a stream. The items in map are stored - /// by pointer. - /// @param[in] os - the output stream - /// @param[in] container - the map container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::map& container) - { - static_assert(std::is_base_of::value, "Type V must be derived from serialize::I"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::MAP); - write(os, size, false); - - if (check_stream(os) && check_container_size(os, size)) - { - for (const auto& entry : container) - { - write_element(os, entry.first); - - if (entry.second != nullptr) - { - bool notNULL = true; - write(os, notNULL, false); - - auto* i = static_cast(entry.second); - write(os, i); - } - else - { - bool notNULL = false; - write(os, notNULL, false); - } - } - } - return os; - } - - /// Read into a map container from a stream. Items in map stored - /// by pointer. Operator new called to create object instances. - /// @param[in] is - the input stream - /// @param[in] container - the map container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::map& container) - { - static_assert(std::is_base_of::value, "Type V must be derived from serialize::I"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::MAP)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - for (uint16_t i = 0; i < size; ++i) - { - K key; - read_element(is, key); - bool notNULL; - read(is, notNULL, false); - if (notNULL) - { - V* object = new V; - auto* iface = static_cast(object); - read(is, iface); - container[key] = static_cast(object); - } - else - { - container[key] = nullptr; - } - } - } - } - return is; - } - - /// Write a set container to a stream. The items in set are stored - /// by value. - /// @param[in] os - the output stream - /// @param[in] container - the set container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::set& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type T must not be a shared_ptr type"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::SET); - write(os, size, false); - - if (check_stream(os) && check_container_size(os, size)) - { - for (const auto& item : container) - { - write_element(os, item); - } - } - return os; - } - - /// Read into a set container from a stream. Items in set are stored - /// by value. - /// @param[in] is - the input stream - /// @param[in] container - the set container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::set& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type T must not be a shared_ptr type"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::SET)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - for (uint16_t i = 0; i < size; ++i) - { - T t; - read_element(is, t); - container.insert(t); - } - } - } - return is; - } - - /// Write a set container to a stream. The items in set are stored - /// by pointer. - /// @param[in] os - the output stream - /// @param[in] container - the set container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::set& container) - { - static_assert(std::is_base_of::value, "Type T must be derived from serialize::I"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::SET); - write(os, size, false); - if (check_stream(os) && check_container_size(os, size)) - { - for (auto ptr : container) - { - if (ptr != nullptr) - { - bool notNULL = true; - write(os, notNULL, false); - - auto* i = static_cast(ptr); - write(os, i); - } - else - { - bool notNULL = false; - write(os, notNULL, false); - } - } - } - return os; - } - - /// Read into a set container from a stream. Items in set stored - /// by pointer. Operator new called to create object instances. - /// @param[in] is - the input stream - /// @param[in] container - the set container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::set& container) - { - static_assert(std::is_base_of::value, "Type T must be derived from serialize::I"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::SET)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - for (uint16_t i = 0; i < size; ++i) - { - bool notNULL = false; - read(is, notNULL, false); - if (notNULL) - { - T* object = new T; - auto* iface = static_cast(object); - read(is, iface); - container.insert(object); - } - else - { - container.insert(nullptr); - } - } - } - } - return is; - } - - /// Write a list container to a stream. The items in list are stored - /// by value. - /// @param[in] os - the output stream - /// @param[in] container - the list container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::list& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type T must not be a shared_ptr type"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::LIST); - write(os, size, false); - - if (check_stream(os) && check_container_size(os, size)) - { - for (const auto& item : container) - { - write_element(os, item); - } - } - return os; - } - - /// Read into a list container from a stream. Items in list are stored - /// by value. - /// @param[in] is - the input stream - /// @param[in] container - the list container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::list& container) - { - static_assert(!serialize_traits::is_shared_ptr::value, "Type T must not be a shared_ptr type"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::LIST)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - for (uint16_t i = 0; i < size; ++i) - { - T t; - read_element(is, t); - container.push_back(t); - } - } - } - return is; - } - - /// Write a list container to a stream. The items in list are stored - /// by pointer. - /// @param[in] os - the output stream - /// @param[in] container - the list container to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::list& container) - { - static_assert(std::is_base_of::value, "Type T must be derived from serialize::I"); - - if (container.size() > MAX_CONTAINER_SIZE) { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - uint16_t size = static_cast(container.size()); - write_type(os, Type::LIST); - write(os, size, false); - - if (check_stream(os) && check_container_size(os, size)) - { - for (auto* ptr : container) - { - if (ptr != nullptr) - { - bool notNULL = true; - write(os, notNULL, false); - - auto* i = static_cast(ptr); - write(os, i); - } - else - { - bool notNULL = false; - write(os, notNULL, false); - } - } - } - return os; - } - - /// Read into a list container from a stream. Items in list stored - /// by pointer. Operator new called to create object instances. - /// @param[in] is - the input stream - /// @param[in] container - the list container to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::list& container) - { - static_assert(std::is_base_of::value, "Type T must be derived from serialize::I"); - - if (check_stop_parse(is)) - return is; - - container.clear(); - if (read_type(is, Type::LIST)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - parseStatus(typeid(container), size); - for (uint16_t i = 0; i < size; ++i) - { - bool notNULL = false; - read(is, notNULL, false); - if (notNULL) - { - T* object = new T; - auto* iface = static_cast(object); - read(is, iface); - container.push_back(object); - } - else - { - container.push_back(nullptr); - } - } - } - } - return is; - } - - /// Write a std::array. Uses the VECTOR type marker on purpose (no separate ARRAY - /// type), so the bytes match a std::vector and one side can declare the field as - /// std::vector while the other uses std::array. The element count on the - /// wire is what catches a mismatch: the array read requires exactly N. A fixed-size - /// array needs no allocation, which suits fixed-block / no-heap targets. - /// @param[in] os - the output stream - /// @param[in] container - the array to write - /// @return The output stream - template - std::ostream& write(std::ostream& os, const std::array& container) - { - static_assert(N <= MAX_CONTAINER_SIZE, "std::array larger than DMQ_SERIALIZE_MAX_CONTAINER_SIZE"); - static_assert(!std::is_pointer::value, "std::array of pointers is not supported"); - write_type(os, Type::VECTOR); - uint16_t size = static_cast(N); - write(os, size, false); - if (check_stream(os)) - { - for (const auto& item : container) - write_element(os, item); - } - return os; - } - - /// Read into a std::array. Accepts the VECTOR type marker, so it reads data - /// written from a std::vector or a std::array. The received element count must - /// equal N; otherwise the read fails (INVALID_INPUT) and the array is unchanged. - /// A list, set or map fails with TYPE_MISMATCH. - /// @param[in] is - the input stream - /// @param[in] container - the array to read into - /// @return The input stream - template - std::istream& read(std::istream& is, std::array& container) - { - static_assert(N <= MAX_CONTAINER_SIZE, "std::array larger than DMQ_SERIALIZE_MAX_CONTAINER_SIZE"); - static_assert(!std::is_pointer::value, "std::array of pointers is not supported"); - - if (check_stop_parse(is)) - return is; - - if (read_type(is, Type::VECTOR)) - { - uint16_t size = 0; - read(is, size, false); - if (check_stream(is) && check_container_size(is, size)) - { - if (size != N) - { - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return is; - } - parseStatus(typeid(container), size); - for (auto& item : container) - read_element(is, item); - } - } - return is; - } - - // Non-const containers forward to the const overloads above. Without these, - // a non-const container binds better to the generic write(os, T&, bool) - // template than to a const overload, and fails its static_assert. - std::ostream& write(std::ostream& os, std::vector& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::vector& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::vector& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::map& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::map& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::set& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::set& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::list& container) - { - return write(os, static_cast&>(container)); - } - template - std::ostream& write(std::ostream& os, std::list& container) - { - return write(os, static_cast&>(container)); - } - - template - std::ostream& write(std::ostream& os, std::array& container) - { - return write(os, static_cast&>(container)); - } - - typedef void (*ErrorHandler)(ParsingError error, int line, const char* file); - void setErrorHandler(ErrorHandler error_handler_) - { - error_handler = error_handler_; - } - - ParsingError getLastError() const { return lastError; } - void clearLastError() { lastError = ParsingError::NONE; } - - typedef void (*ParseHandler)(const std::type_info& typeId, size_t size); - void setParseHandler(ParseHandler parse_handler_) - { - parse_handler = parse_handler_; - } - -private: - /// Write/read one container element (or map key). Strings and nested - /// containers go to their own overloads (with their type prefix and size); - /// everything else to write()/read() without a type prefix. A 3-argument - /// write(os, x, false) on a string or container would pick the generic - /// template instead, which only handles literals and serialize::I types. - template - std::ostream& write_element(std::ostream& os, const std::basic_string& s) - { - return write(os, s); - } - - template - std::ostream& write_element(std::ostream& os, const std::vector& c) - { - return write(os, c); - } - - template - std::ostream& write_element(std::ostream& os, const std::list& c) - { - return write(os, c); - } - - template - std::ostream& write_element(std::ostream& os, const std::set& c) - { - return write(os, c); - } - - template - std::ostream& write_element(std::ostream& os, const std::map& c) - { - return write(os, c); - } - - template - std::ostream& write_element(std::ostream& os, const std::array& c) - { - return write(os, c); - } - - template - std::ostream& write_element(std::ostream& os, const T& t_) - { - return write(os, t_, false); - } - - template - std::istream& read_element(std::istream& is, std::basic_string& s) - { - return read(is, s); - } - - template - std::istream& read_element(std::istream& is, std::vector& c) - { - return read(is, c); - } - - template - std::istream& read_element(std::istream& is, std::list& c) - { - return read(is, c); - } - - template - std::istream& read_element(std::istream& is, std::set& c) - { - return read(is, c); - } - - template - std::istream& read_element(std::istream& is, std::map& c) - { - return read(is, c); - } - - template - std::istream& read_element(std::istream& is, std::array& c) - { - return read(is, c); - } - - template - std::istream& read_element(std::istream& is, T& t_) - { - return read(is, t_, false); - } - - /// Read from stream into caller's character buffer. - /// Wire format is little-endian. On a big-endian host the bytes are reversed - /// after the read so that multi-byte values are correctly stored in memory. - /// @param[in] is - input stream - /// @param[out] p - buffer to receive the bytes - /// @param[in] size - number of bytes to read - /// @param[in] no_swap - true suppresses byte-order reversal (used for char arrays) - /// @return The input stream. - std::istream& read_internal(std::istream& is, char* p, uint32_t size, bool no_swap = false) - { - if (check_stop_parse(is)) - return is; - - if (!check_pointer(is, p)) - return is; - - // Single read for all bytes, then reverse in-place when host is big-endian - is.read(p, size); - if (!LE() && !no_swap && size > 1) - std::reverse(p, p + size); - - return is; - } - - /// Write bytes from caller's buffer to stream. - /// Wire format is little-endian. On a big-endian host the bytes are reversed - /// before writing so that multi-byte values appear in little-endian order on the wire. - /// @param[in] os - output stream - /// @param[in] p - bytes to write - /// @param[in] size - number of bytes to write - /// @param[in] no_swap - true suppresses byte-order reversal (used for char arrays) - /// @return The output stream. - std::ostream& write_internal(std::ostream& os, const char* p, uint32_t size, bool no_swap = false) - { - if (!check_pointer(os, p)) - return os; - - if (!LE() && !no_swap && size > 1) - { - if (size > 8) - { - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - os.setstate(std::ios::failbit); - return os; - } - - // Reverse bytes into a small stack buffer then write in a single call. - // Primitives are at most 8 bytes (double / int64_t). - char tmp[8]; - for (uint32_t i = 0; i < size; ++i) - tmp[i] = p[size - 1 - i]; - os.write(tmp, size); - } - else - { - os.write(p, size); - } - return os; - } - - // Maximum sizes allowed by parser (DMQ_SERIALIZE_* in DelegateMQConfig.h) - static constexpr uint16_t MAX_STRING_SIZE = dmq::SERIALIZE_MAX_STRING_SIZE; - static constexpr uint16_t MAX_CONTAINER_SIZE = dmq::SERIALIZE_MAX_CONTAINER_SIZE; - - // Keep wchar_t serialize size consistent on any platform - static const size_t WCHAR_SIZE = 2; - - // LIFO stack used to track stop-parse positions for versioned object reads. - static constexpr size_t MAX_PARSE_STACK_DEPTH = dmq::SERIALIZE_MAX_NESTING; - std::array stopParsePosStack; - size_t stopParsePosIdx = 0; - - ErrorHandler error_handler = nullptr; - ParsingError lastError = ParsingError::NONE; - void raiseError(ParsingError error, int line, const char* file) - { - lastError = error; - if (error_handler) - error_handler(error, line, file); - } - - ParseHandler parse_handler = nullptr; - void parseStatus(const std::type_info& typeId, size_t size = 0) const - { - if (parse_handler) - parse_handler(typeId, size); - } - - void write_type(std::ostream& os, Type type_) - { - uint8_t type = static_cast(type_); - write_internal(os, reinterpret_cast(&type), sizeof(type)); - } - - bool read_type(std::istream& is, Type type_) - { - // Check for end-of-stream before attempting the cast - auto peeked = is.peek(); - if (peeked == std::istream::traits_type::eof()) - { - raiseError(ParsingError::END_OF_FILE, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return false; - } - Type type = static_cast(peeked); - if (type == type_) - { - uint8_t typeByte = 0; - read_internal(is, reinterpret_cast(&typeByte), sizeof(typeByte)); - return true; - } - else - { - raiseError(ParsingError::TYPE_MISMATCH, __LINE__, __FILE__); - is.setstate(std::ios::failbit); - return false; - } - } - - bool check_stream(std::ios& stream) - { - if (!stream.good()) - { - raiseError(ParsingError::STREAM_ERROR, __LINE__, __FILE__); - stream.setstate(std::ios::failbit); - } - return stream.good(); - } - - bool check_slength(std::ios& stream, int stringSize) - { - bool sizeOk = stringSize <= MAX_STRING_SIZE; - if (!sizeOk) - { - raiseError(ParsingError::STRING_TOO_LONG, __LINE__, __FILE__); - stream.setstate(std::ios::failbit); - } - if (stringSize == 0) - return false; - return sizeOk; - } - - bool check_container_size(std::ios& stream, int containerSize) - { - bool sizeOk = containerSize <= MAX_CONTAINER_SIZE; - if (!sizeOk) - { - raiseError(ParsingError::CONTAINER_TOO_MANY, __LINE__, __FILE__); - stream.setstate(std::ios::failbit); - } - return sizeOk; - } - - bool check_pointer(std::ios& stream, const void* ptr) - { - if (!ptr) - { - raiseError(ParsingError::INVALID_INPUT, __LINE__, __FILE__); - stream.setstate(std::ios::failbit); - } - return ptr != nullptr; - } - - // Returns false if the stack is full (nesting too deep) instead of faulting — - // reachable from remote/untrusted input (deserializing a USER_DEFINED object - // nested more than MAX_PARSE_STACK_DEPTH levels deep), so a malformed message - // must fail that one parse, not hard-fault the process. Caller must not call - // pop_stop_parse_pos() for a push that returned false. - bool push_stop_parse_pos(std::streampos stopParsePos) - { - if (stopParsePosIdx >= MAX_PARSE_STACK_DEPTH) - return false; - stopParsePosStack[stopParsePosIdx++] = stopParsePos; - return true; - } - - // Every call site pairs this 1:1 with a push_stop_parse_pos() that returned - // true, so an empty stack here means internal state corruption, not malformed - // input — stays a hard fault. - std::streampos pop_stop_parse_pos() - { - DMQ_ASSERT_TRUE(stopParsePosIdx > 0); - return stopParsePosStack[--stopParsePosIdx]; - } - - bool check_stop_parse(std::istream& is) - { - if (is.eof()) - { - raiseError(ParsingError::END_OF_FILE, __LINE__, __FILE__); - return true; - } - if (stopParsePosIdx > 0) - { - std::streampos stopParsePos = stopParsePosStack[stopParsePosIdx - 1]; - if (is.tellg() >= stopParsePos) - { - return true; - } - } - return false; - } -}; - -#endif // MSG_SERIALIZE_H_ \ No newline at end of file diff --git a/DelegateMQ/port/transport/README.md b/DelegateMQ/port/transport/README.md deleted file mode 100644 index 00e097d..0000000 --- a/DelegateMQ/port/transport/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# Transports (DelegateMQ Abstraction Layer) - -This directory contains the transport part of the **DelegateMQ Abstraction Layer**: the `ITransport` implementations that enable remote function invocation across various physical media and protocols. - -## Core Interfaces - -* **`dmq::transport::ITransport`**: The abstract base class that all transport implementations must inherit from. Defines the `Send()` and `Receive()` contract. -* **`dmq::transport::DmqHeader`**: Defines the protocol header structure (Marker, ID, Sequence Number, Length) used for framing messages. -* **`dmq::transport::ITransportMonitor`**: Interface for reliability monitoring (ACKs, timeouts, and retries). - -## Implementations - -The subdirectories contain ready-to-use transport implementations for specific platforms and libraries: - -### Network (IP-based) -* **`zeromq`**: High-performance asynchronous messaging using **ZeroMQ**. -* **`nng`**: Scalability protocols using **NNG** (Nanomsg Next Gen). -* **`mqtt`**: Publish/Subscribe messaging using **Paho MQTT**. -* **`linux-tcp` / `linux-udp`**: Standard BSD socket implementations for Linux. -* **`win32-tcp` / `win32-udp`**: Winsock implementations for Windows. -* **`arm-lwip-udp`**: Lightweight IP (lwIP) raw-API implementation for embedded ARM (FreeRTOS/Bare-metal). -* **`arm-lwip-netconn-udp`**: lwIP netconn-API UDP implementation for RTOS targets (selected via `DMQ_TRANSPORT_ARM_LWIP_NETCONN_UDP`). -* **`netx-udp`**: Azure RTOS **NetX / NetX Duo** implementation for ThreadX (selected via `DMQ_TRANSPORT_THREADX_UDP`). -* **`zephyr-udp`**: Native **Zephyr Networking** (BSD Socket API) implementation for Zephyr RTOS. - -### IPC & Serial -* **`win32-pipe`**: Inter-Process Communication (IPC) using Windows Named Pipes. -* **`linux-uds`**: Inter-Process Communication (IPC) using Linux Unix domain datagram sockets (`AF_UNIX`, `SOCK_DGRAM`). Duplex, path-addressed, no start-order dependency. A stale socket file left by a crashed process is reused; a path still bound by a live process makes `Create()` fail. Socket access follows the directory's permissions, so prefer a per-user directory such as `$XDG_RUNTIME_DIR` over `/tmp` when other local users must not be able to send. Selected via `DMQ_TRANSPORT_LINUX_UDS`. -* **`serial`**: Serial port (UART/RS-232) transport using **libserialport**. -* **`stm32-uart`**: Interrupt-driven STM32 HAL UART transport for embedded targets (selected via `DMQ_TRANSPORT_STM32_UART`). - -## Usage - -To use a specific transport, simply include the corresponding header in your application and inject it into your `dmq::Dispatcher` or `dmq::DelegateRemote`. - -```cpp -// Example: Using UDP on Windows -#include "port/transport/win32-udp/Win32UdpTransport.h" - -dmq::transport::Win32UdpTransport transport; -transport.Create(dmq::transport::Win32UdpTransport::Type::PUB, "127.0.0.1", 5000); - -// Link transport to the dispatcher -dispatcher.SetTransport(&transport); -``` diff --git a/DelegateMQ/port/transport/arm-lwip-netconn-udp/ArmLwipNetconnUdpTransport.h b/DelegateMQ/port/transport/arm-lwip-netconn-udp/ArmLwipNetconnUdpTransport.h deleted file mode 100644 index 8423fc9..0000000 --- a/DelegateMQ/port/transport/arm-lwip-netconn-udp/ArmLwipNetconnUdpTransport.h +++ /dev/null @@ -1,278 +0,0 @@ -#ifndef ARM_LWIP_NETCONN_UDP_TRANSPORT_H -#define ARM_LWIP_NETCONN_UDP_TRANSPORT_H - -/// @file ArmLwipNetconnUdpTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ARM lwIP Netconn UDP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the lwIP "Netconn" API. -/// This API is specific to lwIP+FreeRTOS and is more efficient than the BSD -/// Socket API as it avoids the socket wrapper overhead. -/// -/// Prerequisites: -/// - lwIP must be compiled with `LWIP_NETCONN=1` -/// - FreeRTOS must be running (Netconn relies on OS primitives) - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" - - -// lwIP Netconn Includes -#include "lwip/api.h" -#include "lwip/inet.h" -#include "lwip/ip_addr.h" - -#include -#include - -namespace dmq::transport { - -class NetconnUdpTransport : public ITransport -{ -public: - enum class Type - { - PUB, - SUB - }; - - NetconnUdpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~NetconnUdpTransport() - { - Close(); - } - - /// Initialize the Netconn UDP connection - /// @param type PUB or SUB - /// @param addr Target IP string (e.g. "192.168.1.50") for PUB; Ignored for SUB. - /// @param port Local port to bind (SUB) or Remote port to target (PUB). - /// @return 0 on success, -1 on failure - int Create(Type type, const char* addr, uint16_t port) - { - const dmq::LockGuard recvLock(m_recvMutex); - const dmq::LockGuard lock(m_mutex); - Close(); // a second Create() replaces the connection instead of leaking it - m_type = type; - m_remotePort = port; - - // 1. Create a new UDP connection - m_conn = netconn_new(NETCONN_UDP); - if (m_conn == nullptr) - { - return -1; - } - - // 2. Configure Address - if (type == Type::PUB) - { - // Parse string IP to LwIP ip_addr_t - if (ipaddr_aton(addr, &m_remoteIp) == 0) - { - Close(); // Prevent memory leak on invalid IP - return -1; - } - netconn_set_recvtimeout(m_conn, static_cast(dmq::UDP_PUB_RECV_TIMEOUT.count())); - } - else if (type == Type::SUB) - { - // Bind to all interfaces (IP_ADDR_ANY) on the specified port - if (netconn_bind(m_conn, IP_ADDR_ANY, port) != ERR_OK) - { - Close(); // Prevent memory leak on bind failure - return -1; - } - // Receive timeout, so the receive thread can check for exit - netconn_set_recvtimeout(m_conn, static_cast(dmq::UDP_SUB_RECV_TIMEOUT.count())); - } - - return 0; - } - - /// Clean up the netconn resources. Waits for a Receive() in progress on - /// another thread to return (at most its receive timeout) first. - void Close() - { - const dmq::LockGuard recvLock(m_recvMutex); - const dmq::LockGuard lock(m_mutex); - if (m_conn) - { - netconn_delete(m_conn); - m_conn = nullptr; - } - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - const dmq::LockGuard lock(m_mutex); - if (m_conn) - { - netconn_set_recvtimeout(m_conn, static_cast(timeout.count())); - } - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - const dmq::LockGuard lock(m_mutex); - if (os.bad() || os.fail() || !m_conn) { - return -1; - } - - // Only SUBs should block non-ACK traffic - if (m_type == Type::SUB && header.GetId() != dmq::ACK_REMOTE_ID) { - return -1; - } - - if (m_sendTransport != this) { - return -1; - } - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - // Allocate a Netbuf - struct netbuf* buf = netbuf_new(); - if (!buf) return -1; - - void* dataPtr = netbuf_alloc(buf, DmqHeader::HEADER_SIZE + payloadLen); - if (!dataPtr) { - netbuf_delete(buf); - return -1; - } - - // Copy to NetX/LwIP internal buffer - memcpy(dataPtr, m_sendBuffer, DmqHeader::HEADER_SIZE + payloadLen); - - // PUB uses pre-configured IP; SUB uses last-received IP (Reply) - err_t err = netconn_sendto(m_conn, buf, &m_remoteIp, m_remotePort); - - netbuf_delete(buf); - - if (err != ERR_OK) return -1; - - return 0; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - // m_recvMutex, not m_mutex: a Send() on another thread (e.g. a PUB that - // also drains its ACKs here) isn't held up for the receive timeout. - const dmq::LockGuard recvLock(m_recvMutex); - if (m_recvTransport != this || !m_conn) { - return -1; - } - - struct netbuf* buf = nullptr; - err_t err = netconn_recv(m_conn, &buf); - - if (err == ERR_TIMEOUT) return RECEIVE_NO_DATA; - if (err != ERR_OK || buf == nullptr) return -1; - - uint16_t len = netbuf_len(buf); - if (len < DmqHeader::HEADER_SIZE) { - netbuf_delete(buf); - return -1; - } - - // Read Header (Network Byte Order) - char headerBuf[DmqHeader::HEADER_SIZE]; - netbuf_copy(buf, headerBuf, DmqHeader::HEADER_SIZE); - - header.Decode(headerBuf); - - // One datagram is one message: the header length must match exactly - // and fit the buffer. Anything else is malformed and must not be - // delivered (cut short) or ACKed. - const uint16_t payloadSize = header.GetLength(); - if (!header.IsValid() || len != DmqHeader::HEADER_SIZE + payloadSize || - payloadSize > BUFFER_SIZE) { - netbuf_delete(buf); - return -1; - } - - // A SUB replies to whoever sent the last valid message. Only a SUB, and - // only now: a stray or malformed datagram must never redirect where a - // PUB sends. - if (m_type == Type::SUB) { - const dmq::LockGuard lock(m_mutex); - ip_addr_t* addr = netbuf_fromaddr(buf); - if (addr) ip_addr_copy(m_remoteIp, *addr); - m_remotePort = netbuf_fromport(buf); - } - - // Extract Payload - if (payloadSize > 0) { - netbuf_copy_partial(buf, m_recvBuffer, payloadSize, DmqHeader::HEADER_SIZE); - is.clear(); - is.str(""); - is.write(m_recvBuffer, payloadSize); - } - - netbuf_delete(buf); - - // Handle Reliability Logic - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - else if (m_sendTransport) { - // Auto-ACK using Send logic - dmq::xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - ack.SetLength(0); - m_sendTransport->Send(ss_ack, ack); - } - - return 0; - } - - void SetTransportMonitor(ITransportMonitor* monitor) { m_transportMonitor = monitor; } - void SetSendTransport(ITransport* transport) { m_sendTransport = transport; } - void SetRecvTransport(ITransport* transport) { m_recvTransport = transport; } - -private: - struct netconn* m_conn = nullptr; - ip_addr_t m_remoteIp{}; - uint16_t m_remotePort = 0; - Type m_type = Type::PUB; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - // Datagram buffer (header + payload): DMQ_UDP_BUFFER_SIZE, default the - // 1500-byte Ethernet MTU. - static constexpr size_t BUFFER_SIZE = dmq::UDP_BUFFER_SIZE; - char m_recvBuffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; ///< Connection open/close and Send() state (remote address) - dmq::RecursiveMutex m_recvMutex; ///< Held by Receive(); taken before m_mutex -}; - -} - -#endif // ARM_LWIP_NETCONN_UDP_TRANSPORT_H \ No newline at end of file diff --git a/DelegateMQ/port/transport/arm-lwip-udp/ArmLwipUdpTransport.h b/DelegateMQ/port/transport/arm-lwip-udp/ArmLwipUdpTransport.h deleted file mode 100644 index 1e38785..0000000 --- a/DelegateMQ/port/transport/arm-lwip-udp/ArmLwipUdpTransport.h +++ /dev/null @@ -1,297 +0,0 @@ -#ifndef ARM_LWIP_UDP_TRANSPORT_H -#define ARM_LWIP_UDP_TRANSPORT_H - -/// @file ArmLwipUdpTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief ARM lwIP UDP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the lwIP (Lightweight IP) -/// BSD-style socket API. It is designed for embedded ARM targets running FreeRTOS -/// (or similar) with the lwIP stack. -/// -/// Prerequisites: -/// - lwIP must be compiled with `LWIP_SOCKET=1` -/// - lwIP must be compiled with `LWIP_SO_RCVTIMEO=1` (for non-blocking timeouts) - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" - -// lwIP Includes -#include "lwip/sockets.h" -#include "lwip/inet.h" -#include "lwip/sys.h" -#include "lwip/api.h" - -#include -#include -#include - -// Ensure lwIP is configured correctly -#if !defined(LWIP_SO_RCVTIMEO) || LWIP_SO_RCVTIMEO == 0 - #error "ArmLwipUdpTransport requires LWIP_SO_RCVTIMEO=1 in lwipopts.h" -#endif - -namespace dmq::transport { - -class UdpTransport : public ITransport -{ -public: - enum class Type - { - PUB, - SUB - }; - - UdpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~UdpTransport() - { - Close(); - } - - int Create(Type type, const char* addr, uint16_t port) - { - const dmq::LockGuard recvLock(m_recvMutex); - const dmq::LockGuard lock(m_mutex); - Close(); // a second Create() replaces the socket instead of leaking it - m_type = type; - - // Create lwIP UDP socket - m_socket = lwip_socket(AF_INET, SOCK_DGRAM, 0); - if (m_socket < 0) - { - return -1; - } - - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); - - if (type == Type::PUB) - { - // Note: inet_aton in lwIP returns 1 on success - if (inet_aton(addr, &m_addr.sin_addr) == 0) - { - Close(); - return -1; - } - - // Short timeout so polling this socket for ACKs doesn't hang. - struct timeval timeout = ToTimeval(dmq::UDP_PUB_RECV_TIMEOUT); - - if (lwip_setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) - { - Close(); - return -1; - } - } - else if (type == Type::SUB) - { - m_addr.sin_addr.s_addr = INADDR_ANY; - - if (lwip_bind(m_socket, (struct sockaddr*)&m_addr, sizeof(m_addr)) < 0) - { - Close(); - return -1; - } - - // Receive timeout, so the receive thread can check for exit - struct timeval timeout = ToTimeval(dmq::UDP_SUB_RECV_TIMEOUT); - - if (lwip_setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) - { - Close(); - return -1; - } - } - - return 0; - } - - /// @details Waits for a Receive() in progress on another thread to return - /// (at most its receive timeout) before closing, so the socket is never - /// closed under it. - void Close() - { - const dmq::LockGuard recvLock(m_recvMutex); - const dmq::LockGuard lock(m_mutex); - if (m_socket >= 0) - { - lwip_close(m_socket); - m_socket = -1; - } - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - const dmq::LockGuard lock(m_mutex); - if (os.bad() || os.fail() || m_socket < 0) { - return -1; - } - - // Allow ACKs on SUB sockets. Block only regular data. - if (m_type == Type::SUB && header.GetId() != dmq::ACK_REMOTE_ID) { - return -1; - } - - if (m_sendTransport != this) { - return -1; - } - - // Get payload and set length on the copy - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Convert header fields to Network Byte Order (Big Endian) - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - ssize_t sent = lwip_sendto(m_socket, m_sendBuffer, totalSize, 0, - (struct sockaddr*)&m_addr, sizeof(m_addr)); - - if (sent != (ssize_t)totalSize) return -1; - - return 0; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - // m_recvMutex, not m_mutex: a Send() on another thread (e.g. a PUB socket - // that also drains its ACKs here) isn't held up for the receive timeout. - const dmq::LockGuard recvLock(m_recvMutex); - if (m_recvTransport != this || m_socket < 0) { - return -1; - } - - sockaddr_in fromAddr; - socklen_t addrLen = sizeof(fromAddr); - - // lwip_recvfrom - ssize_t size = lwip_recvfrom(m_socket, m_buffer, sizeof(m_buffer), 0, - (struct sockaddr*)&fromAddr, &addrLen); - - if (size < 0) - { - // Explicit check for timeout vs real error - if (errno == EWOULDBLOCK || errno == EAGAIN) - return RECEIVE_NO_DATA; - - // Real socket error - return -1; - } - - if (static_cast(size) < DmqHeader::HEADER_SIZE) { // size >= 0 here (checked above) - return -1; - } - - // 1. Read Header (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) - { - return -1; // Sync marker mismatch - } - - // 2. Extract Payload. One datagram is one message, so the header length - // must match exactly; anything else (including a datagram cut short by - // the buffer) is malformed and must not be delivered or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != static_cast(size) - DmqHeader::HEADER_SIZE) - return -1; - - // Update m_addr to the sender's address so we can ACK back. Only after - // validation, and under m_mutex since Send() uses it. - if (m_type == Type::SUB) { - const dmq::LockGuard lock(m_mutex); - m_addr = fromAddr; - } - - if (payloadSize > 0) { - is.clear(); - is.str(""); - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - if (header.GetId() == dmq::ACK_REMOTE_ID) - { - if (m_transportMonitor) - m_transportMonitor->Remove(header.GetSeqNum()); - } - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - else if (m_sendTransport) - { - // Send ACK back using Send logic (recursive mutex handles it) - xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - ack.SetLength(0); - m_sendTransport->Send(ss_ack, ack); - } - - return 0; - } - - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - void SetSendTransport(ITransport* sendTransport) - { - m_sendTransport = sendTransport; - } - - void SetRecvTransport(ITransport* recvTransport) - { - m_recvTransport = recvTransport; - } - -private: - int m_socket = -1; - sockaddr_in m_addr{}; - Type m_type = Type::PUB; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - static struct timeval ToTimeval(std::chrono::milliseconds ms) - { - struct timeval tv; - tv.tv_sec = static_cast(ms.count() / 1000); - tv.tv_usec = static_cast((ms.count() % 1000) * 1000); - return tv; - } - - // Datagram buffer (header + payload): DMQ_UDP_BUFFER_SIZE, default the - // 1500-byte Ethernet MTU. - static constexpr size_t BUFFER_SIZE = dmq::UDP_BUFFER_SIZE; - char m_buffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; ///< Socket open/close and Send() state (m_addr) - dmq::RecursiveMutex m_recvMutex; ///< Held by Receive(); taken before m_mutex -}; - -} - -#endif // ARM_LWIP_UDP_TRANSPORT_H \ No newline at end of file diff --git a/DelegateMQ/port/transport/common/DmqHeader.h b/DelegateMQ/port/transport/common/DmqHeader.h deleted file mode 100644 index a2ef56d..0000000 --- a/DelegateMQ/port/transport/common/DmqHeader.h +++ /dev/null @@ -1,130 +0,0 @@ -#ifndef DMQ_HEADER_H -#define DMQ_HEADER_H - -/// @file -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. - -#include "delegate/DelegateOpt.h" -#include -#include -#include - -namespace dmq::transport { - -/// @brief Header for remote delegate messages. -/// @details Stores values in host byte order. On the wire it is 10 bytes, every -/// multi-byte field big-endian (network byte order): -/// -/// | Offset | Size | Field | Notes | -/// |--------|------|----------|----------------------------------------------------| -/// | 0 | 2 | marker | Always `MARKER` (0xAA55). Frame check. | -/// | 2 | 1 | nodeId | Sender's node ID. 0 = unset. | -/// | 3 | 1 | version | Wire protocol version, `VERSION`. | -/// | 4 | 2 | id | DelegateRemoteId. `ACK_REMOTE_ID` (0) for an ACK. | -/// | 6 | 2 | seqNum | Sender's sequence number. | -/// | 8 | 2 | length | Payload bytes following the header. | -/// -/// Transports write and read the header with `Encode()`/`Decode()` and check it -/// with `IsValid()`, so the layout lives only here. -class DmqHeader -{ -public: - /// Frame marker (10101010 01010101). - static constexpr uint16_t MARKER = 0xAA55; - - /// Wire protocol version this build sends and accepts. - static constexpr uint8_t VERSION = 1; - - /// Encoded header size in bytes. - static constexpr size_t HEADER_SIZE = 10; - - DmqHeader() = default; - DmqHeader(uint16_t id, uint16_t seqNum, uint16_t length = 0) - : m_id(id), m_seqNum(seqNum), m_length(length) { - } - - // --- Getters (host byte order) --- - - uint16_t GetMarker() const { return m_marker; } - uint8_t GetNodeId() const { return m_nodeId; } - uint8_t GetVersion() const { return m_version; } - uint16_t GetId() const { return m_id; } - uint16_t GetSeqNum() const { return m_seqNum; } - uint16_t GetLength() const { return m_length; } - - // --- Setters (host byte order) --- - - void SetMarker(uint16_t marker) { m_marker = marker; } - void SetNodeId(uint8_t nodeId) { m_nodeId = nodeId; } - void SetVersion(uint8_t version) { m_version = version; } - void SetId(uint16_t id) { m_id = id; } - void SetSeqNum(uint16_t seqNum) { m_seqNum = seqNum; } - void SetLength(uint16_t length) { m_length = length; } - - /// @brief True if the marker matches. False means garbage or lost framing. - bool HasValidMarker() const { return m_marker == MARKER; } - - /// @brief True if the marker and protocol version both match. A valid marker - /// with another version is a well-formed frame from an incompatible peer. - bool IsValid() const { return m_marker == MARKER && m_version == VERSION; } - - /// @brief Write the header to `buf` in wire format. - /// @param[out] buf At least HEADER_SIZE bytes. - void Encode(void* buf) const { - uint8_t* p = static_cast(buf); - Put16(p + 0, m_marker); - p[2] = m_nodeId; - p[3] = m_version; - Put16(p + 4, m_id); - Put16(p + 6, m_seqNum); - Put16(p + 8, m_length); - } - - /// @brief Read a header from `buf` in wire format. Doesn't validate it; - /// call IsValid() afterwards. - /// @param[in] buf At least HEADER_SIZE bytes. - void Decode(const void* buf) { - const uint8_t* p = static_cast(buf); - m_marker = Get16(p + 0); - m_nodeId = p[2]; - m_version = p[3]; - m_id = Get16(p + 4); - m_seqNum = Get16(p + 6); - m_length = Get16(p + 8); - } - - /// @brief This process's node ID, stamped into every header it creates. - /// Defaults to dmq::NODE_ID (DMQ_NODE_ID). - static uint8_t GetLocalNodeId() { return LocalNodeId().load(std::memory_order_relaxed); } - - /// @brief Set this process's node ID (1-255, 0 = unset). Call once at - /// startup, before any messages are sent. - static void SetLocalNodeId(uint8_t nodeId) { LocalNodeId().store(nodeId, std::memory_order_relaxed); } - -private: - static std::atomic& LocalNodeId() { - static std::atomic nodeId{ dmq::NODE_ID }; - return nodeId; - } - - static void Put16(uint8_t* p, uint16_t v) { - p[0] = static_cast(v >> 8); - p[1] = static_cast(v); - } - static uint16_t Get16(const uint8_t* p) { - return static_cast((static_cast(p[0]) << 8) | p[1]); - } - - uint16_t m_marker = MARKER; - uint8_t m_nodeId = GetLocalNodeId(); - uint8_t m_version = VERSION; - uint16_t m_id = 0; // DelegateRemoteId - uint16_t m_seqNum = 0; - uint16_t m_length = 0; // Payload length -}; - -} // namespace dmq::transport - - -#endif diff --git a/DelegateMQ/port/transport/common/ITransport.h b/DelegateMQ/port/transport/common/ITransport.h deleted file mode 100644 index 3f67a2e..0000000 --- a/DelegateMQ/port/transport/common/ITransport.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef ITRANSPORT_H -#define ITRANSPORT_H - -#include "DmqHeader.h" -#include "../../../delegate/DelegateOpt.h" - -namespace dmq::transport { - -/// @TODO Implement the ITransport interface if necessary. -/// @brief DelegateMQ transport interface. -class ITransport -{ -public: - virtual ~ITransport() = default; - /// Send data to a remote - /// @param[in] os Output stream to send. - /// @param[in] header The header to send. - /// @return 0 if success. - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) = 0; - - /// Returned by Receive() when nothing arrived within the transport's receive - /// timeout (or, for a non-blocking transport, nothing was waiting). Not an - /// error: callers poll again. - static constexpr int RECEIVE_NO_DATA = 1; - - /// Receive data from a remote - /// @param[out] is The received incoming data bytes, not including the header. - /// @param[out] header Incoming delegate message header. - /// @return 0 if a message was received, RECEIVE_NO_DATA if nothing arrived, - /// or a negative value on error (socket failure, malformed or truncated frame). - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) = 0; -}; - -} // namespace dmq::transport - - -#endif \ No newline at end of file diff --git a/DelegateMQ/port/transport/common/ITransportMonitor.h b/DelegateMQ/port/transport/common/ITransportMonitor.h deleted file mode 100644 index 642d937..0000000 --- a/DelegateMQ/port/transport/common/ITransportMonitor.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef ITRANSPORT_MONITOR_H -#define ITRANSPORT_MONITOR_H - -//#include "DmqHeader.h" -//#include - -namespace dmq::transport { - -/// @TODO Implement the ITransportMonitor interface if necessary. -/// @brief DelegateMQ transport monitor interface. -class ITransportMonitor -{ -public: - virtual ~ITransportMonitor() = default; - /// Add a sequence number - /// param[in] seqNum - the message sequence number - /// param[in] remoteId - the remote ID - /// @return true if added; false otherwise. - virtual bool Add(uint16_t seqNum, dmq::DelegateRemoteId remoteId) = 0; - - /// Remove a sequence number - /// param[in] seqNum - the message sequence number - virtual void Remove(uint16_t seqNum) = 0; -}; - -} // namespace dmq::transport - - -#endif \ No newline at end of file diff --git a/DelegateMQ/port/transport/linux-tcp/LinuxTcpTransport.h b/DelegateMQ/port/transport/linux-tcp/LinuxTcpTransport.h deleted file mode 100644 index 61a59d1..0000000 --- a/DelegateMQ/port/transport/linux-tcp/LinuxTcpTransport.h +++ /dev/null @@ -1,386 +0,0 @@ -#ifndef LINUX_TCP_TRANSPORT_H -#define LINUX_TCP_TRANSPORT_H - -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Linux TCP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using standard Linux BSD sockets. -/// It supports both CLIENT and SERVER modes for reliable, stream-based communication. -/// In SERVER mode, it supports multiple simultaneous client connections and broadcasts -/// outgoing messages to all connected participants. -/// -/// Key Features: -/// 1. **Thread-Safe I/O**: Executes socket operations directly on the calling thread, -/// relying on OS-level thread safety for concurrent Send/Receive operations. -/// 2. **Low Latency**: Configures `TCP_NODELAY` to disable Nagle's algorithm, optimized -/// for the small, frequent packets typical of RPC/delegate calls. -/// 3. **Non-Blocking Poll**: Utilizes `select()` in the receive loop to prevent -/// thread blocking when no data is available, facilitating clean shutdowns. -/// 4. **Multi-Client Multiplexing**: SERVER mode manages a list of clients and -/// polls them for data using `select()`. -/// 5. **Reliability**: Fully integrated with `TransportMonitor` to handle sequence -/// tracking and ACK generation. -/// -/// @note This class is specific to Linux and uses POSIX socket APIs. - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" - -namespace dmq::transport { - -/// @brief A TCP transport implementation for Linux using BSD sockets. -class LinuxTcpTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type { SERVER, CLIENT }; - - LinuxTcpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~LinuxTcpTransport() { Close(); } - - /// @brief Create a TCP transport. - /// @param type SERVER or CLIENT. - /// @param addr The IP address string. - /// @param port The TCP port. - /// @return 0 on success, -1 on failure. - int Create(Type type, const char* addr, uint16_t port) - { - Close(); // a second Create() replaces the sockets instead of leaking them - m_type = type; - m_socket = socket(AF_INET, SOCK_STREAM, 0); - if (m_socket < 0) return -1; - - // Set TCP_NODELAY to disable Nagle's algorithm for low-latency RPC - int flag = 1; - setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int)); - - sockaddr_in srv_addr{}; - srv_addr.sin_family = AF_INET; - srv_addr.sin_port = htons(port); - inet_aton(addr, &srv_addr.sin_addr); - - if (type == Type::SERVER) { - int opt = 1; - setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); - if (bind(m_socket, (struct sockaddr*)&srv_addr, sizeof(srv_addr)) < 0) { Close(); return -1; } - if (listen(m_socket, 5) < 0) { Close(); return -1; } - } - else { - if (connect(m_socket, (struct sockaddr*)&srv_addr, sizeof(srv_addr)) < 0) { Close(); return -1; } - m_connFd = m_socket; - - struct timeval tv; - tv.tv_sec = 2; tv.tv_usec = 0; - setsockopt(m_connFd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv)); - } - - return 0; - } - - /// @brief Close all sockets and clean up. - void Close() - { - // m_mutex: Receive() may close the client socket on another thread - const std::lock_guard lock(m_mutex); - - // Close Connected Socket - if (m_connFd >= 0) - { - shutdown(m_connFd, SHUT_RDWR); - if (m_connFd != m_socket) - { - close(m_connFd); - } - } - - // Close all server-accepted clients - { - for (auto s : m_serverClients) { - shutdown(s, SHUT_RDWR); - close(s); - } - m_serverClients.clear(); - } - - // Close Listen Socket - if (m_socket >= 0) - { - shutdown(m_socket, SHUT_RDWR); - close(m_socket); - } - - m_connFd = m_socket = -1; - } - - /// @brief Set the receive timeout for all active sockets. - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - m_recvTimeout = timeout; - struct timeval tv; - tv.tv_sec = timeout.count() / 1000; - tv.tv_usec = (timeout.count() % 1000) * 1000; - - if (m_connFd >= 0) - { - setsockopt(m_connFd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - } - - const std::lock_guard lock(m_mutex); - for (auto s : m_serverClients) { - setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - } - } - - /// @brief Send data over the TCP link. - /// @details In SERVER mode, this broadcasts to all connected clients. - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - // m_mutex guards m_sendBuffer and keeps frames from different threads - // (including ACKs written by Receive()) from interleaving on the stream. - const std::lock_guard lock(m_mutex); - if (m_type == Type::CLIENT) { - return SendToSocket(m_connFd, os, header); - } else { - int lastErr = 0; - for (auto fd : m_serverClients) { - if (SendToSocket(fd, os, header) != 0) lastErr = -1; - } - return lastErr; - } - } - - /// @brief Receive data from the TCP link. - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - if (m_type == Type::SERVER) { - return ReceiveServer(is, header); - } else { - if (m_connFd < 0) { - // The connection was dropped (see below). Wait out one receive - // timeout before reporting it again, so a caller polling in a - // tight loop (RemoteDispatcher's receive thread) doesn't spin. - std::this_thread::sleep_for(m_recvTimeout); - return -1; - } - int result = ReceiveSocket(m_connFd, is, header); - if (result == -2) { - // Disconnected, or the stream lost framing (bad header, partial - // frame). Either way nothing more on it can be trusted. Close it: - // a shut-down but still open socket stays readable at EOF, so the - // next select() would return at once and the caller would spin. - const std::lock_guard lock(m_mutex); - if (m_connFd >= 0) { - shutdown(m_connFd, SHUT_RDWR); - close(m_connFd); - m_connFd = m_socket = -1; - } - } - return result; - } - } - - void SetTransportMonitor(ITransportMonitor* tm) { - m_transportMonitor = tm; - } - void SetSendTransport(ITransport* st) { - m_sendTransport = st; - } - void SetRecvTransport(ITransport* rt) { - m_recvTransport = rt; - } - -private: - /// @brief Internal helper to send to a specific socket. - int SendToSocket(int fd, xostringstream& os, const DmqHeader& header) { - if (fd < 0) return -1; - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - std::cerr << "Error: Payload too large for static buffer." << std::endl; - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - // Copy payload after header - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - return WriteAll(fd, m_sendBuffer, totalSize) ? 0 : -1; - } - - /// @brief Internal helper to handle server-side multiplexing. - int ReceiveServer(xstringstream& is, DmqHeader& header) { - // 1. Lazy Accept: Check for new client connections - fd_set fds; - FD_ZERO(&fds); - FD_SET(m_socket, &fds); - struct timeval tv = { 0, 1000 }; // 1ms poll - - if (select(m_socket + 1, &fds, nullptr, nullptr, &tv) > 0) { - int client = accept(m_socket, nullptr, nullptr); - if (client >= 0) { - struct timeval t; - t.tv_sec = m_recvTimeout.count() / 1000; - t.tv_usec = (m_recvTimeout.count() % 1000) * 1000; - setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &t, sizeof(t)); - const std::lock_guard lock(m_mutex); - m_serverClients.push_back(client); - } - } - - // 2. Poll all connected clients for data - fd_set readfds; - FD_ZERO(&readfds); - int max_fd = -1; - { - const std::lock_guard lock(m_mutex); - if (m_serverClients.empty()) return RECEIVE_NO_DATA; - for (auto s : m_serverClients) { - FD_SET(s, &readfds); - if (s > max_fd) max_fd = s; - } - } - - tv.tv_usec = 1000; // 1ms poll - if (select(max_fd + 1, &readfds, nullptr, nullptr, &tv) > 0) { - const std::lock_guard lock(m_mutex); - for (auto it = m_serverClients.begin(); it != m_serverClients.end(); ) { - if (FD_ISSET(*it, &readfds)) { - int result = ReceiveSocket(*it, is, header); - if (result == -2) { - // Disconnected, or lost framing (bad header): drop this client. - close(*it); - it = m_serverClients.erase(it); - continue; - } - return result; - } - ++it; - } - } - return RECEIVE_NO_DATA; - } - - /// @brief Internal helper to read from a specific socket and parse DMQ protocol. - int ReceiveSocket(int fd, xstringstream& is, DmqHeader& header) { - if (fd < 0) return -1; - - fd_set readfds; - FD_ZERO(&readfds); - FD_SET(fd, &readfds); - struct timeval tv = { 0, 1000 }; - int ready = select(fd + 1, &readfds, nullptr, nullptr, &tv); - if (ready == 0) return RECEIVE_NO_DATA; - if (ready < 0) return -1; - - // 1. Read Header - char headerBuf[DmqHeader::HEADER_SIZE]; - if (!ReadExact(fd, headerBuf, DmqHeader::HEADER_SIZE)) return -2; // Disconnected - - // Parse Header (Convert Network -> Host) - header.Decode(headerBuf); - - // A stream has no resync point: after a bad header (or a payload we - // can't hold and so can't skip), the next bytes aren't a header either. - // Report it like a disconnect (-2) so the connection is dropped. - if (!header.IsValid()) return -2; - - // 2. Read Payload - uint16_t payloadSize = header.GetLength(); - if (payloadSize > 0) { - if (payloadSize > BUFFER_SIZE) return -2; - if (!ReadExact(fd, m_recvBuffer, payloadSize)) return -2; - is.write(m_recvBuffer, payloadSize); - } - - // 3. Handle Acknowledgment - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - else if (m_sendTransport) { - // Send ACK using a small stack buffer - DmqHeader ack(dmq::ACK_REMOTE_ID, header.GetSeqNum()); - char ackBuf[DmqHeader::HEADER_SIZE]; - ack.Encode(ackBuf); - - const std::lock_guard lock(m_mutex); // don't interleave with Send() - (void)WriteAll(fd, ackBuf, DmqHeader::HEADER_SIZE); - } - return 0; - } - - /// @brief Write all 'len' bytes; a short write would otherwise leave half a - /// frame on the stream. - bool WriteAll(int fd, const char* buf, size_t len) - { - size_t total = 0; - while (total < len) { - ssize_t w = write(fd, buf + total, len - total); - if (w < 0 && errno == EINTR) continue; - if (w <= 0) return false; - total += static_cast(w); - } - return true; - } - - /// @brief Read exactly 'len' bytes from the socket. - bool ReadExact(int fd, char* buf, size_t len) - { - size_t total = 0; - while (total < len) { - ssize_t r = read(fd, buf + total, len - total); - if (r <= 0) return false; - total += r; - } - return true; - } - - int m_socket = -1; - int m_connFd = -1; - std::vector m_serverClients; - static const int BUFFER_SIZE = 4096; - char m_recvBuffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - std::chrono::milliseconds m_recvTimeout{2000}; - Type m_type = Type::SERVER; - - ITransport* m_sendTransport, * m_recvTransport; - ITransportMonitor* m_transportMonitor = nullptr; - dmq::RecursiveMutex m_mutex; -}; - -using TcpTransport = LinuxTcpTransport; - -} // namespace dmq::transport - -#endif // LINUX_TCP_TRANSPORT_H diff --git a/DelegateMQ/port/transport/linux-udp/LinuxUdpTransport.h b/DelegateMQ/port/transport/linux-udp/LinuxUdpTransport.h deleted file mode 100644 index 09fa757..0000000 --- a/DelegateMQ/port/transport/linux-udp/LinuxUdpTransport.h +++ /dev/null @@ -1,324 +0,0 @@ -#ifndef LINUX_UDP_TRANSPORT_H -#define LINUX_UDP_TRANSPORT_H - -/// @file LinuxUdpTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Linux UDP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using standard Linux BSD sockets -/// for connectionless UDP communication. It supports both PUB (Publisher/Sender) -/// and SUB (Subscriber/Receiver) modes. -/// -/// Key Features: -/// 1. **Direct Execution**: Executes socket operations directly on the calling thread, -/// relying on OS-level thread safety to avoid deadlocks. -/// 2. **Reliability Support**: Integrates with `TransportMonitor` to track outgoing -/// sequence numbers and process incoming ACKs to detect packet loss. -/// 3. **Non-Blocking I/O**: Configures socket receive timeouts (`SO_RCVTIMEO`) to -/// prevent indefinite blocking during polling loops. -/// 4. **Address Management**: Automatically updates the target address on the receiver -/// side to support reliable bidirectional ACKs. -/// -/// @note This class is specific to Linux and uses POSIX socket APIs. - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -// Linux UDP transport example -class LinuxUdpTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type - { - PUB, - SUB - }; - - LinuxUdpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~LinuxUdpTransport() - { - Close(); - } - - int Create(Type type, const char* addr, uint16_t port) - { - const std::lock_guard recvLock(m_recvMutex); - const std::lock_guard lock(m_mutex); - Close(); // a second Create() replaces the socket instead of leaking it - m_type = type; - - // Create UDP socket - m_socket = socket(AF_INET, SOCK_DGRAM, 0); - if (m_socket < 0) - { - std::cerr << "Socket creation failed: " << strerror(errno) << std::endl; - return -1; - } - - int opt = 1; - setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); -#ifdef SO_REUSEPORT - setsockopt(m_socket, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt)); -#endif - - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); - - if (type == Type::PUB) - { - if (inet_aton(addr, &m_addr.sin_addr) == 0) - { - std::cerr << "Invalid IP address format." << std::endl; - Close(); - return -1; - } - - // Set a short timeout (e.g. 2ms) so Sender::Send() doesn't hang - // while polling for ACKs. - struct timeval timeout; - timeout.tv_sec = 0; - timeout.tv_usec = 2000; // 2ms - - if (setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) - { - std::cerr << "setsockopt(SO_RCVTIMEO) failed: " << strerror(errno) << std::endl; - Close(); - return -1; - } - } - else if (type == Type::SUB) - { - if (inet_aton(addr, &m_addr.sin_addr) == 0) - { - m_addr.sin_addr.s_addr = INADDR_ANY; - } - - if (bind(m_socket, (struct sockaddr*)&m_addr, sizeof(m_addr)) < 0) - { - std::cerr << "Bind failed: " << strerror(errno) << std::endl; - Close(); - return -1; - } - - struct timeval timeout; - timeout.tv_sec = 2; - timeout.tv_usec = 0; - - if (setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) - { - std::cerr << "setsockopt(SO_RCVTIMEO) failed: " << strerror(errno) << std::endl; - Close(); - return -1; - } - } - - return 0; - } - - /// @details Waits for a Receive() in progress on another thread to return - /// (at most its receive timeout) before closing, so the socket is never - /// closed under it. - void Close() - { - const std::lock_guard recvLock(m_recvMutex); - const std::lock_guard lock(m_mutex); - if (m_socket != -1) - { - shutdown(m_socket, SHUT_RDWR); - close(m_socket); - m_socket = -1; - } - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - const std::lock_guard lock(m_mutex); - if (m_socket != -1) - { - struct timeval tv; - tv.tv_sec = timeout.count() / 1000; - tv.tv_usec = (timeout.count() % 1000) * 1000; - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - } - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - const std::lock_guard lock(m_mutex); - // Allow ACKs on SUB sockets. Block only regular data. - if (m_type == Type::SUB && header.GetId() != dmq::ACK_REMOTE_ID) { - std::cerr << "Send operation not allowed on SUB socket." << std::endl; - return -1; - } - - if (m_sendTransport != this) { - std::cerr << "Send operation not allowed (Receive only)." << std::endl; - return -1; - } - - // Get payload data without string copy if possible - // Note: os.str() still creates a copy. In a full zero-copy version, - // we would use a custom streambuf that points to m_sendBuffer. - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - std::cerr << "Error: Payload too large for static buffer." << std::endl; - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - // Copy payload after header - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - ssize_t sent = sendto(m_socket, m_sendBuffer, totalSize, 0, - (struct sockaddr*)&m_addr, sizeof(m_addr)); - - if (sent != (ssize_t)totalSize) return -1; - - return 0; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - // m_recvMutex, not m_mutex: a Send() on another thread (e.g. a PUB socket - // that also drains its ACKs here) isn't held up for the receive timeout. - const std::lock_guard recvLock(m_recvMutex); - if (m_recvTransport != this) { - std::cerr << "Receive operation not allowed (Send only)." << std::endl; - return -1; - } - if (m_socket == -1) - return -1; - - sockaddr_in fromAddr; - socklen_t addrLen = sizeof(fromAddr); - // MSG_TRUNC: return the datagram's real length, so one larger than the - // buffer is detected and dropped rather than delivered cut short. - ssize_t size = recvfrom(m_socket, m_buffer, sizeof(m_buffer), MSG_TRUNC, - (struct sockaddr*)&fromAddr, &addrLen); - - if (size < 0) - { - if (errno == EWOULDBLOCK || errno == EAGAIN) - return RECEIVE_NO_DATA; // Timeout - return -1; - } - - if (size < static_cast(DmqHeader::HEADER_SIZE) || - size > static_cast(sizeof(m_buffer))) { - return -1; // runt, or truncated - } - - // 1. Read Header directly from m_buffer (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) - { - return -1; - } - - // 2. Write payload to provided stream. One datagram is one message, so - // the header length must match exactly; anything else is malformed and - // must not be delivered or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != static_cast(size) - DmqHeader::HEADER_SIZE) - return -1; - - if (payloadSize > 0) { - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - // 3. Handle ACKs and Metadata - if (header.GetId() == dmq::ACK_REMOTE_ID) - { - if (m_transportMonitor) - m_transportMonitor->Remove(header.GetSeqNum()); - } - else if (m_sendTransport && m_type == Type::SUB) - { - // Send ACK using a small stack buffer to avoid any heap - DmqHeader ack(dmq::ACK_REMOTE_ID, header.GetSeqNum()); - char ackBuf[DmqHeader::HEADER_SIZE]; - ack.Encode(ackBuf); - - // Use the subscriber's m_addr which was set by recvfrom if m_type == SUB - sockaddr_in targetAddr = (m_type == Type::SUB) ? fromAddr : m_addr; - - sendto(m_socket, ackBuf, DmqHeader::HEADER_SIZE, 0, - (struct sockaddr*)&targetAddr, sizeof(targetAddr)); - } - - return 0; - } - - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - void SetSendTransport(ITransport* sendTransport) - { - m_sendTransport = sendTransport; - } - - void SetRecvTransport(ITransport* recvTransport) - { - m_recvTransport = recvTransport; - } - -private: - int m_socket = -1; - sockaddr_in m_addr{}; - Type m_type = Type::PUB; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - /// @note UDP datagrams larger than the network MTU (typically 1500 bytes) will be - /// fragmented by the IP layer. If any fragment is lost, the entire message is - /// discarded. For maximum reliability, keep serialized messages under 1400 bytes. - /// Messages exceeding BUFFER_SIZE will be truncated and discarded by the OS. - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; ///< Socket open/close and Send() state - dmq::RecursiveMutex m_recvMutex; ///< Held by Receive(); taken before m_mutex -}; - -using UdpTransport = LinuxUdpTransport; - -} // namespace dmq::transport - -#endif // LINUX_UDP_TRANSPORT_H \ No newline at end of file diff --git a/DelegateMQ/port/transport/linux-udp/MulticastTransport.h b/DelegateMQ/port/transport/linux-udp/MulticastTransport.h deleted file mode 100644 index 002d13b..0000000 --- a/DelegateMQ/port/transport/linux-udp/MulticastTransport.h +++ /dev/null @@ -1,141 +0,0 @@ -#ifndef LINUX_MULTICAST_TRANSPORT_H -#define LINUX_MULTICAST_TRANSPORT_H - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief Linux Multicast UDP transport implementation for DelegateMQ. -class MulticastTransport : public ITransport -{ -public: - enum class Type { PUB, SUB }; - - MulticastTransport() = default; - ~MulticastTransport() { Close(); } - - int Create(Type type, const char* groupAddr, uint16_t port, const char* localInterface = "0.0.0.0") - { - dmq::LockGuard lock(m_mutex); - m_type = type; - m_socket = socket(AF_INET, SOCK_DGRAM, 0); - if (m_socket < 0) return -1; - - int reuse = 1; - setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)); - - // ALWAYS enable loopback for testing convenience - int loop = 1; - setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); - - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); - - if (type == Type::PUB) { - m_addr.sin_addr.s_addr = inet_addr(groupAddr); - - struct in_addr interface_addr; - interface_addr.s_addr = inet_addr(localInterface); - setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_IF, &interface_addr, sizeof(interface_addr)); - - int ttl = 3; - setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); - } - else { - m_addr.sin_addr.s_addr = INADDR_ANY; - if (bind(m_socket, (struct sockaddr*)&m_addr, sizeof(m_addr)) < 0) { Close(); return -1; } - - struct ip_mreq mreq; - mreq.imr_multiaddr.s_addr = inet_addr(groupAddr); - mreq.imr_interface.s_addr = inet_addr(localInterface); - if (setsockopt(m_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) { - Close(); return -1; - } - - struct timeval timeout; - timeout.tv_sec = 1; - timeout.tv_usec = 0; - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); - } - return 0; - } - - void Close() { - dmq::LockGuard lock(m_mutex); - if (m_socket != -1) { - close(m_socket); - m_socket = -1; - } - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override { - dmq::LockGuard lock(m_mutex); - if (m_type != Type::PUB) return -1; - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) return -1; - DmqHeader headerCopy = header; - headerCopy.SetLength(static_cast(payload.length())); - - xostringstream ss(std::ios::in | std::ios::out | std::ios::binary); - char headerBuf[DmqHeader::HEADER_SIZE]; - headerCopy.Encode(headerBuf); - ss.write(headerBuf, DmqHeader::HEADER_SIZE); - ss.write(payload.data(), payload.size()); - - auto data = ss.str(); - sendto(m_socket, data.c_str(), data.size(), 0, (struct sockaddr*)&m_addr, sizeof(m_addr)); - return 0; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override { - dmq::LockGuard lock(m_mutex); - if (m_type != Type::SUB) return -1; - // MSG_TRUNC: return the datagram's real length, so one larger than the - // buffer is detected and dropped rather than delivered cut short. - ssize_t size = recvfrom(m_socket, m_buffer, sizeof(m_buffer), MSG_TRUNC, NULL, NULL); - if (size < 0) - return (errno == EAGAIN || errno == EWOULDBLOCK) ? RECEIVE_NO_DATA : -1; - - if (size < (ssize_t)DmqHeader::HEADER_SIZE) return -1; - if (size > (ssize_t)sizeof(m_buffer)) return -1; // truncated - - header.Decode(m_buffer); - - if (!header.IsValid()) { - // std::cerr << "[Multicast] Bad Marker: " << std::hex << header.GetMarker() << std::dec << std::endl; - return -1; - } - - // One datagram is one message: the header length must match exactly. - int payloadSize = static_cast(size) - static_cast(DmqHeader::HEADER_SIZE); - if (header.GetLength() != payloadSize) return -1; - is.write(m_buffer + DmqHeader::HEADER_SIZE, header.GetLength()); - return 0; - } - -private: - int m_socket = -1; - sockaddr_in m_addr{}; - Type m_type = Type::PUB; - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; -}; - -} // namespace dmq::transport - -#endif diff --git a/DelegateMQ/port/transport/linux-uds/LinuxUdsTransport.h b/DelegateMQ/port/transport/linux-uds/LinuxUdsTransport.h deleted file mode 100644 index 8eca390..0000000 --- a/DelegateMQ/port/transport/linux-uds/LinuxUdsTransport.h +++ /dev/null @@ -1,350 +0,0 @@ -#ifndef LINUX_UDS_TRANSPORT_H -#define LINUX_UDS_TRANSPORT_H - -/// @file LinuxUdsTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Linux Unix domain socket transport implementation for DelegateMQ. -/// -/// @details -/// Local inter-process communication over a Unix domain datagram socket -/// (`AF_UNIX`, `SOCK_DGRAM`). This is the Linux counterpart to -/// `Win32PipeTransport`: one transport instance is duplex, so a single -/// participant can both send and receive over it. -/// -/// Each endpoint is a filesystem path. Every instance binds its own local path -/// (so the peer can address it) and sends to the peer's path: -/// -/// @code -/// // Process A // Process B -/// t.Create(Type::SUB, "/tmp/a.sock", "/tmp/b.sock"); t.Create(Type::PUB, "/tmp/b.sock", "/tmp/a.sock"); -/// @endcode -/// -/// Key Features: -/// 1. **No start order**: datagram sockets have no connection. Either side may -/// start first; a Send() to a peer that isn't bound yet fails (returns -1) -/// and the next Send() after the peer binds succeeds. -/// 2. **Message boundaries**: one Send() is exactly one Receive(). -/// Linux Unix datagram sockets are reliable and ordered, so no ACK/retry -/// layer is used (same as `Win32PipeTransport`). -/// 3. **Non-blocking by default**: Receive() returns -1 immediately when no -/// datagram is waiting, matching `Win32PipeTransport`'s `PIPE_NOWAIT` mode. -/// SetRecvTimeout() makes Receive() block up to the given time instead. -/// Receive() does not hold the send lock while waiting, so a concurrent -/// Send() on the same instance is never held up by an idle read. -/// 4. **Stale paths**: a crashed process leaves its socket file behind. Create() -/// probes the local path first: a stale socket (nothing listening) is -/// unlinked and reused; a path a live process is still bound to makes -/// Create() fail rather than take it over. Close() unlinks the path again. -/// -/// @note Socket files are ordinary filesystem entries, so access is governed by -/// the directory's permissions. A world-writable directory such as `/tmp` lets -/// any local user send to the socket. Use a per-user directory such as -/// `$XDG_RUNTIME_DIR` when that matters. -/// -/// Type is kept for API parity with `Win32PipeTransport` (`SUB` = server end, -/// `PUB` = client end). Both ends are duplex. The one difference: a `SUB` -/// created with `peerPath == nullptr` replies to whoever sent it the most recent -/// datagram, instead of a fixed peer. -/// -/// @note This class is specific to Linux and uses POSIX socket APIs. - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief Linux Unix domain datagram socket transport. -class LinuxUdsTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type - { - PUB, - SUB - }; - - LinuxUdsTransport() = default; - - ~LinuxUdsTransport() - { - Close(); - } - - /// Create the socket and bind it to localPath. - /// @param[in] type PUB (client end) or SUB (server end). Both are duplex. - /// @param[in] localPath This endpoint's socket path. Required. - /// @param[in] peerPath The other endpoint's socket path. Required for PUB; - /// optional for SUB (nullptr = reply to the most recent sender). - /// @return 0 on success, -1 on failure. - int Create(Type type, const char* localPath, const char* peerPath) - { - const std::lock_guard lock(m_mutex); - m_type = type; - - if (localPath == nullptr || (type == Type::PUB && peerPath == nullptr)) - { - std::cerr << "LinuxUdsTransport: missing socket path." << std::endl; - return -1; - } - - if (!MakeAddr(localPath, m_localAddr) || - (peerPath && !MakeAddr(peerPath, m_peerAddr))) - { - std::cerr << "LinuxUdsTransport: socket path too long (max " - << sizeof(m_localAddr.sun_path) - 1 << " chars)." << std::endl; - return -1; - } - m_fixedPeer = (peerPath != nullptr); - m_hasPeer = m_fixedPeer; - - m_socket = socket(AF_UNIX, SOCK_DGRAM, 0); - if (m_socket < 0) - { - std::cerr << "Socket creation failed: " << strerror(errno) << std::endl; - return -1; - } - - // A crashed run leaves the socket file behind, which makes bind() fail. - // Unlink it only if it is a stale socket; never steal a live one. - if (!ClearStalePath(m_localAddr)) - { - close(m_socket); - m_socket = -1; - return -1; - } - if (bind(m_socket, (struct sockaddr*)&m_localAddr, sizeof(m_localAddr)) < 0) - { - std::cerr << "Bind failed (" << m_localAddr.sun_path << "): " << strerror(errno) << std::endl; - close(m_socket); - m_socket = -1; - return -1; - } - m_bound = true; - return 0; - } - - void Close() - { - // Lock order matches Receive(): m_recvMutex, then m_mutex. Holding - // m_recvMutex means no Receive() is mid-wait on the socket we close - // (Close() waits at most one recv timeout for it to return). - const std::lock_guard recvLock(m_recvMutex); - const std::lock_guard lock(m_mutex); - if (m_socket != -1) - { - shutdown(m_socket, SHUT_RDWR); - close(m_socket); - m_socket = -1; - } - if (m_bound) - { - unlink(m_localAddr.sun_path); - m_bound = false; - } - } - - /// Make Receive() wait up to timeout for a datagram. 0 (default) = non-blocking. - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - const std::lock_guard lock(m_mutex); - m_recvTimeout = timeout; - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - const std::lock_guard lock(m_mutex); - if (os.bad() || os.fail()) - return -1; - - if (m_socket == -1 || !m_hasPeer) - return -1; - - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - std::cerr << "Error: Payload too large for static buffer." << std::endl; - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - // Copy payload after header - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - // MSG_DONTWAIT: if the peer isn't reading and its queue is full, fail - // this send rather than stall the caller. A peer that isn't bound yet - // fails with ENOENT/ECONNREFUSED. - ssize_t sent = sendto(m_socket, m_sendBuffer, totalSize, MSG_DONTWAIT, - (struct sockaddr*)&m_peerAddr, sizeof(m_peerAddr)); - - if (sent != (ssize_t)totalSize) - return -1; - - return 0; - } - - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override - { - // Receive-side state (m_buffer) is only touched here, under m_recvMutex. - // m_mutex is not held while waiting, so Send() is never blocked by an idle read. - // The socket copied below stays valid: Close() also takes m_recvMutex. - const std::lock_guard recvLock(m_recvMutex); - - int sock; - std::chrono::milliseconds timeout; - { - const std::lock_guard lock(m_mutex); - sock = m_socket; - timeout = m_recvTimeout; - } - if (sock == -1) - return -1; - - if (timeout.count() > 0) - { - pollfd pfd{ sock, POLLIN, 0 }; - int ready = poll(&pfd, 1, static_cast(timeout.count())); - if (ready == 0) - return RECEIVE_NO_DATA; - if (ready < 0) - return -1; - } - - sockaddr_un fromAddr{}; - socklen_t addrLen = sizeof(fromAddr); - // MSG_TRUNC: return the datagram's real length, so an oversized one is - // detected and dropped instead of being silently cut off. - ssize_t size = recvfrom(sock, m_buffer, sizeof(m_buffer), MSG_DONTWAIT | MSG_TRUNC, - (struct sockaddr*)&fromAddr, &addrLen); - - if (size < 0) - return (errno == EAGAIN || errno == EWOULDBLOCK) ? RECEIVE_NO_DATA : -1; - if (size < static_cast(DmqHeader::HEADER_SIZE)) - return -1; // runt datagram - if (size > static_cast(sizeof(m_buffer))) - return -1; // truncated: larger than the receive buffer - - // 1. Read Header directly from m_buffer (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) - return -1; - - // 2. Write payload to provided stream. One Send() is one datagram, so - // the header length must match exactly; anything else is malformed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != (size - DmqHeader::HEADER_SIZE)) - return -1; - - if (payloadSize > 0) { - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - // 3. A SUB without a fixed peer replies to the most recent (bound) sender. - if (m_type == Type::SUB && addrLen > sizeof(sa_family_t)) - { - const std::lock_guard lock(m_mutex); - if (!m_fixedPeer) - { - m_peerAddr = fromAddr; - m_hasPeer = true; - } - } - - return 0; - } - -private: - /// Prepare addr's path for bind(). A connect() probe tells a stale socket - /// file (ECONNREFUSED: nothing bound) from a live one (connect succeeds). - /// Only a stale socket is unlinked; a live one, or anything that isn't a - /// socket, is left alone. - /// @return true if bind() may proceed. - static bool ClearStalePath(const sockaddr_un& addr) - { - // connect() also reports ECONNREFUSED for a regular file, so check the - // file type first. lstat(): a symlink is not followed or removed. - struct stat st{}; - if (lstat(addr.sun_path, &st) != 0) - return true; // nothing there - if (!S_ISSOCK(st.st_mode)) - return true; // not a socket: leave it; bind() fails and reports it - - int probe = socket(AF_UNIX, SOCK_DGRAM, 0); - if (probe < 0) - { - std::cerr << "Socket creation failed: " << strerror(errno) << std::endl; - return false; - } - int rc = connect(probe, (const struct sockaddr*)&addr, sizeof(addr)); - int err = errno; - close(probe); - - if (rc == 0) - { - std::cerr << "LinuxUdsTransport: " << addr.sun_path - << " is in use by another process." << std::endl; - return false; - } - if (err == ECONNREFUSED) - unlink(addr.sun_path); // stale socket file - // Any other error (e.g. EACCES): leave the file alone and let bind() - // fail and report it. - return true; - } - - static bool MakeAddr(const char* path, sockaddr_un& addr) - { - memset(&addr, 0, sizeof(addr)); - addr.sun_family = AF_UNIX; - if (strlen(path) >= sizeof(addr.sun_path)) - return false; - strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); - return true; - } - - int m_socket = -1; - bool m_bound = false; - bool m_hasPeer = false; - bool m_fixedPeer = false; // peer given to Create(); never overwritten by Receive() - sockaddr_un m_localAddr{}; - sockaddr_un m_peerAddr{}; - Type m_type = Type::PUB; - std::chrono::milliseconds m_recvTimeout{ 0 }; - - /// Max datagram size. Linux Unix datagram sockets accept datagrams up to - /// the socket send buffer size (net.core.wmem_default, typically ~200 KB), - /// so this static buffer is the practical limit. - static const int BUFFER_SIZE = 65536; - char m_buffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; // socket state + send path - dmq::RecursiveMutex m_recvMutex; // receive path -}; - -} // namespace dmq::transport - -#endif // LINUX_UDS_TRANSPORT_H diff --git a/DelegateMQ/port/transport/mqtt/MqttTransport.h b/DelegateMQ/port/transport/mqtt/MqttTransport.h deleted file mode 100644 index a438d71..0000000 --- a/DelegateMQ/port/transport/mqtt/MqttTransport.h +++ /dev/null @@ -1,350 +0,0 @@ - -#ifndef MQTT_TRANSPORT_H -#define MQTT_TRANSPORT_H - -/// @file -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Transport callable argument data to/from a remote using MQTT library. -/// https://github.com/eclipse-paho/paho.mqtt.c -/// -/// Carries DelegateMQ binary frames between DelegateMQ apps on one MQTT topic. -/// Other MQTT tools can't read these frames; to expose DataBus topics as -/// readable JSON instead, see tools/bridge/mqtt/MqttBridge. -/// -/// The broker defaults to a local one (tcp://localhost:1883, e.g. Mosquitto). -/// Pass a broker URI to Create() to use another. Never point real traffic at -/// a public test broker: anyone can read and publish on it. -/// -/// @code -/// MqttTransport t; -/// t.Create(MqttTransport::Type::PUB); // local broker, default topic -/// t.Create(MqttTransport::Type::SUB, "tcp://10.0.0.5:1883", "plant/dmq"); // explicit broker and topic -/// @endcode - -// Ensure network byte order functions are available -#if defined(_WIN32) || defined(_WIN64) - #include - #pragma comment(lib, "ws2_32.lib") -#else - #include -#endif - -#include "port/transport/common/ITransport.h" -#include "port/transport/common/ITransportMonitor.h" -#include "port/transport/common/DmqHeader.h" -#include "MQTTClient.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief MQTT transport example. -class MqttTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type - { - PUB, - SUB - }; - - static constexpr const char* DEFAULT_ADDRESS = "tcp://localhost:1883"; - static constexpr const char* DEFAULT_TOPIC = "dmq/delegate"; - static constexpr int QOS = 1; - static constexpr long TIMEOUT_MS = 10000L; - - MqttTransport() = default; - - ~MqttTransport() - { - Close(); - } - - /// Connect to the broker. - /// @param[in] type PUB publishes to topic; SUB subscribes to it. - /// @param[in] address Broker URI, e.g. "tcp://localhost:1883". - /// @param[in] topic MQTT topic carrying the frames. Both ends must use the same one. - /// @param[in] clientId MQTT client ID. Must be unique on the broker: a second - /// client with the same ID disconnects the first. nullptr (default) - /// generates a random one ("dmq-pub-xxxxxxxx" / "dmq-sub-xxxxxxxx"). - /// @return 0 (MQTTCLIENT_SUCCESS) on success, otherwise a Paho error code. - int Create(Type type, const char* address = DEFAULT_ADDRESS, - const char* topic = DEFAULT_TOPIC, const char* clientId = nullptr) - { - const std::lock_guard lock(m_mutex); - int rc = EXIT_FAILURE; - if (address == nullptr || topic == nullptr || *topic == '\0') - return MQTTCLIENT_NULL_PARAMETER; - - m_topic = topic; - const std::string id = clientId ? std::string(clientId) : MakeClientId(type); - printf("MqttTransport: broker %s, topic %s, client %s\n", address, m_topic.c_str(), id.c_str()); - - { - std::lock_guard q_lock(m_queueMtx); - m_stop = false; - } - - MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; - m_type = type; - if (m_type == Type::PUB) - { - if ((rc = MQTTClient_create(&m_client, address, id.c_str(), - MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS) - { - m_client = nullptr; - return rc; - } - - conn_opts.keepAliveInterval = 20; - conn_opts.cleansession = 1; - if ((rc = MQTTClient_connect(m_client, &conn_opts)) != MQTTCLIENT_SUCCESS) - { - MQTTClient_destroy(&m_client); - m_client = nullptr; - return rc; - } - } - else if (m_type == Type::SUB) - { - if ((rc = MQTTClient_create(&m_client, address, id.c_str(), - MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS) - { - m_client = nullptr; - return rc; - } - - // Register callbacks to populate internal queue - if ((rc = MQTTClient_setCallbacks(m_client, this, connlost, msgarrvd, delivered)) != MQTTCLIENT_SUCCESS) - { - MQTTClient_destroy(&m_client); - m_client = nullptr; - return rc; - } - - conn_opts.keepAliveInterval = 20; - conn_opts.cleansession = 1; - if ((rc = MQTTClient_connect(m_client, &conn_opts)) != MQTTCLIENT_SUCCESS) - { - MQTTClient_destroy(&m_client); - m_client = nullptr; - return rc; - } - - if ((rc = MQTTClient_subscribe(m_client, m_topic.c_str(), QOS)) != MQTTCLIENT_SUCCESS) - { - MQTTClient_disconnect(m_client, 1000); - MQTTClient_destroy(&m_client); - m_client = nullptr; - return rc; - } - } - return MQTTCLIENT_SUCCESS; - } - - void Close() - { - const std::lock_guard lock(m_mutex); - if (m_client) - { - if (m_type == Type::SUB) - { - MQTTClient_unsubscribe(m_client, m_topic.c_str()); - } - MQTTClient_disconnect(m_client, 1000); - MQTTClient_destroy(&m_client); - m_client = nullptr; - } - - // Wake up any blocked Receive - { - std::lock_guard q_lock(m_queueMtx); - m_stop = true; - } - m_queueCv.notify_all(); - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - const std::lock_guard lock(m_mutex); - if (os.bad() || os.fail() || !m_client) - return -1; - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - MQTTClient_message pubmsg = MQTTClient_message_initializer; - MQTTClient_deliveryToken token; - - pubmsg.payload = (void*)m_sendBuffer; - pubmsg.payloadlen = (int)totalSize; - pubmsg.qos = QOS; - pubmsg.retained = 0; - - int rc; - if ((rc = MQTTClient_publishMessage(m_client, m_topic.c_str(), &pubmsg, &token)) != MQTTCLIENT_SUCCESS) - { - return EXIT_FAILURE; - } - else - { - return EXIT_SUCCESS; - } - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - std::unique_lock q_lock(m_queueMtx); - - // Wait for data or stop signal - if (m_queueCv.wait_for(q_lock, m_recvTimeout, [this] { return !m_rxQueue.empty() || m_stop; })) - { - if (m_stop) return -1; - - if (m_rxQueue.empty()) return RECEIVE_NO_DATA; - - // Pop message - std::vector msg = std::move(m_rxQueue.front()); - m_rxQueue.pop(); - q_lock.unlock(); // Release queue lock before processing - - if (msg.size() < DmqHeader::HEADER_SIZE) return -1; - - // 1. Read Header (Network Byte Order) - header.Decode(msg.data()); - - if (!header.IsValid()) return -1; - - // 2. Write payload. One message per MQTT publish: the header length - // must match exactly. Anything else is malformed and must not be - // delivered (cut short) or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != msg.size() - DmqHeader::HEADER_SIZE) - return -1; - - if (payloadSize > 0) { - is.clear(); - is.str(""); - is.write(msg.data() + DmqHeader::HEADER_SIZE, payloadSize); - } - - // 3. ACK Logic - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - else if (m_transportMonitor) { - // Auto-ACK - xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - Send(ss_ack, ack); - } - return 0; - } - - return RECEIVE_NO_DATA; // Timeout - } - - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - m_recvTimeout = timeout; - } - -private: - /// Random client ID, so two apps (or two runs) never share one by accident. - static std::string MakeClientId(Type type) - { - static const char hex[] = "0123456789abcdef"; - std::random_device rd; - std::string id = (type == Type::PUB) ? "dmq-pub-" : "dmq-sub-"; - for (int i = 0; i < 8; ++i) - id += hex[rd() & 0xF]; - return id; - } - - static void delivered(void* context, MQTTClient_deliveryToken dt) - { - // printf("Message with token value %d delivery confirmed\n", dt); - } - - // Callback running on Paho Thread - static int msgarrvd(void* context, char* topicName, int topicLen, MQTTClient_message* message) - { - MqttTransport* instance = (MqttTransport*)context; - if (instance) - { - // Copy data to vector and push to queue - std::vector data; - data.resize(message->payloadlen); - std::memcpy(data.data(), message->payload, message->payloadlen); - - { - std::lock_guard lock(instance->m_queueMtx); - instance->m_rxQueue.push(std::move(data)); - } - instance->m_queueCv.notify_one(); - } - - MQTTClient_freeMessage(&message); - MQTTClient_free(topicName); - return 1; - } - - static void connlost(void* context, char* cause) - { - // printf("\nConnection lost\n"); - } - - MQTTClient m_client = nullptr; - std::string m_topic = DEFAULT_TOPIC; - ITransportMonitor* m_transportMonitor = nullptr; - Type m_type = Type::PUB; - - std::chrono::milliseconds m_recvTimeout = std::chrono::milliseconds(1000); - - // Thread-safe Queue for bridging Paho callback to ITransport::Receive - std::queue> m_rxQueue; - std::mutex m_queueMtx; - std::condition_variable m_queueCv; - bool m_stop = false; - - static const int BUFFER_SIZE = 4096; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; -}; - -} - -#endif // MQTT_TRANSPORT_H \ No newline at end of file diff --git a/DelegateMQ/port/transport/netx-udp/NetXUdpTransport.h b/DelegateMQ/port/transport/netx-udp/NetXUdpTransport.h deleted file mode 100644 index 351a4d0..0000000 --- a/DelegateMQ/port/transport/netx-udp/NetXUdpTransport.h +++ /dev/null @@ -1,345 +0,0 @@ -#ifndef NETX_UDP_TRANSPORT_H -#define NETX_UDP_TRANSPORT_H - -/// @file NetXUdpTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief NetX (ThreadX) UDP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the Azure RTOS NetX (or NetX Duo) -/// network stack. It is designed for embedded targets running ThreadX. -/// -/// **Dependencies:** -/// * ThreadX (`tx_api.h`) -/// * NetX (`nx_api.h`) -/// * A valid `NX_IP` instance and `NX_PACKET_POOL` must be provided at construction. -/// -/// **Key Features:** -/// 1. **Direct Execution**: Executes network operations directly on the calling thread. -/// 2. **Thread Safety**: Uses a `TX_MUTEX` to protect the NetX socket. -/// 3. **Reliability**: Integrated with `TransportMonitor` for ACKs/Retries. -/// 4. **Robustness**: Validates packet allocation and append results to prevent corruption. - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" -#include "nx_api.h" - -#include -#include -#include - -namespace dmq::transport { - -class NetXUdpTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type - { - PUB, - SUB - }; - - /// @brief Constructor - /// @param ip_ptr Pointer to the initialized NetX IP instance. - /// @param pool_ptr Pointer to the packet pool for allocating UDP packets. - NetXUdpTransport(NX_IP* ip_ptr, NX_PACKET_POOL* pool_ptr) - : m_ip(ip_ptr) - , m_pool(pool_ptr) - , m_sendTransport(this) - , m_recvTransport(this) - { - // Initialize mutexes for socket protection (No Inherit to detect deadlocks easier). - // m_recvMutex is held by Receive(); m_mutex by Send() and socket setup. - // Lock order: m_recvMutex, then m_mutex. - tx_mutex_create(&m_mutex, (CHAR*)"NetXTransportMutex", TX_NO_INHERIT); - tx_mutex_create(&m_recvMutex, (CHAR*)"NetXTransportRecvMutex", TX_NO_INHERIT); - memset(&m_socket, 0, sizeof(m_socket)); - } - - ~NetXUdpTransport() - { - Close(); - tx_mutex_delete(&m_recvMutex); - tx_mutex_delete(&m_mutex); - } - - /// @brief Initialize the UDP socket. - int Create(Type type, const char* addr_str, uint16_t port) - { - Close(); // a second Create() replaces the socket instead of leaking it - tx_mutex_get(&m_recvMutex, TX_WAIT_FOREVER); - tx_mutex_get(&m_mutex, TX_WAIT_FOREVER); - - m_type = type; - m_port = port; - - // Parse IP Address - m_targetIp = 0; - if (addr_str) { - uint32_t a, b, c, d; - if (std::sscanf(addr_str, "%u.%u.%u.%u", &a, &b, &c, &d) == 4) { - // Construct IP ULONG (Assumes NetX expects Host Byte Order for setup) - m_targetIp = (a << 24) | (b << 16) | (c << 8) | d; - } - } - - // Create the UDP Socket - UINT ret = nx_udp_socket_create(m_ip, &m_socket, (CHAR*)"DelegateMQ_Sock", - NX_IP_NORMAL, NX_FRAGMENT_OKAY, 0x80, 5); - if (ret != NX_SUCCESS) { - tx_mutex_put(&m_mutex); - tx_mutex_put(&m_recvMutex); - return -1; - } - - // Bind - if (type == Type::SUB) { - ret = nx_udp_socket_bind(&m_socket, port, NX_WAIT_FOREVER); - } else { - ret = nx_udp_socket_bind(&m_socket, NX_ANY_PORT, NX_WAIT_FOREVER); - } - - if (ret != NX_SUCCESS) { - nx_udp_socket_delete(&m_socket); - memset(&m_socket, 0, sizeof(m_socket)); - tx_mutex_put(&m_mutex); - tx_mutex_put(&m_recvMutex); - return -1; - } - - SetRecvTimeout(type == Type::PUB ? dmq::UDP_PUB_RECV_TIMEOUT : dmq::UDP_SUB_RECV_TIMEOUT); - - tx_mutex_put(&m_mutex); - tx_mutex_put(&m_recvMutex); - return 0; - } - - /// @details Waits for a Receive() in progress on another thread to return - /// (at most its receive timeout) first. - void Close() - { - tx_mutex_get(&m_recvMutex, TX_WAIT_FOREVER); - tx_mutex_get(&m_mutex, TX_WAIT_FOREVER); - - if (m_socket.nx_udp_socket_id != 0) - { - nx_udp_socket_unbind(&m_socket); - nx_udp_socket_delete(&m_socket); - memset(&m_socket, 0, sizeof(m_socket)); - } - - tx_mutex_put(&m_mutex); - tx_mutex_put(&m_recvMutex); - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - tx_mutex_get(&m_mutex, TX_WAIT_FOREVER); - // Convert ms to ThreadX ticks - m_recvTimeout = (ULONG)((timeout.count() * TX_TIMER_TICKS_PER_SECOND) / 1000); - if (m_recvTimeout == 0 && timeout.count() > 0) m_recvTimeout = 1; - tx_mutex_put(&m_mutex); - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - tx_mutex_get(&m_mutex, TX_WAIT_FOREVER); - - if (os.bad() || os.fail()) { - tx_mutex_put(&m_mutex); - return -1; - } - - // Block regular data on SUB socket (only ACKs allowed) - if (m_type == Type::SUB && header.GetId() != dmq::ACK_REMOTE_ID) { - tx_mutex_put(&m_mutex); - return -1; - } - - if (m_sendTransport != this) { - tx_mutex_put(&m_mutex); - return -1; - } - - auto payload = os.str(); - // The receiver's buffer (same DMQ_UDP_BUFFER_SIZE) must hold the datagram. - if (payload.length() > dmq::UDP_BUFFER_SIZE - DmqHeader::HEADER_SIZE) { - tx_mutex_put(&m_mutex); - return -1; - } - - // 1. Allocate NetX Packet - NX_PACKET* packet_ptr = nullptr; - UINT ret = nx_packet_allocate(m_pool, &packet_ptr, NX_UDP_PACKET, NX_NO_WAIT); - if (ret != NX_SUCCESS) { - tx_mutex_put(&m_mutex); - return -1; - } - - // 2. Prepare Header (Network Byte Order) - DmqHeader headerCopy = header; - headerCopy.SetLength(static_cast(payload.length())); - - UCHAR headerBuf[DmqHeader::HEADER_SIZE]; - headerCopy.Encode(headerBuf); - - // 3. Append Data (With Error Checks) - // Check return value of every append. If one fails, the packet is corrupted/partial. - if (nx_packet_data_append(packet_ptr, headerBuf, sizeof(headerBuf), m_pool, NX_NO_WAIT) != NX_SUCCESS) - goto cleanup_and_fail; - - if (nx_packet_data_append(packet_ptr, (VOID*)payload.data(), payload.size(), m_pool, NX_NO_WAIT) != NX_SUCCESS) - goto cleanup_and_fail; - - // 4. Send - // nx_udp_socket_send typically releases the packet on internal errors. - // However, if it fails due to binding issues (before driver), it might not. - ret = nx_udp_socket_send(&m_socket, packet_ptr, m_targetIp, m_port); - - if (ret != NX_SUCCESS) { - // Defensive release: Verify if your specific NetX version auto-releases on specific errors. - // Standard practice is often to release if send fails. - nx_packet_release(packet_ptr); - tx_mutex_put(&m_mutex); - return -1; - } - - tx_mutex_put(&m_mutex); - return 0; - - cleanup_and_fail: - nx_packet_release(packet_ptr); - tx_mutex_put(&m_mutex); - return -1; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - // m_recvMutex, not m_mutex: a Send() on another thread isn't held up - // for the receive timeout. - tx_mutex_get(&m_recvMutex, TX_WAIT_FOREVER); - const int result = ReceiveLocked(is, header); - tx_mutex_put(&m_recvMutex); - return result; - } - - void SetTransportMonitor(ITransportMonitor* tm) { m_transportMonitor = tm; } - void SetSendTransport(ITransport* st) { m_sendTransport = st; } - void SetRecvTransport(ITransport* rt) { m_recvTransport = rt; } - -private: - /// Receive() body; caller holds m_recvMutex. - int ReceiveLocked(xstringstream& is, DmqHeader& header) - { - if (m_recvTransport != this || m_socket.nx_udp_socket_id == 0) { - return -1; - } - - NX_PACKET* packet_ptr = nullptr; - - // Use configured timeout - UINT ret = nx_udp_socket_receive(&m_socket, &packet_ptr, m_recvTimeout); - if (ret == NX_NO_PACKET) { - return RECEIVE_NO_DATA; - } - if (ret != NX_SUCCESS) { - return -1; - } - - // --- Extract Source Info for ACKs --- - ULONG srcIp = 0; - UINT srcPort = 0; - nx_udp_source_extract(packet_ptr, &srcIp, &srcPort); - - // Validate total length before attempting retrieve - if (packet_ptr->nx_packet_length > sizeof(m_recvBuffer)) { - nx_packet_release(packet_ptr); - return -1; // Packet too large for buffer - } - - // Retrieve copies data out of packet (handling chained packets if necessary) - ULONG bytesRead = 0; - ret = nx_packet_data_retrieve(packet_ptr, m_recvBuffer, &bytesRead); - nx_packet_release(packet_ptr); - - if (ret != NX_SUCCESS || bytesRead < DmqHeader::HEADER_SIZE) { - return -1; - } - - // Parse Header - header.Decode(m_recvBuffer); - if (!header.IsValid()) { - return -1; - } - - // One datagram is one message: the header length must match exactly. - // Anything else is malformed and must not be delivered or ACKed. - if (bytesRead != (ULONG)(DmqHeader::HEADER_SIZE + header.GetLength())) { - return -1; - } - - // A SUB replies to whoever sent the last valid message. Updated only - // now, after validation, and under m_mutex since Send() uses it. - if (m_type == Type::SUB) { - tx_mutex_get(&m_mutex, TX_WAIT_FOREVER); - m_targetIp = srcIp; - m_port = srcPort; - tx_mutex_put(&m_mutex); - } - - // Reset stream state before writing - is.clear(); - is.str(""); - - // Write Payload to stream - is.write((char*)(m_recvBuffer + DmqHeader::HEADER_SIZE), header.GetLength()); - - // --- ACK Logic --- - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - else if (m_sendTransport) { - xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - ack.SetLength(0); - m_sendTransport->Send(ss_ack, ack); // takes m_mutex; m_recvMutex is held: same lock order - } - - return 0; - } - - NX_IP* m_ip = nullptr; - NX_PACKET_POOL* m_pool = nullptr; - NX_UDP_SOCKET m_socket; - TX_MUTEX m_mutex; ///< Socket setup and Send() state (target address) - TX_MUTEX m_recvMutex; ///< Held by Receive(); taken before m_mutex - - /// Receive buffer (header + payload), DMQ_UDP_BUFFER_SIZE. A member, not a - /// stack array: thread stacks on these targets are small. - UCHAR m_recvBuffer[dmq::UDP_BUFFER_SIZE]; - - ULONG m_targetIp = 0; - UINT m_port = 0; - - Type m_type = Type::PUB; - - ULONG m_recvTimeout = 1; // Default 1 tick - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; -}; - -} - -#endif // NETX_UDP_TRANSPORT_H \ No newline at end of file diff --git a/DelegateMQ/port/transport/nng/NngTransport.h b/DelegateMQ/port/transport/nng/NngTransport.h deleted file mode 100644 index 05f3a63..0000000 --- a/DelegateMQ/port/transport/nng/NngTransport.h +++ /dev/null @@ -1,355 +0,0 @@ -#ifndef NNG_TRANSPORT_H -#define NNG_TRANSPORT_H - -/// @file NngTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief NNG transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the NNG (Nanomsg Next Gen) -/// lightweight messaging library. It supports multiple scalability protocols including -/// PAIR (1-to-1 bidrectional) and PUB/SUB (1-to-many unidirectional). -/// -/// Key Features: -/// 1. **Thread Safety**: Uses a `dmq::RecursiveMutex` to protect the NNG socket, -/// allowing safe concurrent access from the Send and Receive threads (NNG sockets -/// are not inherently thread-safe). -/// 2. **Scalability Protocols**: flexible configuration for different topologies: -/// * `PAIR_CLIENT`/`PAIR_SERVER`: Exclusive 1-to-1 connection. -/// * `PUB`/`SUB`: Efficient distribution to multiple subscribers. -/// 3. **Non-Blocking**: Uses asynchronous messaging patterns provided by NNG. -/// 4. **Reliability**: Integrates with `TransportMonitor` to providing sequence tracking -/// and ACKs even over PUB/SUB (when a return channel is available). -/// -/// @note Requires the `libnng` library. - -// Add Windows Sockets headers for htons/ntohs -#if defined(_WIN32) || defined(_WIN64) - #include - #pragma comment(lib, "ws2_32.lib") -#else - #include -#endif - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/ITransportMonitor.h" -#include "port/transport/common/DmqHeader.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief NNG transport class. -/// @details Logic now executes directly on the caller's thread, protected by a mutex -/// to prevent concurrent access to the underlying NNG socket. -class NngTransport : public ITransport -{ -public: - enum class Type - { - PAIR_CLIENT, - PAIR_SERVER, - PUB, - SUB - }; - - NngTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~NngTransport() - { - Destroy(); - } - - int Create(Type type, const char* addr) - { - std::lock_guard lock(m_mutex); - - // Initialize NNG context - m_type = type; - - int rc = 0; - if (m_type == Type::PAIR_CLIENT) - { - rc = nng_pair0_open(&m_nngSocket); - if (rc != 0) { - std::cerr << "Failed to open NNG pair client socket: " << nng_strerror(rc) << std::endl; - return rc; - } - rc = nng_dial(m_nngSocket, addr, nullptr, 0); - if (rc != 0) { - std::cerr << "Failed to dial address: " << nng_strerror(rc) << std::endl; - nng_close(m_nngSocket); - return rc; - } - // Set recv timeout to avoid blocking forever - nng_duration timeout = 100; // 100ms - nng_socket_set_ms(m_nngSocket, NNG_OPT_RECVTIMEO, timeout); - } - else if (m_type == Type::PAIR_SERVER) - { - rc = nng_pair0_open(&m_nngSocket); - if (rc != 0) { - std::cerr << "Failed to open NNG pair server socket: " << nng_strerror(rc) << std::endl; - return rc; - } - rc = nng_listen(m_nngSocket, addr, nullptr, 0); - if (rc != 0) { - std::cerr << "Failed to listen on address: " << nng_strerror(rc) << std::endl; - return rc; - } - // Set recv timeout - nng_duration timeout = 100; // 100ms - nng_socket_set_ms(m_nngSocket, NNG_OPT_RECVTIMEO, timeout); - } - else if (m_type == Type::PUB) - { - rc = nng_pub0_open(&m_nngSocket); - if (rc != 0) { - std::cerr << "Failed to open NNG PUB socket: " << nng_strerror(rc) << std::endl; - return rc; - } - rc = nng_listen(m_nngSocket, addr, nullptr, 0); - if (rc != 0) { - std::cerr << "Failed to listen on address: " << nng_strerror(rc) << std::endl; - return rc; - } - } - else if (m_type == Type::SUB) - { - rc = nng_sub0_open(&m_nngSocket); - if (rc != 0) { - std::cerr << "Failed to open NNG SUB socket: " << nng_strerror(rc) << std::endl; - return rc; - } - rc = nng_dial(m_nngSocket, addr, nullptr, 0); - if (rc != 0) { - std::cerr << "Failed to dial address: " << nng_strerror(rc) << std::endl; - nng_close(m_nngSocket); - return rc; - } - - // Subscribe to all messages - rc = nng_socket_set(m_nngSocket, NNG_OPT_SUB_SUBSCRIBE, "", 0); - if (rc != 0) { - std::cerr << "Failed to set subscription filter: " << nng_strerror(rc) << std::endl; - return rc; - } - - // Set recv timeout - nng_duration timeout = 100; // 100ms - nng_socket_set_ms(m_nngSocket, NNG_OPT_RECVTIMEO, timeout); - } - else - { - std::cerr << "Invalid socket type" << std::endl; - return 1; - } - - return 0; - } - - void Close() - { - std::lock_guard lock(m_mutex); - - // Close the socket - if (nng_socket_id(m_nngSocket) != 0) { - nng_close(m_nngSocket); - } - m_nngSocket = NNG_SOCKET_INITIALIZER; - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - std::lock_guard lock(m_mutex); - if (nng_socket_id(m_nngSocket) != 0) - { - nng_duration ms = static_cast(timeout.count()); - nng_socket_set_ms(m_nngSocket, NNG_OPT_RECVTIMEO, ms); - } - } - - void Destroy() - { - Close(); - // NNG doesn't require explicit context terminations like ZMQ - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - std::lock_guard lock(m_mutex); - - if (os.bad() || os.fail() || nng_socket_id(m_nngSocket) == 0) { - return -1; - } - - if (m_type == Type::SUB) { - return -1; - } - - if (m_sendTransport != this) { - return -1; - } - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - // Send data using NNG - // Use NNG_FLAG_NONBLOCK to prevent deadlocks if peer is gone - int err = nng_send(m_nngSocket, (void*)m_sendBuffer, totalSize, NNG_FLAG_NONBLOCK); - if (err != 0) - { - // NNG_EAGAIN means queue full (congestion), treat as error to trigger retry logic - return -1; - } - - return 0; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override { - // Lock Guard - std::lock_guard lock(m_mutex); - - if (nng_socket_id(m_nngSocket) == 0) { - return -1; - } - - if (m_type == Type::PUB) { - return -1; - } - - if (m_recvTransport != this) { - return -1; - } - - size_t size = sizeof(m_buffer); - - // Receive with 100ms timeout (set in Create) - int err = nng_recv(m_nngSocket, m_buffer, &size, 0); - if (err == NNG_ETIMEDOUT || err == NNG_EAGAIN) { - return RECEIVE_NO_DATA; - } - if (err != 0) { - return -1; - } - - if (size < DmqHeader::HEADER_SIZE) { - return -1; - } - - // Never trust a size beyond what the buffer holds. - if (size > sizeof(m_buffer)) { - return -1; - } - - // 1. Read Header (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) { - return -1; - } - - // 2. Write payload - // One message per NNG message: the header length must match exactly. Anything - // else is malformed and must not be delivered (cut short) or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != size - DmqHeader::HEADER_SIZE) - return -1; - - if (payloadSize > 0) { - is.clear(); - is.str(""); - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - if (header.GetId() == dmq::ACK_REMOTE_ID) - { - // Receiver ack'ed message. Remove sequence number from monitor. - if (m_transportMonitor) - m_transportMonitor->Remove(header.GetSeqNum()); - } - else - { - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - if (m_sendTransport) - { - // Send header with received seqNum as the ack message - dmq::xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - - // Note: Recursive mutex allows Send() here - m_sendTransport->Send(ss_ack, ack); - } - } - - return 0; // Success - } - - // Set a transport monitor for checking message ack - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - // Set an alternative send transport - void SetSendTransport(ITransport* sendTransport) - { - m_sendTransport = sendTransport; - } - - // Set an alternative receive transport - void SetRecvTransport(ITransport* recvTransport) - { - m_recvTransport = recvTransport; - } - -private: - nng_socket m_nngSocket = NNG_SOCKET_INITIALIZER; - Type m_type = Type::PAIR_CLIENT; - - // Mutex to protect non-thread-safe socket - dmq::RecursiveMutex m_mutex; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = {}; - char m_sendBuffer[BUFFER_SIZE] = {}; -}; - -} // namespace dmq::transport - -#endif diff --git a/DelegateMQ/port/transport/serial/SerialTransport.h b/DelegateMQ/port/transport/serial/SerialTransport.h deleted file mode 100644 index 80bde51..0000000 --- a/DelegateMQ/port/transport/serial/SerialTransport.h +++ /dev/null @@ -1,245 +0,0 @@ -#ifndef SERIAL_TRANSPORT_H -#define SERIAL_TRANSPORT_H - -/// @file SerialTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Libserialport-based transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the cross-platform `libserialport` -/// library. It provides a reliable, packet-based communication layer over RS-232/UART -/// serial links. -/// -/// Key Features: -/// 1. **Thread-Safe Access**: Uses a recursive mutex to serialize access to the -/// underlying serial port, allowing concurrent Send/Receive calls from different threads. -/// 2. **Data Framing**: Encapsulates delegate arguments in a binary-safe frame structure: -/// `[Header (10 bytes)] + [Payload (N bytes)] + [CRC16 (2 bytes)]`. -/// 3. **Data Integrity**: Automatically calculates and verifies a 16-bit CRC for every -/// packet to detect transmission errors common in serial communication. -/// 4. **Reliability**: Integrates with `TransportMonitor` to track sequence numbers and -/// support ACK-based reliability when paired with the `RetryMonitor`. -/// -/// @note This class requires `libserialport` to be linked. - -#include "libserialport.h" -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" -#include "extras/util/crc16.h" - -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -class SerialTransport : public ITransport -{ -public: - SerialTransport() : m_sendTransport(this), m_recvTransport(this) {} - - ~SerialTransport() { Close(); } - - int Create(const char* portName, int baudRate) - { - std::lock_guard recvLock(m_recvMutex); - std::lock_guard lock(m_mutex); - Close(); // a second Create() replaces the port instead of leaking it - sp_return ret = sp_get_port_by_name(portName, &m_port); - if (ret != SP_OK) { - std::cerr << "SerialTransport: Could not find port " << portName << std::endl; - return -1; - } - - ret = sp_open(m_port, SP_MODE_READ_WRITE); - if (ret != SP_OK) { - std::cerr << "SerialTransport: Could not open port " << portName << std::endl; - sp_free_port(m_port); - m_port = nullptr; - return -1; - } - - sp_set_baudrate(m_port, baudRate); - sp_set_bits(m_port, 8); - sp_set_parity(m_port, SP_PARITY_NONE); - sp_set_stopbits(m_port, 1); - sp_set_flowcontrol(m_port, SP_FLOWCONTROL_NONE); - return 0; - } - - /// @details Waits for a Receive() in progress on another thread to return - /// (at most about a second: its reads time out), so the port is never - /// freed under it. - void Close() - { - std::lock_guard recvLock(m_recvMutex); - std::lock_guard lock(m_mutex); - if (m_port) { - sp_close(m_port); - sp_free_port(m_port); - m_port = nullptr; - } - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - std::lock_guard lock(m_mutex); - if (!m_port) return -1; - - DmqHeader headerCopy = header; - dmq::xstring payload = os.str(); - if (payload.length() > UINT16_MAX) return -1; - headerCopy.SetLength(static_cast(payload.length())); - - dmq::xostringstream ss(std::ios::in | std::ios::out | std::ios::binary); - - // SERIALIZE HEADER (Big Endian) - char headerBuf[DmqHeader::HEADER_SIZE]; - headerCopy.Encode(headerBuf); - ss.write(headerBuf, DmqHeader::HEADER_SIZE); - - // Payload - ss.write(payload.data(), payload.size()); - - // CRC (big-endian) - dmq::xstring packetWithoutCrc = ss.str(); - uint16_t crc = dmq::util::Crc16CalcBlock((unsigned char*)packetWithoutCrc.c_str(), (int)packetWithoutCrc.length(), 0xFFFF); - const char crcBytes[2] = { static_cast(crc >> 8), static_cast(crc & 0xFF) }; - ss.write(crcBytes, sizeof(crcBytes)); - - dmq::xstring packetData = ss.str(); - - int result = sp_blocking_write(m_port, packetData.c_str(), packetData.length(), 1000); - if (result != (int)packetData.length()) return -1; - - return 0; - } - - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override - { - // Held for the whole read so Close() can't free m_port under it. Send() - // uses m_mutex, so it's never blocked by an idle read. - std::lock_guard recvLock(m_recvMutex); - if (!m_port) return -1; - if (m_recvTransport != this) return -1; - - char headerBuf[DmqHeader::HEADER_SIZE]; - - // 1. Sync Loop: both marker bytes, tracked with a sliding previous byte - // so a stray 0xAA right before a real marker (0xAA 0xAA 0x55) still - // syncs on the real one. - const uint8_t markerHigh = (uint8_t)(DmqHeader::MARKER >> 8); - const uint8_t markerLow = (uint8_t)(DmqHeader::MARKER & 0xFF); - uint8_t prev = 0; - while (true) { - // Waiting for a frame start: nothing arriving is "no data", not an - // error. After a 0xAA, give the next byte longer to arrive. - char b = 0; - int r = sp_blocking_read(m_port, &b, 1, prev == markerHigh ? 100 : 10); - if (r == 0) { - if (prev == markerHigh) { prev = 0; continue; } // lone 0xAA - return RECEIVE_NO_DATA; - } - if (r < 0) return -1; - - if (prev == markerHigh && (uint8_t)b == markerLow) { - headerBuf[0] = (char)markerHigh; - headerBuf[1] = (char)markerLow; - break; - } - prev = (uint8_t)b; - } - - // 2. Read Rest of Header - // INCREASED TIMEOUT: 1000ms (was 100ms) to allow OS latency - if (!ReadExact(headerBuf + 2, DmqHeader::HEADER_SIZE - 2, 1000)) - return -1; - - // 3. Deserialize - header.Decode(headerBuf); - - if (!header.IsValid()) return -1; - - // 4. Payload - uint16_t len = header.GetLength(); - if (len > 0) { - if (len > BUFFER_SIZE) return -1; - // INCREASED TIMEOUT: 1000ms - if (!ReadExact(m_buffer, len, 1000)) return -1; - is.write(m_buffer, len); - } - - // 5. CRC Check (big-endian) - unsigned char crcBytes[2] = {}; - // INCREASED TIMEOUT: 500ms - if (!ReadExact(reinterpret_cast(crcBytes), sizeof(crcBytes), 500)) return -1; - const uint16_t receivedCrc = static_cast((crcBytes[0] << 8) | crcBytes[1]); - - uint16_t calcCrc = dmq::util::Crc16CalcBlock((unsigned char*)headerBuf, DmqHeader::HEADER_SIZE, 0xFFFF); - if (len > 0) calcCrc = dmq::util::Crc16CalcBlock((unsigned char*)m_buffer, len, calcCrc); - - if (receivedCrc != calcCrc) { - std::cerr << "CRC Mismatch" << std::endl; - return -1; - } - - // 6. ACKs - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - else if (m_sendTransport) { - dmq::xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - m_sendTransport->Send(ss_ack, ack); - } - return 0; - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - m_recvTimeout = timeout; - } - - void SetTransportMonitor(ITransportMonitor* tm) { m_transportMonitor = tm; } - void SetSendTransport(ITransport* st) { m_sendTransport = st; } - void SetRecvTransport(ITransport* rt) { m_recvTransport = rt; } - -private: - bool ReadExact(char* dest, size_t size, unsigned int timeoutMs) - { - size_t totalRead = 0; - // Keep attempting to read until we have 'size' bytes - while (totalRead < size) - { - if (!m_port) return false; - int ret = sp_blocking_read(m_port, dest + totalRead, size - totalRead, timeoutMs); - if (ret < 0) return false; // Error - if (ret == 0) return false; // Timeout - totalRead += ret; - } - return true; - } - - sp_port* m_port = nullptr; - std::recursive_mutex m_mutex; ///< Port open/close and Send() - std::recursive_mutex m_recvMutex; ///< Held by Receive(); Close() takes it first - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - std::chrono::milliseconds m_recvTimeout = std::chrono::milliseconds(2000); - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = { 0 }; -}; - -} // namespace dmq::transport - -#endif diff --git a/DelegateMQ/port/transport/stm32-uart/Stm32UartTransport.h b/DelegateMQ/port/transport/stm32-uart/Stm32UartTransport.h deleted file mode 100644 index 04ad3cf..0000000 --- a/DelegateMQ/port/transport/stm32-uart/Stm32UartTransport.h +++ /dev/null @@ -1,347 +0,0 @@ -#ifndef STM32_UART_TRANSPORT_H -#define STM32_UART_TRANSPORT_H - -/// @file Stm32UartTransport.h -/// @brief STM32 HAL UART transport implementation for DelegateMQ (FreeRTOS). -/// -/// @details -/// This class provides a robust, thread-safe transport layer for serial communication -/// on STM32 microcontrollers running FreeRTOS. -/// -/// **Key Architecture: Interrupt-Driven Ring Buffer** -/// Instead of polling the UART (which wastes CPU) or using blocking HAL calls -/// (which starve other FreeRTOS tasks), this implementation uses: -/// 1. **UART RX Interrupt:** Fires immediately when a byte arrives, pushing it into a `UartRingBuffer`. -/// 2. **Binary Semaphore:** The `Receive()` task sleeps on this semaphore. It is only woken up -/// by the ISR when data is actually available. -/// 3. **Recursive Mutex:** Protects the `Send()` function to ensure atomic packet transmission -/// even if multiple threads try to send simultaneously. -/// -/// **Data Integrity:** -/// * Implements strict `0xAA 0x55` framing synchronization. -/// * Calculates and verifies 16-bit CRC for every packet (sent big-endian, after -/// the payload). -/// * Sizes and timeouts come from DMQ_UART_* in DelegateMQConfig.h. -/// * Handles reliable delivery via `TransportMonitor` (ACKs/Retries). - -#include "stm32f4xx_hal.h" -#include "stm32f4xx_hal_uart.h" -#include "delegate/DelegateOpt.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/ITransportMonitor.h" -#include "extras/util/crc16.h" - -// FreeRTOS Includes -#include "FreeRTOS.h" -#include "semphr.h" -#include "task.h" - -#include -#include - -namespace dmq::transport { - -// ---------------------------------------------------------------------------- -// Forward Declarations & Global Hook -// ---------------------------------------------------------------------------- -class Stm32UartTransport; - -} // namespace dmq::transport - -// Global pointer to the active transport instance. -// This is defined in main.cpp and used by the C-style HAL Interrupt Callback -// to route the hardware interrupt back into the C++ class. -extern dmq::transport::Stm32UartTransport* g_uartTransportInstance; - -namespace dmq::transport { - -// ============================================================================ -// UartRingBuffer -// ============================================================================ -/// @brief A lightweight, thread-safe (Single Producer / Single Consumer) Ring Buffer. -/// @tparam Size The size of the buffer in bytes. Must be large enough to hold -/// bursts of data (e.g., 1024 bytes) to prevent overrun. -template -class UartRingBuffer { -public: - /// Push a byte into the buffer (Called from ISR). - /// @return false if the buffer was full and the byte was dropped. - bool Put(uint8_t data) { - size_t next_head = (m_head + 1) % Size; - if (next_head == m_tail) return false; // Buffer Full - m_buffer[m_head] = data; - m_head = next_head; - return true; - } - - /// Pop a byte from the buffer (Called from Consumer Task). - bool Get(uint8_t& data) { - if (m_head == m_tail) return false; // Buffer Empty - data = m_buffer[m_tail]; - m_tail = (m_tail + 1) % Size; - return true; - } - - void Clear() { m_head = m_tail = 0; } - -private: - volatile uint8_t m_buffer[Size]; - volatile size_t m_head = 0; - volatile size_t m_tail = 0; -}; - -// ============================================================================ -// Stm32UartTransport Class -// ============================================================================ -class Stm32UartTransport : public ITransport -{ -public: - Stm32UartTransport() : m_huart(nullptr), m_sendTransport(this), m_recvTransport(this) {} - Stm32UartTransport(UART_HandleTypeDef* huart) : m_huart(huart), m_sendTransport(this), m_recvTransport(this) {} - - ~Stm32UartTransport() { - if (m_mutex) vSemaphoreDelete(m_mutex); - if (m_rxSemaphore) vSemaphoreDelete(m_rxSemaphore); - g_uartTransportInstance = nullptr; - } - - /// @brief Initialize the Transport and enable UART Interrupts. - /// @param huart Pointer to the HAL UART handle (e.g., &huart6). - /// @return 0 on success, -1 on failure. - int Create(UART_HandleTypeDef* huart) { - m_huart = huart; - g_uartTransportInstance = this; // Hook global pointer for ISR - - // Create OS primitives - if (!m_mutex) m_mutex = xSemaphoreCreateRecursiveMutex(); - if (!m_rxSemaphore) m_rxSemaphore = xSemaphoreCreateBinary(); - - if (!m_huart || !m_mutex || !m_rxSemaphore) return -1; - - // Clear potential hardware error flags from startup noise - __HAL_UART_CLEAR_OREFLAG(m_huart); - __HAL_UART_CLEAR_NEFLAG(m_huart); - __HAL_UART_CLEAR_FEFLAG(m_huart); - - // START RECEIVING: Enable RX Interrupt for the first byte. - // This kicks off the chain; subsequent bytes are re-armed in OnRxCplt. - if (HAL_UART_Receive_IT(m_huart, &m_rxByte, 1) != HAL_OK) return -1; - - return 0; - } - - virtual void Close() { - // Optional: Disable UART interrupts here if destroying the transport. - } - - // ------------------------------------------------------------------------ - // Send() Implementation - // ------------------------------------------------------------------------ - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override { - if (os.bad() || os.fail()) return -1; - if (!m_huart || !m_mutex) return -1; - - // CRITICAL SECTION: Protect UART TX hardware - if (xSemaphoreTakeRecursive(m_mutex, portMAX_DELAY) != pdTRUE) return -1; - - const uint32_t txTimeout = static_cast(dmq::UART_TX_TIMEOUT.count()); - - // 1. Prepare Packet Structure - dmq::xstring payload = os.str(); - if (payload.length() > BUFFER_SIZE) { // receiver's reassembly limit - xSemaphoreGiveRecursive(m_mutex); - return -1; - } - DmqHeader headerCopy = header; - headerCopy.SetLength((uint16_t)payload.length()); - - // Serialize Header (Network Byte Order) - uint8_t packet[DmqHeader::HEADER_SIZE]; - headerCopy.Encode(packet); - - // 2. Send Header - if (HAL_UART_Transmit(m_huart, packet, DmqHeader::HEADER_SIZE, txTimeout) != HAL_OK) { - xSemaphoreGiveRecursive(m_mutex); return -1; - } - - // 3. Send Payload - if (payload.length() > 0) { - if (HAL_UART_Transmit(m_huart, (uint8_t*)payload.data(), (uint16_t)payload.length(), txTimeout) != HAL_OK) { - xSemaphoreGiveRecursive(m_mutex); return -1; - } - } - - // 4. Calculate and Send CRC (Required for PC communication) - uint16_t crc = dmq::util::Crc16CalcBlock(packet, DmqHeader::HEADER_SIZE, 0xFFFF); - if (payload.length() > 0) crc = dmq::util::Crc16CalcBlock((uint8_t*)payload.data(), payload.length(), crc); - - const uint8_t crcBytes[2] = { static_cast(crc >> 8), static_cast(crc) }; // big-endian - if (HAL_UART_Transmit(m_huart, const_cast(crcBytes), 2, txTimeout) != HAL_OK) { - xSemaphoreGiveRecursive(m_mutex); return -1; - } - - xSemaphoreGiveRecursive(m_mutex); - return 0; - } - - // ------------------------------------------------------------------------ - // Receive() Implementation - // ------------------------------------------------------------------------ - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override { - if (m_recvTransport != this) return -1; - - uint8_t headerBuf[DmqHeader::HEADER_SIZE]; - const uint8_t markerHigh = (uint8_t)(DmqHeader::MARKER >> 8); - const uint8_t markerLow = (uint8_t)(DmqHeader::MARKER & 0xFF); - const TickType_t frameTimeout = pdMS_TO_TICKS(dmq::UART_FRAME_TIMEOUT.count()); - - // 1. Sync Loop: both marker bytes, so a stray 0xAA in other data doesn't - // start a frame. Waits indefinitely (sleeping on the semaphore while the - // ring buffer is empty) until a 0xAA arrives; only the byte after it - // must come within the frame timeout. Stray bytes followed by an idle - // line are discarded, not reported as an error. - uint8_t prev = 0; - while (true) { - uint8_t b = 0; - const TickType_t wait = (prev == markerHigh) ? frameTimeout : portMAX_DELAY; - if (!ReadByte(b, wait)) { - if (prev == markerHigh) { prev = 0; continue; } // lone 0xAA: keep syncing - return -1; - } - if (prev == markerHigh && b == markerLow) break; - prev = b; - } - headerBuf[0] = markerHigh; - headerBuf[1] = markerLow; - - // 2. Read Rest of Header. Each later byte must arrive within the frame - // timeout: a frame cut short by lost bytes is dropped instead of - // swallowing the start of the next one. - for (int i = 2; i < (int)DmqHeader::HEADER_SIZE; i++) { - if (!ReadByte(headerBuf[i], frameTimeout)) return -1; - } - - // Deserialize Header - header.Decode(headerBuf); - - if (!header.IsValid()) return -1; - - // 3. Read Payload - uint16_t len = header.GetLength(); - if (len > 0) { - if (len > BUFFER_SIZE) return -1; - for (int i = 0; i < len; i++) { - if (!ReadByte(m_tempRxBuffer[i], frameTimeout)) return -1; - } - is.clear(); is.str(""); is.write((char*)m_tempRxBuffer, len); - } - - // 4. Read & Verify CRC (big-endian) - uint8_t crcBytes[2]; - if (!ReadByte(crcBytes[0], frameTimeout)) return -1; - if (!ReadByte(crcBytes[1], frameTimeout)) return -1; - const uint16_t receivedCrc = static_cast((crcBytes[0] << 8) | crcBytes[1]); - - uint16_t calcCrc = dmq::util::Crc16CalcBlock(headerBuf, DmqHeader::HEADER_SIZE, 0xFFFF); - if (len > 0) calcCrc = dmq::util::Crc16CalcBlock(m_tempRxBuffer, len, calcCrc); - if (receivedCrc != calcCrc) return -1; - - // 5. Handle ACKs - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - else if (m_sendTransport) { - // Auto-Reply with ACK - dmq::xostringstream ss; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - m_sendTransport->Send(ss, ack); - } - return 0; - } - - // ------------------------------------------------------------------------ - // Interrupt Handler - // ------------------------------------------------------------------------ - /// @brief Called by HAL_UART_RxCpltCallback when a byte arrives. - void OnRxCplt() { - BaseType_t xHigherPriorityTaskWoken = pdFALSE; - - // 1. Push data to thread-safe buffer. A full buffer drops the byte (the - // frame then fails its CRC); count it so the app can see it happening. - if (!m_ringBuffer.Put(m_rxByte)) - m_rxOverflows.fetch_add(1, std::memory_order_relaxed); - - // 2. Wake up the Receive() task immediately - xSemaphoreGiveFromISR(m_rxSemaphore, &xHigherPriorityTaskWoken); - - // 3. Re-arm interrupt for the next byte - HAL_UART_Receive_IT(m_huart, &m_rxByte, 1); - - // 4. Context Switch if necessary - portYIELD_FROM_ISR(xHigherPriorityTaskWoken); - } - - /// @brief Called by HAL_UART_ErrorCallback. ISR-safe: no OS calls. - /// @details A blocking UART error (e.g. overrun) makes the HAL abort the - /// interrupt-driven receive, so no further bytes would ever arrive. Clear - /// the error flags and re-arm single-byte reception. For non-blocking - /// errors (noise/framing/parity) the HAL keeps receiving, RxState stays - /// busy, and re-arming is skipped. Any frame the error corrupted is - /// rejected by the CRC check in Receive(). - void OnRxError() { - if (!m_huart) return; - - __HAL_UART_CLEAR_OREFLAG(m_huart); - __HAL_UART_CLEAR_NEFLAG(m_huart); - __HAL_UART_CLEAR_FEFLAG(m_huart); - - if (m_huart->RxState == HAL_UART_STATE_READY) - HAL_UART_Receive_IT(m_huart, &m_rxByte, 1); - } - - void SetTransportMonitor(ITransportMonitor* tm) { m_transportMonitor = tm; } - void SetSendTransport(ITransport* st) { m_sendTransport = st; } - void SetRecvTransport(ITransport* rt) { m_recvTransport = rt; } - - /// @brief Received bytes dropped because the RX ring buffer was full. - /// Non-zero means DMQ_UART_RX_RING_SIZE is too small for the traffic, or - /// Receive() isn't called often enough. - uint32_t GetRxOverflowCount() const { return m_rxOverflows.load(std::memory_order_relaxed); } - -private: - /// @brief Read a byte from the Ring Buffer, sleeping on the RX semaphore - /// while it's empty. - /// @param timeout Most to wait for each wake-up (portMAX_DELAY = forever). - /// @return false if no byte arrived within the timeout. - bool ReadByte(uint8_t& out, TickType_t timeout) { - while (true) { - if (m_ringBuffer.Get(out)) return true; - if (xSemaphoreTake(m_rxSemaphore, timeout) != pdTRUE) return false; - } - } - - UART_HandleTypeDef* m_huart; - SemaphoreHandle_t m_mutex = nullptr; // Mutex for Send() - SemaphoreHandle_t m_rxSemaphore = nullptr; // Semaphore for Receive() blocking - - uint8_t m_rxByte; // Temp byte for HAL ISR - UartRingBuffer m_ringBuffer; - std::atomic m_rxOverflows{ 0 }; - - static constexpr size_t BUFFER_SIZE = dmq::UART_MAX_PAYLOAD; - uint8_t m_tempRxBuffer[BUFFER_SIZE]; // Payload reassembly buffer - - ITransport* m_sendTransport; - ITransport* m_recvTransport; - ITransportMonitor* m_transportMonitor = nullptr; -}; - -} // namespace dmq::transport - -#endif // STM32_UART_TRANSPORT_H diff --git a/DelegateMQ/port/transport/win32-pipe/Win32PipeTransport.h b/DelegateMQ/port/transport/win32-pipe/Win32PipeTransport.h deleted file mode 100644 index f739ca6..0000000 --- a/DelegateMQ/port/transport/win32-pipe/Win32PipeTransport.h +++ /dev/null @@ -1,225 +0,0 @@ -#ifndef WIN32_PIPE_TRANSPORT_H -#define WIN32_PIPE_TRANSPORT_H - -/// @file -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// Transport callable argument data to/from a remote using Win32 data pipe. - -#if !defined(_WIN32) && !defined(_WIN64) - #error This code must be compiled as a Win32 or Win64 application. -#endif - -// Include Winsock for htons/ntohs consistency -#include -#pragma comment(lib, "ws2_32.lib") - -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief Win32 data pipe transport example. -class Win32PipeTransport : public ITransport -{ -public: - enum class Type - { - PUB, - SUB - }; - - Win32PipeTransport() = default; - - ~Win32PipeTransport() - { - Close(); - } - - int Create(Type type, LPCSTR pipeName) - { - const std::lock_guard lock(m_mutex); - m_type = type; - if (type == Type::PUB) - { - // Connect to an existing pipe (Client) - m_hPipe = CreateFile( - pipeName, // pipe name - GENERIC_READ | // read and write access - GENERIC_WRITE, - 0, // no sharing - NULL, // default security attributes - OPEN_EXISTING, // opens existing pipe - 0, // default attributes - NULL); // no template file - - // A client handle opens in byte-read, blocking mode. Match the server's - // message-read, non-blocking mode so a duplex client can Receive(): one - // ReadFile returns exactly one message, and an idle read doesn't block - // (while holding m_mutex) a concurrent Send(). - if (m_hPipe != INVALID_HANDLE_VALUE) - { - DWORD mode = PIPE_READMODE_MESSAGE | PIPE_NOWAIT; - if (!SetNamedPipeHandleState(m_hPipe, &mode, NULL, NULL)) - { - CloseHandle(m_hPipe); - m_hPipe = INVALID_HANDLE_VALUE; - } - } - } - else if (type == Type::SUB) - { - // Create named pipe (Server) - m_hPipe = CreateNamedPipe( - pipeName, // pipe name - PIPE_ACCESS_DUPLEX, // read/write access - PIPE_TYPE_MESSAGE | // message type pipe - PIPE_READMODE_MESSAGE | // message-read mode - PIPE_NOWAIT, // non-blocking mode - PIPE_UNLIMITED_INSTANCES, // max. instances - BUFFER_SIZE, // output buffer size - BUFFER_SIZE, // input buffer size - 0, // client time-out - NULL); // default security attribute - } - - if (m_hPipe == INVALID_HANDLE_VALUE) - { - // DWORD dwError = GetLastError(); - // std::cout << "Create pipe failed: " << dwError << std::endl; - return -1; - } - return 0; - } - - void Close() - { - const std::lock_guard lock(m_mutex); - if (m_hPipe != INVALID_HANDLE_VALUE) - { - // DisconnectNamedPipe is a server (SUB) only API; skip for client (PUB) - if (m_type == Type::SUB) - DisconnectNamedPipe(m_hPipe); - CloseHandle(m_hPipe); - m_hPipe = INVALID_HANDLE_VALUE; - } - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - const std::lock_guard lock(m_mutex); - // Named pipes on Windows use different mechanisms for timeouts - // than sockets (e.g. SetCommTimeouts for serial or ReadFile with OVERLAPPED). - // Since this transport currently uses PIPE_NOWAIT, we'll just store it. - m_recvTimeout = timeout; - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - const std::lock_guard lock(m_mutex); - if (os.bad() || os.fail()) - return -1; - - if (m_hPipe == INVALID_HANDLE_VALUE) return -1; - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - std::cerr << "Error: Payload too large for static buffer." << std::endl; - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - // Copy payload after header - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - DWORD totalSize = static_cast(DmqHeader::HEADER_SIZE + payloadLen); - DWORD sentLen = 0; - BOOL success = WriteFile(m_hPipe, m_sendBuffer, totalSize, &sentLen, NULL); - - if (!success || sentLen != totalSize) - return -1; - - return 0; - } - - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override - { - const std::lock_guard lock(m_mutex); - if (m_hPipe == INVALID_HANDLE_VALUE) return -1; - - // Check/Accept connection (server only; ConnectNamedPipe is a server API) - // Note: In non-blocking mode (PIPE_NOWAIT), this returns false immediately - // if connected, or error if already connected. - if (m_type == Type::SUB) - { - BOOL connected = ConnectNamedPipe(m_hPipe, NULL) ? - TRUE : (GetLastError() == ERROR_PIPE_CONNECTED); - - // If not connected yet, we can't read. - if (connected == FALSE && GetLastError() == ERROR_NO_DATA) { - return RECEIVE_NO_DATA; - } - } - - DWORD size = 0; - BOOL success = ReadFile(m_hPipe, m_buffer, BUFFER_SIZE, &size, NULL); - - if (success == FALSE) { - // PIPE_NOWAIT: no message waiting, or no client connected yet. - const DWORD err = GetLastError(); - if (err == ERROR_NO_DATA || err == ERROR_PIPE_LISTENING) - return RECEIVE_NO_DATA; - return -1; // includes ERROR_MORE_DATA: message larger than the buffer - } - if (size < DmqHeader::HEADER_SIZE) - return -1; - - // 1. Read Header directly from m_buffer (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) { - return -1; - } - - // 2. Write payload to provided stream. Message-mode pipe: one message - // per read, so the header length must match exactly. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != size - DmqHeader::HEADER_SIZE) - return -1; - - if (payloadSize > 0) { - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - return 0; - } - -private: - // Increase buffer to Max Packet Size (64KB) to avoid truncation - static const int BUFFER_SIZE = 65536; - char m_buffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - - Type m_type = Type::PUB; - HANDLE m_hPipe = INVALID_HANDLE_VALUE; - std::chrono::milliseconds m_recvTimeout = std::chrono::milliseconds(2000); - dmq::RecursiveMutex m_mutex; -}; - -} // namespace dmq::transport - -#endif diff --git a/DelegateMQ/port/transport/win32-tcp/Win32TcpTransport.h b/DelegateMQ/port/transport/win32-tcp/Win32TcpTransport.h deleted file mode 100644 index 12dc55c..0000000 --- a/DelegateMQ/port/transport/win32-tcp/Win32TcpTransport.h +++ /dev/null @@ -1,398 +0,0 @@ -#ifndef WIN32_TCP_TRANSPORT_H -#define WIN32_TCP_TRANSPORT_H - -/// @file Win32TcpTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Win32 TCP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using Windows Sockets (Winsock2). -/// It supports both CLIENT and SERVER modes for transmitting serialized delegate data. -/// In SERVER mode, it supports multiple simultaneous client connections and broadcasts -/// outgoing messages to all connected participants. -/// -/// Key Features: -/// 1. **Direct I/O**: Executes socket operations directly on the calling thread, -/// relying on OS-level thread safety to avoid deadlocks. -/// 2. **Reliability Support**: Integrates with `TransportMonitor` to track sequence -/// numbers and acknowledge (ACK) receipts. -/// 3. **Non-Blocking I/O**: Utilizes `select()` in the receive loop to prevent -/// thread blocking when no data is available, facilitating clean shutdowns. -/// 4. **Multi-Client Multiplexing**: SERVER mode manages a list of clients and -/// polls them for data using `select()`. -/// 5. **Socket Management**: Use WinsockConnect class in main() for `WSAStartup` and -/// socket creation/cleanup. - -#if !defined(_WIN32) && !defined(_WIN64) -#error This code must be compiled as a Win32 or Win64 application. -#endif - -#include -#include -#pragma comment(lib, "ws2_32.lib") - -#include "port/transport/common/ITransport.h" -#include "port/transport/common/ITransportMonitor.h" -#include "port/transport/common/DmqHeader.h" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief A TCP transport implementation for Win32 using Winsock. -class Win32TcpTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type - { - SERVER, - CLIENT - }; - - Win32TcpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~Win32TcpTransport() - { - Close(); - } - - /// @brief Create a TCP transport. - /// @param type SERVER or CLIENT. - /// @param addr The IP address string. - /// @param port The TCP port. - /// @return 0 on success, -1 on failure. - int Create(Type type, LPCSTR addr, USHORT port) - { - Close(); // a second Create() replaces the sockets instead of leaking them - m_type = type; - sockaddr_in service; - service.sin_family = AF_INET; - service.sin_port = htons(port); - inet_pton(AF_INET, addr, &service.sin_addr); - - if (type == Type::SERVER) - { - m_listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (m_listenSocket == INVALID_SOCKET) return -1; - - // Allow address reuse to facilitate quick restarts during development - int opt = 1; - setsockopt(m_listenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt)); - - if (bind(m_listenSocket, (SOCKADDR*)&service, sizeof(service)) == SOCKET_ERROR) - { - std::cerr << "Win32TcpTransport: Bind failed: " << WSAGetLastError() << std::endl; - Close(); - return -1; - } - - if (listen(m_listenSocket, SOMAXCONN) == SOCKET_ERROR) { - std::cerr << "Win32TcpTransport: Listen failed." << std::endl; - Close(); - return -1; - } - std::cout << "Win32TcpTransport: Server listening on " << port << "..." << std::endl; - } - else if (type == Type::CLIENT) - { - m_clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (connect(m_clientSocket, (SOCKADDR*)&service, sizeof(service)) == SOCKET_ERROR) - { - // Silent fail for clients to support polling/retries in application layer - closesocket(m_clientSocket); - m_clientSocket = INVALID_SOCKET; - return -1; - } - std::cout << "Win32TcpTransport: Client connected to " << addr << ":" << port << std::endl; - - DWORD timeout = 2000; - setsockopt(m_clientSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); - } - - return 0; - } - - /// @brief Close all sockets and clean up. - void Close() - { - // m_mutex: Receive() may close the client socket on another thread - const std::lock_guard lock(m_mutex); - - // Close Client Socket - if (m_clientSocket != INVALID_SOCKET) { - shutdown(m_clientSocket, SD_BOTH); - closesocket(m_clientSocket); - m_clientSocket = INVALID_SOCKET; - } - - // Close all server-accepted clients - { - for (auto s : m_serverClients) { - shutdown(s, SD_BOTH); - closesocket(s); - } - m_serverClients.clear(); - } - - // Close Listen Socket - if (m_listenSocket != INVALID_SOCKET) { - closesocket(m_listenSocket); - m_listenSocket = INVALID_SOCKET; - } - } - - /// @brief Set the receive timeout for all active sockets. - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - m_recvTimeoutMs = static_cast(timeout.count()); - if (m_clientSocket != INVALID_SOCKET) - { - setsockopt(m_clientSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&m_recvTimeoutMs, sizeof(m_recvTimeoutMs)); - } - - const std::lock_guard lock(m_mutex); - for (auto s : m_serverClients) { - setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&m_recvTimeoutMs, sizeof(m_recvTimeoutMs)); - } - } - - /// @brief Send data over the TCP link. - /// @details In SERVER mode, this broadcasts to all connected clients. - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - // m_mutex guards m_sendBuffer and keeps frames from different threads - // (including ACKs sent by Receive()) from interleaving on the stream. - const std::lock_guard lock(m_mutex); - if (m_type == Type::CLIENT) { - return SendToSocket(m_clientSocket, os, header); - } else { - int lastErr = 0; - for (auto s : m_serverClients) { - if (SendToSocket(s, os, header) != 0) lastErr = -1; - } - return lastErr; - } - } - - /// @brief Receive data from the TCP link. - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override - { - if (m_type == Type::SERVER) { - return ReceiveServer(is, header); - } else { - if (m_clientSocket == INVALID_SOCKET) { - // The connection was dropped (see below). Wait out one receive - // timeout before reporting it again, so a caller polling in a - // tight loop (RemoteDispatcher's receive thread) doesn't spin. - std::this_thread::sleep_for(std::chrono::milliseconds(m_recvTimeoutMs)); - return -1; - } - int result = ReceiveSocket(m_clientSocket, is, header); - if (result == -2) { - // Disconnected, or the stream lost framing (bad header, partial - // frame). Either way nothing more on it can be trusted. Close it: - // a shut-down but still open socket stays readable at EOF, so the - // next select() would return at once and the caller would spin. - const std::lock_guard lock(m_mutex); - if (m_clientSocket != INVALID_SOCKET) { - shutdown(m_clientSocket, SD_BOTH); - closesocket(m_clientSocket); - m_clientSocket = INVALID_SOCKET; - } - } - return result; - } - } - - void SetTransportMonitor(ITransportMonitor* tm) { m_transportMonitor = tm; } - void SetSendTransport(ITransport* st) { m_sendTransport = st; } - void SetRecvTransport(ITransport* rt) { m_recvTransport = rt; } - -private: - /// @brief Internal helper to send to a specific socket. - int SendToSocket(SOCKET s, dmq::xostringstream& os, const DmqHeader& header) { - if (s == INVALID_SOCKET) return -1; - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - std::cerr << "Error: Payload too large for static buffer." << std::endl; - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - // Copy payload after header - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - int totalSize = DmqHeader::HEADER_SIZE + payloadLen; - const char* ptr = m_sendBuffer; - int remaining = totalSize; - - while (remaining > 0) - { - int sent = send(s, ptr, remaining, 0); - if (sent == SOCKET_ERROR) return -1; - ptr += sent; - remaining -= sent; - } - - return 0; - } - - /// @brief Internal helper to handle server-side multiplexing. - int ReceiveServer(dmq::xstringstream& is, DmqHeader& header) { - // 1. Lazy Accept: Check for new client connections - TIMEVAL tv = { 0, 1000 }; // 1ms poll - fd_set fds; - FD_ZERO(&fds); - FD_SET(m_listenSocket, &fds); - - if (select(0, &fds, NULL, NULL, &tv) > 0) { - SOCKET client = accept(m_listenSocket, NULL, NULL); - if (client != INVALID_SOCKET) { - std::cout << "Win32TcpTransport: Accepted client connection." << std::endl; - setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, (const char*)&m_recvTimeoutMs, sizeof(m_recvTimeoutMs)); - const std::lock_guard lock(m_mutex); - m_serverClients.push_back(client); - } - } - - // 2. Poll all connected clients for data - fd_set readfds; - FD_ZERO(&readfds); - { - const std::lock_guard lock(m_mutex); - if (m_serverClients.empty()) return RECEIVE_NO_DATA; - for (auto s : m_serverClients) { - FD_SET(s, &readfds); - } - } - - tv.tv_usec = 1000; // 1ms poll - if (select(0, &readfds, NULL, NULL, &tv) > 0) { - const std::lock_guard lock(m_mutex); - for (auto it = m_serverClients.begin(); it != m_serverClients.end(); ) { - if (FD_ISSET(*it, &readfds)) { - int result = ReceiveSocket(*it, is, header); - if (result == -2) { // Disconnected, or lost framing (bad header) - std::cout << "Win32TcpTransport: Client disconnected." << std::endl; - closesocket(*it); - it = m_serverClients.erase(it); - continue; - } - return result; - } - ++it; - } - } - return RECEIVE_NO_DATA; - } - - /// @brief Internal helper to read from a specific socket and parse DMQ protocol. - int ReceiveSocket(SOCKET s, dmq::xstringstream& is, DmqHeader& header) { - if (s == INVALID_SOCKET) return -1; - - // Poll check to prevent blocking if no data is waiting - fd_set readfds; - FD_ZERO(&readfds); - FD_SET(s, &readfds); - TIMEVAL tv = { 0, 1000 }; - int ready = select(0, &readfds, NULL, NULL, &tv); - if (ready == 0) return RECEIVE_NO_DATA; - if (ready < 0) return -1; - - // 1. Read Header - char headerBuf[DmqHeader::HEADER_SIZE]; - if (!ReadExact(s, headerBuf, DmqHeader::HEADER_SIZE)) return -2; // Disconnected - - // Parse Header (Convert Network -> Host) - header.Decode(headerBuf); - - // A stream has no resync point: after a bad header (or a payload we - // can't hold and so can't skip), the next bytes aren't a header either. - // Report it like a disconnect (-2) so the connection is dropped. - if (!header.IsValid()) return -2; - - // 2. Read Payload - uint16_t payloadSize = header.GetLength(); - if (payloadSize > 0) - { - if (payloadSize > BUFFER_SIZE) return -2; - if (!ReadExact(s, m_recvBuffer, payloadSize)) return -2; - is.write(m_recvBuffer, payloadSize); - } - - // 3. Handle Acknowledgment - if (header.GetId() == dmq::ACK_REMOTE_ID) { - if (m_transportMonitor) m_transportMonitor->Remove(header.GetSeqNum()); - } - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - else if (m_sendTransport) { - // Send ACK using a small stack buffer - DmqHeader ack(dmq::ACK_REMOTE_ID, header.GetSeqNum()); - char ackBuf[DmqHeader::HEADER_SIZE]; - ack.Encode(ackBuf); - - const std::lock_guard lock(m_mutex); // don't interleave with Send() - const char* ptr = ackBuf; - int remaining = static_cast(DmqHeader::HEADER_SIZE); - while (remaining > 0) { - int sent = send(s, ptr, remaining, 0); - if (sent == SOCKET_ERROR || sent == 0) break; - ptr += sent; - remaining -= sent; - } - } - return 0; - } - - /// @brief Read exactly 'size' bytes from the socket. - bool ReadExact(SOCKET s, char* dest, int size) - { - int total = 0; - while (total < size) { - int r = recv(s, dest + total, size - total, 0); - if (r <= 0) return false; - total += r; - } - return true; - } - - SOCKET m_listenSocket = INVALID_SOCKET; - SOCKET m_clientSocket = INVALID_SOCKET; - std::vector m_serverClients; - static const int BUFFER_SIZE = 4096; - char m_recvBuffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - DWORD m_recvTimeoutMs = 2000; - Type m_type = Type::SERVER; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - dmq::RecursiveMutex m_mutex; -}; - -} // namespace dmq::transport - -#endif diff --git a/DelegateMQ/port/transport/win32-udp/MulticastTransport.h b/DelegateMQ/port/transport/win32-udp/MulticastTransport.h deleted file mode 100644 index 15a81b4..0000000 --- a/DelegateMQ/port/transport/win32-udp/MulticastTransport.h +++ /dev/null @@ -1,148 +0,0 @@ -#ifndef WIN32_MULTICAST_TRANSPORT_H -#define WIN32_MULTICAST_TRANSPORT_H - -#if !defined(_WIN32) && !defined(_WIN64) -#error This code must be compiled as a Win32 or Win64 application. -#endif - -#include -#include -#pragma comment(lib, "ws2_32.lib") - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include -#include -#include -#include - -namespace dmq::transport { - -class MulticastTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type { PUB, SUB }; - - MulticastTransport() = default; - ~MulticastTransport() { Close(); } - - int Create(Type type, LPCSTR groupAddr, USHORT port, LPCSTR localInterface = "0.0.0.0") - { - dmq::LockGuard lock(m_mutex); - m_type = type; - m_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (m_socket == INVALID_SOCKET) return -1; - - int reuse = 1; - setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)); - - int loop = 1; - setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_LOOP, (const char*)&loop, sizeof(loop)); - - if (type == Type::PUB) { - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); - inet_pton(AF_INET, groupAddr, &m_addr.sin_addr); - - // Disable loopback so we don't receive our own packets - loop = 0; - setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_LOOP, (const char*)&loop, sizeof(loop)); - - in_addr localAddr; - inet_pton(AF_INET, localInterface, &localAddr); - setsockopt(m_socket, IPPROTO_IP, IP_MULTICAST_IF, (const char*)&localAddr, sizeof(localAddr)); - - std::cout << "[Multicast] Created PUB on " << localInterface << ", Group: " << groupAddr << ":" << port << std::endl; - } - else { - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); - m_addr.sin_addr.s_addr = INADDR_ANY; - - if (::bind(m_socket, (sockaddr*)&m_addr, sizeof(m_addr)) == SOCKET_ERROR) { Close(); return -1; } - - ip_mreq mreq; - inet_pton(AF_INET, groupAddr, &mreq.imr_multiaddr); - inet_pton(AF_INET, localInterface, &mreq.imr_interface); - if (setsockopt(m_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*)&mreq, sizeof(mreq)) == SOCKET_ERROR) { - std::cerr << "[Multicast] Join Failed: " << WSAGetLastError() << std::endl; - Close(); return -1; - } - - DWORD timeout = 1000; - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); - std::cout << "[Multicast] Created SUB on " << localInterface << ", Group: " << groupAddr << ":" << port << std::endl; - } - return 0; - } - - void Close() { - dmq::LockGuard lock(m_mutex); - if (m_socket != INVALID_SOCKET) { - closesocket(m_socket); - m_socket = INVALID_SOCKET; - } - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override { - dmq::LockGuard lock(m_mutex); - if (m_type != Type::PUB) return -1; - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) return -1; - DmqHeader headerCopy = header; - headerCopy.SetLength(static_cast(payload.length())); - - dmq::xostringstream ss(std::ios::in | std::ios::out | std::ios::binary); - char headerBuf[DmqHeader::HEADER_SIZE]; - headerCopy.Encode(headerBuf); - ss.write(headerBuf, DmqHeader::HEADER_SIZE); - ss.write(payload.data(), payload.size()); - - auto fullData = ss.str(); - int err = sendto(m_socket, fullData.data(), (int)fullData.length(), 0, (sockaddr*)&m_addr, sizeof(m_addr)); - - if (err != SOCKET_ERROR) { - // std::cout << "[Multicast] Sent " << fullData.length() << " bytes" << std::endl; - return 0; - } - return -1; - } - - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override { - dmq::LockGuard lock(m_mutex); - if (m_type != Type::SUB) return -1; - int addrLen = sizeof(m_addr); - int size = recvfrom(m_socket, m_buffer, sizeof(m_buffer), 0, (sockaddr*)&m_addr, &addrLen); - - if (size == SOCKET_ERROR) { - const int err = WSAGetLastError(); - // WSAEMSGSIZE (datagram larger than the buffer) stays an error - return (err == WSAETIMEDOUT || err == WSAEWOULDBLOCK) ? RECEIVE_NO_DATA : -1; - } - if (size < (int)DmqHeader::HEADER_SIZE) return -1; - - header.Decode(m_buffer); - - if (!header.IsValid()) return -1; - - // One datagram is one message: the header length must match exactly. - int payloadSize = size - static_cast(DmqHeader::HEADER_SIZE); - if (header.GetLength() != payloadSize) return -1; - is.write(m_buffer + DmqHeader::HEADER_SIZE, header.GetLength()); - return 0; - } - -private: - SOCKET m_socket = INVALID_SOCKET; - sockaddr_in m_addr{}; - Type m_type = Type::PUB; - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; -}; - -} // namespace dmq::transport - -#endif diff --git a/DelegateMQ/port/transport/win32-udp/Win32UdpTransport.h b/DelegateMQ/port/transport/win32-udp/Win32UdpTransport.h deleted file mode 100644 index bd2b1ae..0000000 --- a/DelegateMQ/port/transport/win32-udp/Win32UdpTransport.h +++ /dev/null @@ -1,312 +0,0 @@ -#ifndef WIN32_UDP_TRANSPORT_H -#define WIN32_UDP_TRANSPORT_H - -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief Win32 UDP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using Windows Sockets (Winsock2) -/// for connectionless UDP communication. It supports two modes: PUB (Publisher/Sender) -/// and SUB (Subscriber/Receiver). -/// -/// Key Features: -/// 1. **Message Oriented**: Transmits discrete packets containing serialized delegate -/// arguments and framing headers. -/// 2. **Reliability Support**: Integrates with `TransportMonitor` to track outgoing -/// sequence numbers and process incoming ACKs to detect packet loss. -/// 3. **Socket Management**: Use WinsockConnect class in main() for `WSAStartup` and -/// socket creation/cleanup. -/// -/// @note This implementation uses blocking sockets with timeouts (`SO_RCVTIMEO`) to -/// prevent indefinite blocking during receive operations. - -#if !defined(_WIN32) && !defined(_WIN64) -#error This code must be compiled as a Win32 or Win64 application. -#endif - -#include -#include -#pragma comment(lib, "ws2_32.lib") // Link with Winsock library - -#include "port/transport/common/ITransport.h" -#include "port/transport/common/ITransportMonitor.h" -#include "port/transport/common/DmqHeader.h" -#include -#include -#include -#include - -namespace dmq::transport { - -/// @brief Win32 UDP transport example. -class Win32UdpTransport : public ITransport -{ - XALLOCATOR -public: - enum class Type - { - PUB, - SUB - }; - - Win32UdpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~Win32UdpTransport() - { - Close(); - } - - int Create(Type type, LPCSTR addr, USHORT port) - { - const std::lock_guard recvLock(m_recvMutex); - const std::lock_guard lock(m_mutex); - Close(); // a second Create() replaces the socket instead of leaking it - m_type = type; - - // Create a UDP socket - m_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (m_socket == INVALID_SOCKET) - { - std::cerr << "Socket creation failed." << std::endl; - return -1; - } - - if (type == Type::PUB) - { - // Set up the server address structure - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); // Convert port to network byte order - - // Convert IP address string to binary form - if (inet_pton(AF_INET, addr, &m_addr.sin_addr) != 1) - { - std::cerr << "Invalid IP address format: " << addr << std::endl; - Close(); - return -1; - } - - DWORD timeout = 2; - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); - } - else if (type == Type::SUB) - { - // Set up the server address structure - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); // Convert port to network byte order - m_addr.sin_addr.s_addr = INADDR_ANY; // Bind to all available interfaces - - // Bind the socket to the address and port - int err = ::bind(m_socket, (sockaddr*)&m_addr, sizeof(m_addr)); - if (err == SOCKET_ERROR) - { - int wsaErr = WSAGetLastError(); - std::cerr << "Win32UdpTransport: Bind failed on port " << port << ". Error: " << wsaErr << std::endl; - Close(); - return -1; - } - - // Set a 2-second receive timeout - DWORD timeout = 2000; // 2000 milliseconds = 2 seconds - err = setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); - if (err == SOCKET_ERROR) - { - std::cerr << "setsockopt(SO_RCVTIMEO) failed: " << WSAGetLastError() << std::endl; - Close(); - return -1; - } - } - - return 0; - } - - /// @details Waits for a Receive() in progress on another thread to return - /// (at most its receive timeout) before closing, so the socket is never - /// closed under it. - void Close() - { - const std::lock_guard recvLock(m_recvMutex); - const std::lock_guard lock(m_mutex); - if (m_socket != INVALID_SOCKET) - { - closesocket(m_socket); - m_socket = INVALID_SOCKET; - } - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - const std::lock_guard lock(m_mutex); - if (m_socket != INVALID_SOCKET) - { - DWORD ms = static_cast(timeout.count()); - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&ms, sizeof(ms)); - } - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - const std::lock_guard lock(m_mutex); - if (os.bad() || os.fail()) { - std::cout << "Error: xostringstream is in a bad state!" << std::endl; - return -1; - } - - if (m_type == Type::SUB && header.GetId() != dmq::ACK_REMOTE_ID) { - std::cout << "Error: Cannot send (non-ACK) on SUB socket!" << std::endl; - return -1; - } - - if (m_sendTransport != this) { - std::cout << "Error: This transport used for receive only!" << std::endl; - return -1; - } - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - std::cerr << "Error: Payload too large for static buffer." << std::endl; - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - // Copy payload after header - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - int totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - int err = sendto(m_socket, m_sendBuffer, totalSize, 0, (sockaddr*)&m_addr, sizeof(m_addr)); - - if (err == SOCKET_ERROR) { - std::cerr << "Win32UdpTransport: ERROR - sendto failed with " << WSAGetLastError() << std::endl; - } - - return (err == SOCKET_ERROR) ? -1 : 0; - } - - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override - { - // m_recvMutex, not m_mutex: a Send() on another thread (e.g. a PUB socket - // that also drains its ACKs here) isn't held up for the receive timeout. - const std::lock_guard recvLock(m_recvMutex); - if (m_recvTransport != this) { - std::cout << "Error: This transport used for send only!" << std::endl; - return -1; - } - if (m_socket == INVALID_SOCKET) - return -1; - - sockaddr_in fromAddr{}; - int addrLen = sizeof(fromAddr); - int size = recvfrom(m_socket, m_buffer, sizeof(m_buffer), 0, (sockaddr*)&fromAddr, &addrLen); - if (size == SOCKET_ERROR) - { - const int err = WSAGetLastError(); - if (err == WSAETIMEDOUT || err == WSAEWOULDBLOCK) - return RECEIVE_NO_DATA; - return -1; // includes WSAEMSGSIZE: datagram larger than the buffer - } - if (size < static_cast(DmqHeader::HEADER_SIZE)) - { - return -1; - } - - // 1. Read Header directly from m_buffer (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) { - return -1; - } - - // 2. Write payload to provided stream. One datagram is one message, so - // the header length must match exactly; anything else is malformed and - // must not be delivered or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != static_cast(size) - DmqHeader::HEADER_SIZE) - return -1; - - // A SUB replies to whoever sent the last valid message. Updated only - // now, after validation: a failed or stray read must not change it. - if (m_type == Type::SUB) - { - const std::lock_guard lock(m_mutex); - m_addr = fromAddr; - } - - if (payloadSize > 0) { - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - // 3. Handle Acknowledgment - if (header.GetId() == dmq::ACK_REMOTE_ID) - { - if (m_transportMonitor) - m_transportMonitor->Remove(header.GetSeqNum()); - } - else if (m_sendTransport && m_type == Type::SUB) - { - // Send ACK using a small stack buffer to avoid any heap - DmqHeader ack(dmq::ACK_REMOTE_ID, header.GetSeqNum()); - char ackBuf[DmqHeader::HEADER_SIZE]; - ack.Encode(ackBuf); - - sockaddr_in targetAddr = (m_type == Type::SUB) ? fromAddr : m_addr; - sendto(m_socket, ackBuf, static_cast(DmqHeader::HEADER_SIZE), 0, (sockaddr*)&targetAddr, sizeof(targetAddr)); - } - - return 0; - } - - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - void SetSendTransport(ITransport* sendTransport) - { - m_sendTransport = sendTransport; - } - - void SetRecvTransport(ITransport* recvTransport) - { - m_recvTransport = recvTransport; - } - - -private: - SOCKET m_socket = INVALID_SOCKET; - sockaddr_in m_addr{}; - - Type m_type = Type::PUB; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - /// @note UDP datagrams larger than the network MTU (typically 1500 bytes) will be - /// fragmented by the IP layer. If any fragment is lost, the entire message is - /// discarded. For maximum reliability, keep serialized messages under 1400 bytes. - /// Messages exceeding BUFFER_SIZE will be truncated and discarded by the OS. - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; ///< Socket open/close and Send() state (m_addr) - dmq::RecursiveMutex m_recvMutex; ///< Held by Receive(); taken before m_mutex -}; - -using UdpTransport = Win32UdpTransport; - -} // namespace dmq::transport - - -#endif \ No newline at end of file diff --git a/DelegateMQ/port/transport/zephyr-udp/ZephyrUdpTransport.h b/DelegateMQ/port/transport/zephyr-udp/ZephyrUdpTransport.h deleted file mode 100644 index b56e4a0..0000000 --- a/DelegateMQ/port/transport/zephyr-udp/ZephyrUdpTransport.h +++ /dev/null @@ -1,338 +0,0 @@ -#ifndef ZEPHYR_UDP_TRANSPORT_H -#define ZEPHYR_UDP_TRANSPORT_H - -/// @file ZephyrUdpTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2026. -/// -/// @brief Zephyr RTOS UDP transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the Zephyr Networking Subsystem -/// (BSD Socket API). It is designed for embedded targets running Zephyr RTOS. -/// -/// **Prerequisites:** -/// * Enable BSD Sockets: `CONFIG_NET_SOCKETS=y` -/// * Enable IPv4: `CONFIG_NET_IPV4=y` -/// * A network interface: on `native_sim` the loopback interface -/// (`CONFIG_NET_LOOPBACK=y`, needs `CONFIG_NET_DRIVERS=y`) is enough for -/// same-process testing with no host-side setup -- see -/// `example/sample-projects/zephyr-udp-serializer/prj.conf`. A real -/// target instead needs its actual link-layer driver (Ethernet, Wi-Fi, etc.). -/// -/// This file calls the `zsock_*`-prefixed socket functions (`zsock_socket()`, -/// `zsock_bind()`, `zsock_sendto()`, etc.) rather than the unprefixed BSD -/// names. Getting the unprefixed names requires `CONFIG_POSIX_API=y`, which -/// replaces large parts of the standard header set (``, -/// pthread types, ...) with Zephyr's own POSIX compatibility layer -- -/// something that collides with the *host's* C++ standard library headers -/// when building for `native_sim` (which links against the host's real -/// libstdc++), and is unnecessary weight on a real target that has no such -/// conflict. `CONFIG_NET_SOCKETS_POSIX_NAMES`, an older, narrower way to get -/// just the unprefixed socket names without the rest of `CONFIG_POSIX_API`, -/// was deprecated in Zephyr 3.7 and removed -- `zsock_*` is the current, -/// portable choice regardless of target. -/// -/// **Key Features:** -/// 1. **Direct Execution**: Executes network operations directly on the calling thread, -/// avoiding context switch overhead and preventing deadlocks. -/// 2. **Zero-Copy Friendly**: Uses the standard BSD API which Zephyr optimizes internally. -/// 3. **Reliability**: Fully integrated with `TransportMonitor` for ACKs/Retries. -/// 4. **Endianness**: Uses `htons`/`ntohs` for standard network byte order compatibility. - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" - -#include -#include - -#include -#include -#include -#include - -namespace dmq::transport { - -class ZephyrUdpTransport : public ITransport -{ -public: - enum class Type - { - PUB, - SUB - }; - - ZephyrUdpTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~ZephyrUdpTransport() - { - Close(); - } - - int Create(Type type, const char* addr, uint16_t port) - { - const dmq::LockGuard recvLock(m_recvMutex); - const dmq::LockGuard lock(m_mutex); - Close(); // a second Create() replaces the socket instead of leaking it - m_type = type; - - // Create UDP socket. zsock_* (not the bare BSD names) so this - // compiles without CONFIG_POSIX_API -- see the class doc comment. - m_socket = zsock_socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (m_socket < 0) - { - // printk("Socket creation failed: %d\n", errno); - return -1; - } - - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons(port); - - if (type == Type::PUB) - { - if (zsock_inet_pton(AF_INET, addr, &m_addr.sin_addr) != 1) - { - // printk("Invalid IP address format.\n"); - Close(); - return -1; - } - - // Short timeout so polling this socket for ACKs doesn't hang. - struct timeval timeout = ToTimeval(dmq::UDP_PUB_RECV_TIMEOUT); - - if (zsock_setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) - { - // printk("setsockopt(SO_RCVTIMEO) failed\n"); - Close(); - return -1; - } - } - else if (type == Type::SUB) - { - m_addr.sin_addr.s_addr = INADDR_ANY; - - if (zsock_bind(m_socket, (struct sockaddr*)&m_addr, sizeof(m_addr)) < 0) - { - // printk("Bind failed: %d\n", errno); - Close(); - return -1; - } - - // Receive timeout, so the receive thread can check for exit - struct timeval timeout = ToTimeval(dmq::UDP_SUB_RECV_TIMEOUT); - - if (zsock_setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) - { - // printk("setsockopt(SO_RCVTIMEO) failed\n"); - Close(); - return -1; - } - } - - return 0; - } - - /// @details Waits for a Receive() in progress on another thread to return - /// (at most its receive timeout) before closing, so the socket is never - /// closed under it. - void Close() - { - const dmq::LockGuard recvLock(m_recvMutex); - const dmq::LockGuard lock(m_mutex); - if (m_socket >= 0) - { - // Receive() has returned (m_recvMutex is held), so nothing is blocked on it - zsock_shutdown(m_socket, ZSOCK_SHUT_RDWR); - zsock_close(m_socket); - m_socket = -1; - } - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - const dmq::LockGuard lock(m_mutex); - if (m_socket >= 0) - { - struct timeval tv; - tv.tv_sec = timeout.count() / 1000; - tv.tv_usec = (timeout.count() % 1000) * 1000; - zsock_setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - } - } - - virtual int Send(xostringstream& os, const DmqHeader& header) override - { - const dmq::LockGuard lock(m_mutex); - if (os.bad() || os.fail() || m_socket < 0) { - return -1; - } - - // Allow ACKs on SUB sockets. Block only regular data. - if (m_type == Type::SUB && header.GetId() != dmq::ACK_REMOTE_ID) { - return -1; - } - - if (m_sendTransport != this) { - return -1; - } - - // Get payload and set length on the copy - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Convert to Network Byte Order (Big Endian) - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - ssize_t sent = zsock_sendto(m_socket, m_sendBuffer, totalSize, 0, - (struct sockaddr*)&m_addr, sizeof(m_addr)); - if (sent != (ssize_t)totalSize) return -1; - - return 0; - } - - virtual int Receive(xstringstream& is, DmqHeader& header) override - { - // m_recvMutex, not m_mutex: a Send() on another thread (e.g. a PUB socket - // that also drains its ACKs here) isn't held up for the receive timeout. - const dmq::LockGuard recvLock(m_recvMutex); - if (m_recvTransport != this || m_socket < 0) { - return -1; - } - - sockaddr_in fromAddr; - socklen_t addrLen = sizeof(fromAddr); - - ssize_t size = zsock_recvfrom(m_socket, m_buffer, sizeof(m_buffer), 0, - (struct sockaddr*)&fromAddr, &addrLen); - - if (size < 0) - { - // Zephyr uses standard errno values - if (errno == EWOULDBLOCK || errno == EAGAIN) - return RECEIVE_NO_DATA; - - return -1; - } - - if (static_cast(size) < DmqHeader::HEADER_SIZE) { - return -1; - } - - // 1. Read Header (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) - { - return -1; // Invalid marker - } - - // 2. Extract Payload. One datagram is one message, so the header length - // must match exactly; anything else (including a datagram cut short by - // the buffer) is malformed and must not be delivered or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != static_cast(size) - DmqHeader::HEADER_SIZE) - return -1; - - // Update m_addr to the sender's address so we can ACK back. Only after - // validation, and under m_mutex since Send() uses it. - if (m_type == Type::SUB) { - const dmq::LockGuard lock(m_mutex); - m_addr = fromAddr; - } - - if (payloadSize > 0) { - is.clear(); - is.str(""); - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - if (header.GetId() == dmq::ACK_REMOTE_ID) - { - if (m_transportMonitor) - m_transportMonitor->Remove(header.GetSeqNum()); - } - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - else if (m_sendTransport) - { - // Send ACK back using Send logic (recursive mutex handles it) - xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - ack.SetLength(0); - m_sendTransport->Send(ss_ack, ack); - } - - return 0; - } - - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - void SetSendTransport(ITransport* sendTransport) - { - m_sendTransport = sendTransport; - } - - void SetRecvTransport(ITransport* recvTransport) - { - m_recvTransport = recvTransport; - } - -private: - int m_socket = -1; - sockaddr_in m_addr{}; - Type m_type = Type::PUB; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - static struct timeval ToTimeval(std::chrono::milliseconds ms) - { - struct timeval tv; - tv.tv_sec = static_cast(ms.count() / 1000); - tv.tv_usec = static_cast((ms.count() % 1000) * 1000); - return tv; - } - - // Datagram buffer (header + payload): DMQ_UDP_BUFFER_SIZE, default the - // 1500-byte Ethernet MTU. - static constexpr size_t BUFFER_SIZE = dmq::UDP_BUFFER_SIZE; - char m_buffer[BUFFER_SIZE] = { 0 }; - char m_sendBuffer[BUFFER_SIZE] = { 0 }; - dmq::RecursiveMutex m_mutex; ///< Socket open/close and Send() state (m_addr) - dmq::RecursiveMutex m_recvMutex; ///< Held by Receive(); taken before m_mutex -}; - -/// @brief Backward-compatible name: application code (e.g. the sender.h/ -/// receiver.h pattern shared by every *-udp-serializer sample) references -/// dmq::transport::UdpTransport generically and stays portable across -/// whichever DMQ_TRANSPORT_* was selected at compile time, the same way -/// dmq::os::Thread works across DMQ_THREAD_* -- see LinuxUdpTransport.h/ -/// Win32UdpTransport.h for the other two ports that already do this. -using UdpTransport = ZephyrUdpTransport; - -} - -#endif // ZEPHYR_UDP_TRANSPORT_H \ No newline at end of file diff --git a/DelegateMQ/port/transport/zeromq/ZeroMqTransport.h b/DelegateMQ/port/transport/zeromq/ZeroMqTransport.h deleted file mode 100644 index 1f6079c..0000000 --- a/DelegateMQ/port/transport/zeromq/ZeroMqTransport.h +++ /dev/null @@ -1,344 +0,0 @@ -#ifndef ZEROMQ_TRANSPORT_H -#define ZEROMQ_TRANSPORT_H - -/// @file ZeroMqTransport.h -/// @see https://github.com/DelegateMQ/DelegateMQ -/// David Lafreniere, 2025. -/// -/// @brief ZeroMQ transport implementation for DelegateMQ. -/// -/// @details -/// This class implements the ITransport interface using the ZeroMQ high-performance -/// asynchronous messaging library. It supports multiple patterns including PAIR (1-to-1) -/// and PUB/SUB (1-to-many). -/// -/// Key Features: -/// 1. **Thread Safety**: Uses a `dmq::RecursiveMutex` to protect the ZeroMQ socket, -/// allowing safe concurrent access from the Send and Receive threads (ZeroMQ sockets -/// are not inherently thread-safe). -/// 2. **Flexible Patterns**: Supports both bidirectional (PAIR) and unidirectional (PUB/SUB) -/// communication topologies. -/// 3. **Non-Blocking**: Configures `ZMQ_RCVTIMEO` and `ZMQ_DONTWAIT` to ensure the -/// transport remains responsive and never blocks the application indefinitely. -/// 4. **Reliability**: Integrates with `TransportMonitor` to provide sequence tracking -/// and ACKs even over PUB/SUB (when a return channel is available). -/// -/// @note Requires the `libzmq` library. - -// Add Windows Sockets headers for htons/ntohs -#if defined(_WIN32) || defined(_WIN64) - #include - #pragma comment(lib, "ws2_32.lib") -#else - #include -#endif - -#include "delegate/DelegateOpt.h" -#include "port/transport/common/ITransport.h" -#include "port/transport/common/DmqHeader.h" -#include "port/transport/common/ITransportMonitor.h" -#include -#include -#include -#include -#include -#include -#include // For std::cout/cerr - -namespace dmq::transport { - -/// @brief ZeroMQ transport class. -/// @details Logic now executes directly on the caller's thread, protected by a mutex -/// to prevent concurrent access to the underlying ZeroMQ socket. -class ZeroMqTransport : public ITransport -{ -public: - enum class Type - { - PAIR_CLIENT, - PAIR_SERVER, - PUB, - SUB - }; - - ZeroMqTransport() : m_sendTransport(this), m_recvTransport(this) - { - } - - ~ZeroMqTransport() - { - Destroy(); - } - - int Create(Type type, const char* addr) - { - std::lock_guard lock(m_mutex); - - if (m_zmqContext == nullptr) { - m_zmqContext = zmq_ctx_new(); - } - - m_type = type; - - if (m_type == Type::PAIR_CLIENT) - { - // Create a PAIR socket and connect the client to the server address - m_zmq = zmq_socket(m_zmqContext, ZMQ_PAIR); - int rc = zmq_connect(m_zmq, addr); - if (rc != 0) { - // perror is less useful on Windows for ZMQ specific errors, but ok for console - perror("zmq_connect failed"); - zmq_close(m_zmq); - return 1; - } - - // Set the receive timeout to 100 milliseconds - int timeout = 100; // 100mS - zmq_setsockopt(m_zmq, ZMQ_RCVTIMEO, &timeout, sizeof(timeout)); - } - else if (m_type == Type::PAIR_SERVER) - { - // Create a PAIR socket and bind the server to an address - m_zmq = zmq_socket(m_zmqContext, ZMQ_PAIR); - int rc = zmq_bind(m_zmq, addr); - if (rc != 0) { - perror("zmq_bind failed"); - return 1; - } - - // Set the receive timeout to 100 milliseconds - int timeout = 100; // 100mS - zmq_setsockopt(m_zmq, ZMQ_RCVTIMEO, &timeout, sizeof(timeout)); - } - else if (m_type == Type::PUB) - { - // Create a PUB socket - m_zmq = zmq_socket(m_zmqContext, ZMQ_PUB); - int rc = zmq_bind(m_zmq, addr); - if (rc != 0) { - perror("zmq_bind failed"); - return 1; - } - } - else if (m_type == Type::SUB) - { - // Create a SUB socket - m_zmq = zmq_socket(m_zmqContext, ZMQ_SUB); - int rc = zmq_connect(m_zmq, addr); - if (rc != 0) { - perror("zmq_connect failed"); - zmq_close(m_zmq); - return 1; - } - - // Subscribe to all messages - zmq_setsockopt(m_zmq, ZMQ_SUBSCRIBE, "", 0); - - // Set the receive timeout to 100 milliseconds - int timeout = 100; // 100mS - zmq_setsockopt(m_zmq, ZMQ_RCVTIMEO, &timeout, sizeof(timeout)); - } - else - { - // Handle other types, if needed - perror("Invalid socket type"); - return 1; - } - return 0; - } - - void Close() - { - std::lock_guard lock(m_mutex); - - // Close the subscriber socket and context - if (m_zmq) { - // Linger 0 ensures close doesn't block waiting for unsent messages - int linger = 0; - zmq_setsockopt(m_zmq, ZMQ_LINGER, &linger, sizeof(linger)); - zmq_close(m_zmq); - m_zmq = nullptr; - } - } - - void SetRecvTimeout(std::chrono::milliseconds timeout) - { - std::lock_guard lock(m_mutex); - if (m_zmq) - { - int ms = static_cast(timeout.count()); - zmq_setsockopt(m_zmq, ZMQ_RCVTIMEO, &ms, sizeof(ms)); - } - } - - void Destroy() - { - Close(); - - // Context termination is thread-safe in ZMQ - if (m_zmqContext) { - zmq_ctx_term(m_zmqContext); - m_zmqContext = nullptr; - } - } - - virtual int Send(dmq::xostringstream& os, const DmqHeader& header) override - { - std::lock_guard lock(m_mutex); - - if (os.bad() || os.fail() || m_zmq == nullptr) { - return -1; - } - - if (m_type == Type::SUB) { - return -1; - } - - if (m_sendTransport != this) { - return -1; - } - - // Get payload data without string copy if possible - auto payload = os.str(); - if (payload.length() > (BUFFER_SIZE - DmqHeader::HEADER_SIZE)) { - return -1; - } - uint16_t payloadLen = static_cast(payload.length()); - - // Prepare header values in Network Byte Order - DmqHeader wireHeader = header; - wireHeader.SetLength(payloadLen); - wireHeader.Encode(m_sendBuffer); - - if (payloadLen > 0) { - memcpy(m_sendBuffer + DmqHeader::HEADER_SIZE, payload.data(), payloadLen); - } - - size_t totalSize = DmqHeader::HEADER_SIZE + payloadLen; - - // Send data using ZeroMQ - int err = zmq_send(m_zmq, m_sendBuffer, totalSize, ZMQ_DONTWAIT); - if (err == -1) - { - // EAGAIN is common if queue is full - return -1; - } - - return 0; - } - - virtual int Receive(dmq::xstringstream& is, DmqHeader& header) override - { - std::lock_guard lock(m_mutex); - - if (m_zmq == nullptr) { - return -1; - } - - if (m_type == Type::PUB) { - return -1; - } - - if (m_recvTransport != this) { - return -1; - } - - int size = zmq_recv(m_zmq, m_buffer, BUFFER_SIZE, 0); - if (size == -1) { - return (zmq_errno() == EAGAIN) ? RECEIVE_NO_DATA : -1; // EAGAIN: ZMQ_RCVTIMEO expired - } - - // zmq_recv() truncates a message longer than the buffer but returns its - // full length. Drop it: only BUFFER_SIZE bytes were stored. - if (size > BUFFER_SIZE) { - return -1; - } - - if (size < DmqHeader::HEADER_SIZE) { - return -1; - } - - // 1. Read Header (Network Byte Order) - header.Decode(m_buffer); - - if (!header.IsValid()) { - return -1; - } - - // 2. Write payload - // One message per ZeroMQ message: the header length must match exactly. Anything - // else is malformed and must not be delivered (cut short) or ACKed. - uint16_t payloadSize = header.GetLength(); - if (payloadSize != static_cast(size) - DmqHeader::HEADER_SIZE) - return -1; - - if (payloadSize > 0) { - is.clear(); - is.str(""); - is.write(m_buffer + DmqHeader::HEADER_SIZE, payloadSize); - } - - if (header.GetId() == dmq::ACK_REMOTE_ID) - { - // Receiver ack'ed message. Remove sequence number from monitor. - if (m_transportMonitor) - m_transportMonitor->Remove(header.GetSeqNum()); - } - else - { - // ACK whenever a send path exists, whether or not this transport also - // tracks its own sends: a receive-only transport (e.g. NetworkNode's SUB) - // has no monitor but must still ACK the sender's RELIABLE messages. - if (m_sendTransport) - { - // Send header with received seqNum as the ack message - dmq::xostringstream ss_ack; - DmqHeader ack; - ack.SetId(dmq::ACK_REMOTE_ID); - ack.SetSeqNum(header.GetSeqNum()); - - // Note: Recursive mutex allows Send() here - m_sendTransport->Send(ss_ack, ack); - } - } - - return 0; // Success - } - - // Set a transport monitor for checking message ack - void SetTransportMonitor(ITransportMonitor* transportMonitor) - { - m_transportMonitor = transportMonitor; - } - - // Set an alternative send transport - void SetSendTransport(ITransport* sendTransport) - { - m_sendTransport = sendTransport; - } - - // Set an alternative receive transport - void SetRecvTransport(ITransport* recvTransport) - { - m_recvTransport = recvTransport; - } - -private: - void* m_zmqContext = nullptr; - void* m_zmq = nullptr; - Type m_type = Type::PAIR_CLIENT; - - dmq::RecursiveMutex m_mutex; - - ITransport* m_sendTransport = nullptr; - ITransport* m_recvTransport = nullptr; - ITransportMonitor* m_transportMonitor = nullptr; - - static const int BUFFER_SIZE = 4096; - char m_buffer[BUFFER_SIZE] = {}; - char m_sendBuffer[BUFFER_SIZE] = {}; -}; - -} // namespace dmq::transport - -#endif diff --git a/README.md b/README.md index 03bacc3..5853f9b 100644 --- a/README.md +++ b/README.md @@ -63,12 +63,22 @@ By implementing the Serialized Command Processor pattern, this library solves SQ * SQLite - SQLite is a C-language library that implements a small, fast, self-contained, high-reliability, full-featured, SQL database engine. # Getting Started -[CMake](https://cmake.org/) is used to create the project build files on any Windows or Linux machine. +[CMake](https://cmake.org/) 3.16 or newer is used to create the project build files on any Windows or Linux machine. 1. Clone the repository. 2. From the repository root, run the following CMake command: - `cmake -B Build .` -3. Build and run the project within the `Build` directory. + `cmake -B build .` +3. Build and run the project within the `build` directory. + +## Dependencies + +* **SQLite 3.54.1** is included in `SQLite/` (the official single-file amalgamation: `sqlite3.c`, `sqlite3.h`, `sqlite3ext.h`). +* **DelegateMQ** is fetched from GitHub by CMake's `FetchContent` when CMake configures, at the release tag set by `DMQ_GIT_TAG` in `CMakeLists.txt` (currently `v2.4.1`). The wrapper links the `DelegateMQ::DelegateMQ` target. Options: + * Another release: `cmake -B build . -DDMQ_GIT_TAG=` + * A local DelegateMQ checkout instead of GitHub: `-DFETCHCONTENT_SOURCE_DIR_DELEGATEMQ=` + * No network after the first configure: `-DFETCHCONTENT_FULLY_DISCONNECTED=ON` + +To use the wrapper in your own project, add `SQLite/` to your build and add DelegateMQ as described in its [build guide](https://github.com/DelegateMQ/DelegateMQ/blob/master/docs/BUILD.md). # Delegate Quick Start diff --git a/SQLite/CMakeLists.txt b/SQLite/CMakeLists.txt index e3f609f..c4cca99 100644 --- a/SQLite/CMakeLists.txt +++ b/SQLite/CMakeLists.txt @@ -1,16 +1,18 @@ -# Collect all .c files in this subdirectory +# SQLite (single-file amalgamation, sqlite3.c) and the async wrapper +# (async_sqlite3.cpp) file(GLOB SUBDIR_SOURCES "*.c" "*.cpp") - -# Collect all .h files in this subdirectory file(GLOB SUBDIR_HEADERS "*.h") -# Create a library target +# Create a library target add_library(SQLiteLib STATIC ${SUBDIR_SOURCES} ${SUBDIR_HEADERS}) # Include directories for the library target_include_directories(SQLiteLib PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}") -# Add /bigobj flag for MSVC +# The wrapper's public header includes DelegateMQ.h +target_link_libraries(SQLiteLib PUBLIC DelegateMQ::DelegateMQ) + +# Add /bigobj flag for MSVC if (MSVC) target_compile_options(SQLiteLib PRIVATE /bigobj) -endif() \ No newline at end of file +endif() diff --git a/SQLite/shell.c b/SQLite/shell.c deleted file mode 100644 index f92668b..0000000 --- a/SQLite/shell.c +++ /dev/null @@ -1,33359 +0,0 @@ -/* DO NOT EDIT! -** This file is automatically generated by the script in the canonical -** SQLite source tree at tool/mkshellc.tcl. That script combines source -** code from various constituent source files of SQLite into this single -** "shell.c" file used to implement the SQLite command-line shell. -** -** Most of the code found below comes from the "src/shell.c.in" file in -** the canonical SQLite source tree. That main file contains "INCLUDE" -** lines that specify other files in the canonical source tree that are -** inserted to getnerate this complete program source file. -** -** The code from multiple files is combined into this single "shell.c" -** source file to help make the command-line program easier to compile. -** -** To modify this program, get a copy of the canonical SQLite source tree, -** edit the src/shell.c.in" and/or some of the other files that are included -** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script. -*/ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains code to implement the "sqlite" command line -** utility for accessing SQLite databases. -*/ -#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS) -/* This needs to come before any includes for MSVC compiler */ -#define _CRT_SECURE_NO_WARNINGS -#endif -typedef unsigned int u32; -typedef unsigned short int u16; - -/* -** Optionally #include a user-defined header, whereby compilation options -** may be set prior to where they take effect, but after platform setup. -** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include -** file. Note that this macro has a like effect on sqlite3.c compilation. -*/ -# define SHELL_STRINGIFY_(f) #f -# define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f) -#ifdef SQLITE_CUSTOM_INCLUDE -# include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE) -#endif - -/* -** Determine if we are dealing with WinRT, which provides only a subset of -** the full Win32 API. -*/ -#if !defined(SQLITE_OS_WINRT) -# define SQLITE_OS_WINRT 0 -#endif - -/* -** If SQLITE_SHELL_FIDDLE is defined then the shell is modified -** somewhat for use as a WASM module in a web browser. This flag -** should only be used when building the "fiddle" web application, as -** the browser-mode build has much different user input requirements -** and this build mode rewires the user input subsystem to account for -** that. -*/ - -/* -** Warning pragmas copied from msvc.h in the core. -*/ -#if defined(_MSC_VER) -#pragma warning(disable : 4054) -#pragma warning(disable : 4055) -#pragma warning(disable : 4100) -#pragma warning(disable : 4127) -#pragma warning(disable : 4130) -#pragma warning(disable : 4152) -#pragma warning(disable : 4189) -#pragma warning(disable : 4206) -#pragma warning(disable : 4210) -#pragma warning(disable : 4232) -#pragma warning(disable : 4244) -#pragma warning(disable : 4305) -#pragma warning(disable : 4306) -#pragma warning(disable : 4702) -#pragma warning(disable : 4706) -#endif /* defined(_MSC_VER) */ - -/* -** No support for loadable extensions in VxWorks. -*/ -#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION -# define SQLITE_OMIT_LOAD_EXTENSION 1 -#endif - -/* -** Enable large-file support for fopen() and friends on unix. -*/ -#ifndef SQLITE_DISABLE_LFS -# define _LARGE_FILE 1 -# ifndef _FILE_OFFSET_BITS -# define _FILE_OFFSET_BITS 64 -# endif -# define _LARGEFILE_SOURCE 1 -#endif - -#if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE) -/* -** emcc requires _POSIX_SOURCE (or one of several similar defines) -** to expose strdup(). -*/ -# define _POSIX_SOURCE -#endif - -#include -#include -#include -#include -#include -#include "sqlite3.h" -typedef sqlite3_int64 i64; -typedef sqlite3_uint64 u64; -typedef unsigned char u8; -#if SQLITE_USER_AUTHENTICATION -# include "sqlite3userauth.h" -#endif -#include -#include - -#if !defined(_WIN32) && !defined(WIN32) -# include -# if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI) -# include -# endif -#endif -#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__) -# include -# include -# define GETPID getpid -# if defined(__MINGW32__) -# define DIRENT dirent -# ifndef S_ISLNK -# define S_ISLNK(mode) (0) -# endif -# endif -#else -# define GETPID (int)GetCurrentProcessId -#endif -#include -#include - -#if HAVE_READLINE -# include -# include -#endif - -#if HAVE_EDITLINE -# include -#endif - -#if HAVE_EDITLINE || HAVE_READLINE - -# define shell_add_history(X) add_history(X) -# define shell_read_history(X) read_history(X) -# define shell_write_history(X) write_history(X) -# define shell_stifle_history(X) stifle_history(X) -# define shell_readline(X) readline(X) - -#elif HAVE_LINENOISE - -# include "linenoise.h" -# define shell_add_history(X) linenoiseHistoryAdd(X) -# define shell_read_history(X) linenoiseHistoryLoad(X) -# define shell_write_history(X) linenoiseHistorySave(X) -# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X) -# define shell_readline(X) linenoise(X) - -#else - -# define shell_read_history(X) -# define shell_write_history(X) -# define shell_stifle_history(X) - -# define SHELL_USE_LOCAL_GETLINE 1 -#endif - -#ifndef deliberate_fall_through -/* Quiet some compilers about some of our intentional code. */ -# if defined(GCC_VERSION) && GCC_VERSION>=7000000 -# define deliberate_fall_through __attribute__((fallthrough)); -# else -# define deliberate_fall_through -# endif -#endif - -#if defined(_WIN32) || defined(WIN32) -# if SQLITE_OS_WINRT -# define SQLITE_OMIT_POPEN 1 -# else -# include -# include -# define isatty(h) _isatty(h) -# ifndef access -# define access(f,m) _access((f),(m)) -# endif -# ifndef unlink -# define unlink _unlink -# endif -# ifndef strdup -# define strdup _strdup -# endif -# undef pclose -# define pclose _pclose -# endif -#else - /* Make sure isatty() has a prototype. */ - extern int isatty(int); - -# if !defined(__RTP__) && !defined(_WRS_KERNEL) && !defined(SQLITE_WASI) - /* popen and pclose are not C89 functions and so are - ** sometimes omitted from the header */ - extern FILE *popen(const char*,const char*); - extern int pclose(FILE*); -# else -# define SQLITE_OMIT_POPEN 1 -# endif -#endif - -#if defined(_WIN32_WCE) -/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() - * thus we always assume that we have a console. That can be - * overridden with the -batch command line option. - */ -#define isatty(x) 1 -#endif - -/* ctype macros that work with signed characters */ -#define IsSpace(X) isspace((unsigned char)X) -#define IsDigit(X) isdigit((unsigned char)X) -#define ToLower(X) (char)tolower((unsigned char)X) - -#if defined(_WIN32) || defined(WIN32) -#if SQLITE_OS_WINRT -#include -#endif -#undef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#include - -/* string conversion routines only needed on Win32 */ -extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR); -extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText); -#endif - -/************************* Begin ../ext/misc/sqlite3_stdio.h ******************/ -/* -** 2024-09-24 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This header file contains definitions of interfaces that provide -** cross-platform I/O for UTF-8 content. -** -** On most platforms, the interfaces definitions in this file are -** just #defines. For example sqlite3_fopen() is a macro that resolves -** to the standard fopen() in the C-library. -** -** But Windows does not have a standard C-library, at least not one that -** can handle UTF-8. So for windows build, the interfaces resolve to new -** C-language routines contained in the separate sqlite3_stdio.c source file. -** -** So on all non-Windows platforms, simply #include this header file and -** use the interfaces defined herein. Then to run your application on Windows, -** also link in the accompanying sqlite3_stdio.c source file when compiling -** to get compatible interfaces. -*/ -#ifndef _SQLITE3_STDIO_H_ -#define _SQLITE3_STDIO_H_ 1 -#ifdef _WIN32 -/**** Definitions For Windows ****/ -#include -#include - -FILE *sqlite3_fopen(const char *zFilename, const char *zMode); -FILE *sqlite3_popen(const char *zCommand, const char *type); -char *sqlite3_fgets(char *s, int size, FILE *stream); -int sqlite3_fputs(const char *s, FILE *stream); -int sqlite3_fprintf(FILE *stream, const char *format, ...); -void sqlite3_fsetmode(FILE *stream, int mode); - - -#else -/**** Definitions For All Other Platforms ****/ -#include -#define sqlite3_fopen fopen -#define sqlite3_popen popen -#define sqlite3_fgets fgets -#define sqlite3_fputs fputs -#define sqlite3_fprintf fprintf -#define sqlite3_fsetmode(F,X) /*no-op*/ - -#endif -#endif /* _SQLITE3_STDIO_H_ */ - -/************************* End ../ext/misc/sqlite3_stdio.h ********************/ -/************************* Begin ../ext/misc/sqlite3_stdio.c ******************/ -/* -** 2024-09-24 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** Implementation of standard I/O interfaces for UTF-8 that are missing -** on Windows. -*/ -#ifdef _WIN32 /* This file is a no-op on all platforms except Windows */ -#ifndef _SQLITE3_STDIO_H_ -/* #include "sqlite3_stdio.h" */ -#endif -#undef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#include -#include -#include -#include -#include -/* #include "sqlite3.h" */ -#include -#include -#include -#include - -/* -** If the SQLITE_U8TEXT_ONLY option is defined, then use O_U8TEXT -** when appropriate on all output. (Sometimes use O_BINARY when -** rendering ASCII text in cases where NL-to-CRLF expansion would -** not be correct.) -** -** If the SQLITE_U8TEXT_STDIO option is defined, then use O_U8TEXT -** when appropriate when writing to stdout or stderr. Use O_BINARY -** or O_TEXT (depending on things like the .mode and the .crlf setting -** in the CLI, or other context clues in other applications) for all -** other output channels. -** -** The default behavior, if neither of the above is defined is to -** use O_U8TEXT when writing to the Windows console (or anything -** else for which _isatty() returns true) and to use O_BINARY or O_TEXT -** for all other output channels. -*/ -#if defined(SQLITE_U8TEXT_ONLY) -# define UseWtextForOutput(fd) 1 -# define UseWtextForInput(fd) 1 -# define IsConsole(fd) _isatty(_fileno(fd)) -#elif defined(SQLITE_U8TEXT_STDIO) -# define UseWtextForOutput(fd) ((fd)==stdout || (fd)==stderr) -# define UseWtextForInput(fd) ((fd)==stdin) -# define IsConsole(fd) _isatty(_fileno(fd)) -#else -# define UseWtextForOutput(fd) _isatty(_fileno(fd)) -# define UseWtextForInput(fd) _isatty(_fileno(fd)) -# define IsConsole(fd) 1 -#endif - -/* -** Global variables determine if simulated O_BINARY mode is to be -** used for stdout or other, respectively. Simulated O_BINARY mode -** means the mode is usually O_BINARY, but switches to O_U8TEXT for -** unicode characters U+0080 or greater (any character that has a -** multi-byte representation in UTF-8). This is the only way we -** have found to render Unicode characters on a Windows console while -** at the same time avoiding undesirable \n to \r\n translation. -*/ -static int simBinaryStdout = 0; -static int simBinaryOther = 0; - - -/* -** Determine if simulated binary mode should be used for output to fd -*/ -static int UseBinaryWText(FILE *fd){ - if( fd==stdout || fd==stderr ){ - return simBinaryStdout; - }else{ - return simBinaryOther; - } -} - - -/* -** Work-alike for the fopen() routine from the standard C library. -*/ -FILE *sqlite3_fopen(const char *zFilename, const char *zMode){ - FILE *fp = 0; - wchar_t *b1, *b2; - int sz1, sz2; - - sz1 = (int)strlen(zFilename); - sz2 = (int)strlen(zMode); - b1 = malloc( (sz1+1)*sizeof(b1[0]) ); - b2 = malloc( (sz2+1)*sizeof(b1[0]) ); - if( b1 && b2 ){ - sz1 = MultiByteToWideChar(CP_UTF8, 0, zFilename, sz1, b1, sz1); - b1[sz1] = 0; - sz2 = MultiByteToWideChar(CP_UTF8, 0, zMode, sz2, b2, sz2); - b2[sz2] = 0; - fp = _wfopen(b1, b2); - } - free(b1); - free(b2); - simBinaryOther = 0; - return fp; -} - - -/* -** Work-alike for the popen() routine from the standard C library. -*/ -FILE *sqlite3_popen(const char *zCommand, const char *zMode){ - FILE *fp = 0; - wchar_t *b1, *b2; - int sz1, sz2; - - sz1 = (int)strlen(zCommand); - sz2 = (int)strlen(zMode); - b1 = malloc( (sz1+1)*sizeof(b1[0]) ); - b2 = malloc( (sz2+1)*sizeof(b1[0]) ); - if( b1 && b2 ){ - sz1 = MultiByteToWideChar(CP_UTF8, 0, zCommand, sz1, b1, sz1); - b1[sz1] = 0; - sz2 = MultiByteToWideChar(CP_UTF8, 0, zMode, sz2, b2, sz2); - b2[sz2] = 0; - fp = _wpopen(b1, b2); - } - free(b1); - free(b2); - return fp; -} - -/* -** Work-alike for fgets() from the standard C library. -*/ -char *sqlite3_fgets(char *buf, int sz, FILE *in){ - if( UseWtextForInput(in) ){ - /* When reading from the command-prompt in Windows, it is necessary - ** to use _O_WTEXT input mode to read UTF-16 characters, then translate - ** that into UTF-8. Otherwise, non-ASCII characters all get translated - ** into '?'. - */ - wchar_t *b1 = malloc( sz*sizeof(wchar_t) ); - if( b1==0 ) return 0; - _setmode(_fileno(in), IsConsole(in) ? _O_WTEXT : _O_U8TEXT); - if( fgetws(b1, sz/4, in)==0 ){ - sqlite3_free(b1); - return 0; - } - WideCharToMultiByte(CP_UTF8, 0, b1, -1, buf, sz, 0, 0); - sqlite3_free(b1); - return buf; - }else{ - /* Reading from a file or other input source, just read bytes without - ** any translation. */ - return fgets(buf, sz, in); - } -} - -/* -** Send ASCII text as O_BINARY. But for Unicode characters U+0080 and -** greater, switch to O_U8TEXT. -*/ -static void piecemealOutput(wchar_t *b1, int sz, FILE *out){ - int i; - wchar_t c; - while( sz>0 ){ - for(i=0; i=0x80; i++){} - if( i>0 ){ - c = b1[i]; - b1[i] = 0; - fflush(out); - _setmode(_fileno(out), _O_U8TEXT); - fputws(b1, out); - fflush(out); - b1 += i; - b1[0] = c; - sz -= i; - }else{ - fflush(out); - _setmode(_fileno(out), _O_TEXT); - _setmode(_fileno(out), _O_BINARY); - fwrite(&b1[0], 1, 1, out); - for(i=1; iiVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){ - clockVfs->xCurrentTimeInt64(clockVfs, &t); - }else{ - double r; - clockVfs->xCurrentTime(clockVfs, &r); - t = (sqlite3_int64)(r*86400000.0); - } - return t; -} - -#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux) -#include -#include - -/* VxWorks does not support getrusage() as far as we can determine */ -#if defined(_WRS_KERNEL) || defined(__RTP__) -struct rusage { - struct timeval ru_utime; /* user CPU time used */ - struct timeval ru_stime; /* system CPU time used */ -}; -#define getrusage(A,B) memset(B,0,sizeof(*B)) -#endif - - -/* Saved resource information for the beginning of an operation */ -static struct rusage sBegin; /* CPU time at start */ -static sqlite3_int64 iBegin; /* Wall-clock time at start */ - -/* -** Begin timing an operation -*/ -static void beginTimer(void){ - if( enableTimer ){ - getrusage(RUSAGE_SELF, &sBegin); - iBegin = timeOfDay(); - } -} - -/* Return the difference of two time_structs in seconds */ -static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ - return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + - (double)(pEnd->tv_sec - pStart->tv_sec); -} - -/* -** Print the timing results. -*/ -static void endTimer(FILE *out){ - if( enableTimer ){ - sqlite3_int64 iEnd = timeOfDay(); - struct rusage sEnd; - getrusage(RUSAGE_SELF, &sEnd); - sqlite3_fprintf(out, "Run Time: real %.3f user %f sys %f\n", - (iEnd - iBegin)*0.001, - timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), - timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); - } -} - -#define BEGIN_TIMER beginTimer() -#define END_TIMER(X) endTimer(X) -#define HAS_TIMER 1 - -#elif (defined(_WIN32) || defined(WIN32)) - -/* Saved resource information for the beginning of an operation */ -static HANDLE hProcess; -static FILETIME ftKernelBegin; -static FILETIME ftUserBegin; -static sqlite3_int64 ftWallBegin; -typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, - LPFILETIME, LPFILETIME); -static GETPROCTIMES getProcessTimesAddr = NULL; - -/* -** Check to see if we have timer support. Return 1 if necessary -** support found (or found previously). -*/ -static int hasTimer(void){ - if( getProcessTimesAddr ){ - return 1; - } else { -#if !SQLITE_OS_WINRT - /* GetProcessTimes() isn't supported in WIN95 and some other Windows - ** versions. See if the version we are running on has it, and if it - ** does, save off a pointer to it and the current process handle. - */ - hProcess = GetCurrentProcess(); - if( hProcess ){ - HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); - if( NULL != hinstLib ){ - getProcessTimesAddr = - (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); - if( NULL != getProcessTimesAddr ){ - return 1; - } - FreeLibrary(hinstLib); - } - } -#endif - } - return 0; -} - -/* -** Begin timing an operation -*/ -static void beginTimer(void){ - if( enableTimer && getProcessTimesAddr ){ - FILETIME ftCreation, ftExit; - getProcessTimesAddr(hProcess,&ftCreation,&ftExit, - &ftKernelBegin,&ftUserBegin); - ftWallBegin = timeOfDay(); - } -} - -/* Return the difference of two FILETIME structs in seconds */ -static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ - sqlite_int64 i64Start = *((sqlite_int64 *) pStart); - sqlite_int64 i64End = *((sqlite_int64 *) pEnd); - return (double) ((i64End - i64Start) / 10000000.0); -} - -/* -** Print the timing results. -*/ -static void endTimer(FILE *out){ - if( enableTimer && getProcessTimesAddr){ - FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; - sqlite3_int64 ftWallEnd = timeOfDay(); - getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd); - sqlite3_fprintf(out, "Run Time: real %.3f user %f sys %f\n", - (ftWallEnd - ftWallBegin)*0.001, - timeDiff(&ftUserBegin, &ftUserEnd), - timeDiff(&ftKernelBegin, &ftKernelEnd)); - } -} - -#define BEGIN_TIMER beginTimer() -#define END_TIMER(X) endTimer(X) -#define HAS_TIMER hasTimer() - -#else -#define BEGIN_TIMER -#define END_TIMER(X) /*no-op*/ -#define HAS_TIMER 0 -#endif - -/* -** Used to prevent warnings about unused parameters -*/ -#define UNUSED_PARAMETER(x) (void)(x) - -/* -** Number of elements in an array -*/ -#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) - -/* -** If the following flag is set, then command execution stops -** at an error if we are not interactive. -*/ -static int bail_on_error = 0; - -/* -** Treat stdin as an interactive input if the following variable -** is true. Otherwise, assume stdin is connected to a file or pipe. -*/ -static int stdin_is_interactive = 1; - -/* -** On Windows systems we need to know if standard output is a console -** in order to show that UTF-16 translation is done in the sign-on -** banner. The following variable is true if it is the console. -*/ -static int stdout_is_console = 1; - -/* -** The following is the open SQLite database. We make a pointer -** to this database a static variable so that it can be accessed -** by the SIGINT handler to interrupt database processing. -*/ -static sqlite3 *globalDb = 0; - -/* -** True if an interrupt (Control-C) has been received. -*/ -static volatile int seenInterrupt = 0; - -/* -** This is the name of our program. It is set in main(), used -** in a number of other places, mostly for error messages. -*/ -static char *Argv0; - -/* -** Prompt strings. Initialized in main. Settable with -** .prompt main continue -*/ -#define PROMPT_LEN_MAX 20 -/* First line prompt. default: "sqlite> " */ -static char mainPrompt[PROMPT_LEN_MAX]; -/* Continuation prompt. default: " ...> " */ -static char continuePrompt[PROMPT_LEN_MAX]; - -/* This is variant of the standard-library strncpy() routine with the -** one change that the destination string is always zero-terminated, even -** if there is no zero-terminator in the first n-1 characters of the source -** string. -*/ -static char *shell_strncpy(char *dest, const char *src, size_t n){ - size_t i; - for(i=0; iinParenLevel += ni; - if( ni==0 ) p->inParenLevel = 0; - p->zScannerAwaits = 0; -} - -/* Record that a lexeme is opened, or closed with args==0. */ -static void setLexemeOpen(struct DynaPrompt *p, char *s, char c){ - if( s!=0 || c==0 ){ - p->zScannerAwaits = s; - p->acAwait[0] = 0; - }else{ - p->acAwait[0] = c; - p->zScannerAwaits = p->acAwait; - } -} - -/* Upon demand, derive the continuation prompt to display. */ -static char *dynamicContinuePrompt(void){ - if( continuePrompt[0]==0 - || (dynPrompt.zScannerAwaits==0 && dynPrompt.inParenLevel == 0) ){ - return continuePrompt; - }else{ - if( dynPrompt.zScannerAwaits ){ - size_t ncp = strlen(continuePrompt); - size_t ndp = strlen(dynPrompt.zScannerAwaits); - if( ndp > ncp-3 ) return continuePrompt; - shell_strcpy(dynPrompt.dynamicPrompt, dynPrompt.zScannerAwaits); - while( ndp<3 ) dynPrompt.dynamicPrompt[ndp++] = ' '; - shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3, - PROMPT_LEN_MAX-4); - }else{ - if( dynPrompt.inParenLevel>9 ){ - shell_strncpy(dynPrompt.dynamicPrompt, "(..", 4); - }else if( dynPrompt.inParenLevel<0 ){ - shell_strncpy(dynPrompt.dynamicPrompt, ")x!", 4); - }else{ - shell_strncpy(dynPrompt.dynamicPrompt, "(x.", 4); - dynPrompt.dynamicPrompt[2] = (char)('0'+dynPrompt.inParenLevel); - } - shell_strncpy(dynPrompt.dynamicPrompt+3, continuePrompt+3, - PROMPT_LEN_MAX-4); - } - } - return dynPrompt.dynamicPrompt; -} -#endif /* !defined(SQLITE_OMIT_DYNAPROMPT) */ - -/* Indicate out-of-memory and exit. */ -static void shell_out_of_memory(void){ - eputz("Error: out of memory\n"); - exit(1); -} - -/* Check a pointer to see if it is NULL. If it is NULL, exit with an -** out-of-memory error. -*/ -static void shell_check_oom(const void *p){ - if( p==0 ) shell_out_of_memory(); -} - -/* -** Write I/O traces to the following stream. -*/ -#ifdef SQLITE_ENABLE_IOTRACE -static FILE *iotrace = 0; -#endif - -/* -** This routine works like printf in that its first argument is a -** format string and subsequent arguments are values to be substituted -** in place of % fields. The result of formatting this string -** is written to iotrace. -*/ -#ifdef SQLITE_ENABLE_IOTRACE -static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){ - va_list ap; - char *z; - if( iotrace==0 ) return; - va_start(ap, zFormat); - z = sqlite3_vmprintf(zFormat, ap); - va_end(ap); - sqlite3_fprintf(iotrace, "%s", z); - sqlite3_free(z); -} -#endif - -/* Lookup table to estimate the number of columns consumed by a Unicode -** character. -*/ -static const struct { - unsigned char w; /* Width of the character in columns */ - int iFirst; /* First character in a span having this width */ -} aUWidth[] = { - /* {1, 0x00000}, */ - {0, 0x00300}, {1, 0x00370}, {0, 0x00483}, {1, 0x00487}, {0, 0x00488}, - {1, 0x0048a}, {0, 0x00591}, {1, 0x005be}, {0, 0x005bf}, {1, 0x005c0}, - {0, 0x005c1}, {1, 0x005c3}, {0, 0x005c4}, {1, 0x005c6}, {0, 0x005c7}, - {1, 0x005c8}, {0, 0x00600}, {1, 0x00604}, {0, 0x00610}, {1, 0x00616}, - {0, 0x0064b}, {1, 0x0065f}, {0, 0x00670}, {1, 0x00671}, {0, 0x006d6}, - {1, 0x006e5}, {0, 0x006e7}, {1, 0x006e9}, {0, 0x006ea}, {1, 0x006ee}, - {0, 0x0070f}, {1, 0x00710}, {0, 0x00711}, {1, 0x00712}, {0, 0x00730}, - {1, 0x0074b}, {0, 0x007a6}, {1, 0x007b1}, {0, 0x007eb}, {1, 0x007f4}, - {0, 0x00901}, {1, 0x00903}, {0, 0x0093c}, {1, 0x0093d}, {0, 0x00941}, - {1, 0x00949}, {0, 0x0094d}, {1, 0x0094e}, {0, 0x00951}, {1, 0x00955}, - {0, 0x00962}, {1, 0x00964}, {0, 0x00981}, {1, 0x00982}, {0, 0x009bc}, - {1, 0x009bd}, {0, 0x009c1}, {1, 0x009c5}, {0, 0x009cd}, {1, 0x009ce}, - {0, 0x009e2}, {1, 0x009e4}, {0, 0x00a01}, {1, 0x00a03}, {0, 0x00a3c}, - {1, 0x00a3d}, {0, 0x00a41}, {1, 0x00a43}, {0, 0x00a47}, {1, 0x00a49}, - {0, 0x00a4b}, {1, 0x00a4e}, {0, 0x00a70}, {1, 0x00a72}, {0, 0x00a81}, - {1, 0x00a83}, {0, 0x00abc}, {1, 0x00abd}, {0, 0x00ac1}, {1, 0x00ac6}, - {0, 0x00ac7}, {1, 0x00ac9}, {0, 0x00acd}, {1, 0x00ace}, {0, 0x00ae2}, - {1, 0x00ae4}, {0, 0x00b01}, {1, 0x00b02}, {0, 0x00b3c}, {1, 0x00b3d}, - {0, 0x00b3f}, {1, 0x00b40}, {0, 0x00b41}, {1, 0x00b44}, {0, 0x00b4d}, - {1, 0x00b4e}, {0, 0x00b56}, {1, 0x00b57}, {0, 0x00b82}, {1, 0x00b83}, - {0, 0x00bc0}, {1, 0x00bc1}, {0, 0x00bcd}, {1, 0x00bce}, {0, 0x00c3e}, - {1, 0x00c41}, {0, 0x00c46}, {1, 0x00c49}, {0, 0x00c4a}, {1, 0x00c4e}, - {0, 0x00c55}, {1, 0x00c57}, {0, 0x00cbc}, {1, 0x00cbd}, {0, 0x00cbf}, - {1, 0x00cc0}, {0, 0x00cc6}, {1, 0x00cc7}, {0, 0x00ccc}, {1, 0x00cce}, - {0, 0x00ce2}, {1, 0x00ce4}, {0, 0x00d41}, {1, 0x00d44}, {0, 0x00d4d}, - {1, 0x00d4e}, {0, 0x00dca}, {1, 0x00dcb}, {0, 0x00dd2}, {1, 0x00dd5}, - {0, 0x00dd6}, {1, 0x00dd7}, {0, 0x00e31}, {1, 0x00e32}, {0, 0x00e34}, - {1, 0x00e3b}, {0, 0x00e47}, {1, 0x00e4f}, {0, 0x00eb1}, {1, 0x00eb2}, - {0, 0x00eb4}, {1, 0x00eba}, {0, 0x00ebb}, {1, 0x00ebd}, {0, 0x00ec8}, - {1, 0x00ece}, {0, 0x00f18}, {1, 0x00f1a}, {0, 0x00f35}, {1, 0x00f36}, - {0, 0x00f37}, {1, 0x00f38}, {0, 0x00f39}, {1, 0x00f3a}, {0, 0x00f71}, - {1, 0x00f7f}, {0, 0x00f80}, {1, 0x00f85}, {0, 0x00f86}, {1, 0x00f88}, - {0, 0x00f90}, {1, 0x00f98}, {0, 0x00f99}, {1, 0x00fbd}, {0, 0x00fc6}, - {1, 0x00fc7}, {0, 0x0102d}, {1, 0x01031}, {0, 0x01032}, {1, 0x01033}, - {0, 0x01036}, {1, 0x01038}, {0, 0x01039}, {1, 0x0103a}, {0, 0x01058}, - {1, 0x0105a}, {2, 0x01100}, {0, 0x01160}, {1, 0x01200}, {0, 0x0135f}, - {1, 0x01360}, {0, 0x01712}, {1, 0x01715}, {0, 0x01732}, {1, 0x01735}, - {0, 0x01752}, {1, 0x01754}, {0, 0x01772}, {1, 0x01774}, {0, 0x017b4}, - {1, 0x017b6}, {0, 0x017b7}, {1, 0x017be}, {0, 0x017c6}, {1, 0x017c7}, - {0, 0x017c9}, {1, 0x017d4}, {0, 0x017dd}, {1, 0x017de}, {0, 0x0180b}, - {1, 0x0180e}, {0, 0x018a9}, {1, 0x018aa}, {0, 0x01920}, {1, 0x01923}, - {0, 0x01927}, {1, 0x01929}, {0, 0x01932}, {1, 0x01933}, {0, 0x01939}, - {1, 0x0193c}, {0, 0x01a17}, {1, 0x01a19}, {0, 0x01b00}, {1, 0x01b04}, - {0, 0x01b34}, {1, 0x01b35}, {0, 0x01b36}, {1, 0x01b3b}, {0, 0x01b3c}, - {1, 0x01b3d}, {0, 0x01b42}, {1, 0x01b43}, {0, 0x01b6b}, {1, 0x01b74}, - {0, 0x01dc0}, {1, 0x01dcb}, {0, 0x01dfe}, {1, 0x01e00}, {0, 0x0200b}, - {1, 0x02010}, {0, 0x0202a}, {1, 0x0202f}, {0, 0x02060}, {1, 0x02064}, - {0, 0x0206a}, {1, 0x02070}, {0, 0x020d0}, {1, 0x020f0}, {2, 0x02329}, - {1, 0x0232b}, {2, 0x02e80}, {0, 0x0302a}, {2, 0x03030}, {1, 0x0303f}, - {2, 0x03040}, {0, 0x03099}, {2, 0x0309b}, {1, 0x0a4d0}, {0, 0x0a806}, - {1, 0x0a807}, {0, 0x0a80b}, {1, 0x0a80c}, {0, 0x0a825}, {1, 0x0a827}, - {2, 0x0ac00}, {1, 0x0d7a4}, {2, 0x0f900}, {1, 0x0fb00}, {0, 0x0fb1e}, - {1, 0x0fb1f}, {0, 0x0fe00}, {2, 0x0fe10}, {1, 0x0fe1a}, {0, 0x0fe20}, - {1, 0x0fe24}, {2, 0x0fe30}, {1, 0x0fe70}, {0, 0x0feff}, {2, 0x0ff00}, - {1, 0x0ff61}, {2, 0x0ffe0}, {1, 0x0ffe7}, {0, 0x0fff9}, {1, 0x0fffc}, - {0, 0x10a01}, {1, 0x10a04}, {0, 0x10a05}, {1, 0x10a07}, {0, 0x10a0c}, - {1, 0x10a10}, {0, 0x10a38}, {1, 0x10a3b}, {0, 0x10a3f}, {1, 0x10a40}, - {0, 0x1d167}, {1, 0x1d16a}, {0, 0x1d173}, {1, 0x1d183}, {0, 0x1d185}, - {1, 0x1d18c}, {0, 0x1d1aa}, {1, 0x1d1ae}, {0, 0x1d242}, {1, 0x1d245}, - {2, 0x20000}, {1, 0x2fffe}, {2, 0x30000}, {1, 0x3fffe}, {0, 0xe0001}, - {1, 0xe0002}, {0, 0xe0020}, {1, 0xe0080}, {0, 0xe0100}, {1, 0xe01f0} -}; - -/* -** Return an estimate of the width, in columns, for the single Unicode -** character c. For normal characters, the answer is always 1. But the -** estimate might be 0 or 2 for zero-width and double-width characters. -** -** Different display devices display unicode using different widths. So -** it is impossible to know that true display width with 100% accuracy. -** Inaccuracies in the width estimates might cause columns to be misaligned. -** Unfortunately, there is nothing we can do about that. -*/ -int cli_wcwidth(int c){ - int iFirst, iLast; - - /* Fast path for common characters */ - if( c<=0x300 ) return 1; - - /* The general case */ - iFirst = 0; - iLast = sizeof(aUWidth)/sizeof(aUWidth[0]) - 1; - while( iFirst c ){ - iLast = iMid - 1; - }else{ - return aUWidth[iMid].w; - } - } - if( aUWidth[iLast].iFirst > c ) return aUWidth[iFirst].w; - return aUWidth[iLast].w; -} - -/* -** Compute the value and length of a multi-byte UTF-8 character that -** begins at z[0]. Return the length. Write the Unicode value into *pU. -** -** This routine only works for *multi-byte* UTF-8 characters. -*/ -static int decodeUtf8(const unsigned char *z, int *pU){ - if( (z[0] & 0xe0)==0xc0 && (z[1] & 0xc0)==0x80 ){ - *pU = ((z[0] & 0x1f)<<6) | (z[1] & 0x3f); - return 2; - } - if( (z[0] & 0xf0)==0xe0 && (z[1] & 0xc0)==0x80 && (z[2] & 0xc0)==0x80 ){ - *pU = ((z[0] & 0x0f)<<12) | ((z[1] & 0x3f)<<6) | (z[2] & 0x3f); - return 3; - } - if( (z[0] & 0xf8)==0xf0 && (z[1] & 0xc0)==0x80 && (z[2] & 0xc0)==0x80 - && (z[3] & 0xc0)==0x80 - ){ - *pU = ((z[0] & 0x0f)<<18) | ((z[1] & 0x3f)<<12) | ((z[2] & 0x3f))<<6 - | (z[4] & 0x3f); - return 4; - } - *pU = 0; - return 1; -} - - -#if 0 /* NOT USED */ -/* -** Return the width, in display columns, of a UTF-8 string. -** -** Each normal character counts as 1. Zero-width characters count -** as zero, and double-width characters count as 2. -*/ -int cli_wcswidth(const char *z){ - const unsigned char *a = (const unsigned char*)z; - int n = 0; - int i = 0; - unsigned char c; - while( (c = a[i])!=0 ){ - if( c>=0xc0 ){ - int u; - int len = decodeUtf8(&a[i], &u); - i += len; - n += cli_wcwidth(u); - }else if( c>=' ' ){ - n++; - i++; - }else{ - i++; - } - } - return n; -} -#endif - -/* -** Output string zUtf to stdout as w characters. If w is negative, -** then right-justify the text. W is the width in UTF-8 characters, not -** in bytes. This is different from the %*.*s specification in printf -** since with %*.*s the width is measured in bytes, not characters. -** -** Take into account zero-width and double-width Unicode characters. -** In other words, a zero-width character does not count toward the -** the w limit. A double-width character counts as two. -*/ -static void utf8_width_print(FILE *out, int w, const char *zUtf){ - const unsigned char *a = (const unsigned char*)zUtf; - unsigned char c; - int i = 0; - int n = 0; - int aw = w<0 ? -w : w; - if( zUtf==0 ) zUtf = ""; - while( (c = a[i])!=0 ){ - if( (c&0xc0)==0xc0 ){ - int u; - int len = decodeUtf8(a+i, &u); - int x = cli_wcwidth(u); - if( x+n>aw ){ - break; - } - i += len; - n += x; - }else if( n>=aw ){ - break; - }else{ - n++; - i++; - } - } - if( n>=aw ){ - sqlite3_fprintf(out, "%.*s", i, zUtf); - }else if( w<0 ){ - sqlite3_fprintf(out, "%*s%s", aw-n, "", zUtf); - }else{ - sqlite3_fprintf(out, "%s%*s", zUtf, aw-n, ""); - } -} - - -/* -** Determines if a string is a number of not. -*/ -static int isNumber(const char *z, int *realnum){ - if( *z=='-' || *z=='+' ) z++; - if( !IsDigit(*z) ){ - return 0; - } - z++; - if( realnum ) *realnum = 0; - while( IsDigit(*z) ){ z++; } - if( *z=='.' ){ - z++; - if( !IsDigit(*z) ) return 0; - while( IsDigit(*z) ){ z++; } - if( realnum ) *realnum = 1; - } - if( *z=='e' || *z=='E' ){ - z++; - if( *z=='+' || *z=='-' ) z++; - if( !IsDigit(*z) ) return 0; - while( IsDigit(*z) ){ z++; } - if( realnum ) *realnum = 1; - } - return *z==0; -} - -/* -** Compute a string length that is limited to what can be stored in -** lower 30 bits of a 32-bit signed integer. -*/ -static int strlen30(const char *z){ - const char *z2 = z; - while( *z2 ){ z2++; } - return 0x3fffffff & (int)(z2 - z); -} - -/* -** Return the length of a string in characters. Multibyte UTF8 characters -** count as a single character. -*/ -static int strlenChar(const char *z){ - int n = 0; - while( *z ){ - if( (0xc0&*(z++))!=0x80 ) n++; - } - return n; -} - -/* -** Return open FILE * if zFile exists, can be opened for read -** and is an ordinary file or a character stream source. -** Otherwise return 0. -*/ -static FILE * openChrSource(const char *zFile){ -#if defined(_WIN32) || defined(WIN32) - struct __stat64 x = {0}; -# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0) - /* On Windows, open first, then check the stream nature. This order - ** is necessary because _stat() and sibs, when checking a named pipe, - ** effectively break the pipe as its supplier sees it. */ - FILE *rv = sqlite3_fopen(zFile, "rb"); - if( rv==0 ) return 0; - if( _fstat64(_fileno(rv), &x) != 0 - || !STAT_CHR_SRC(x.st_mode)){ - fclose(rv); - rv = 0; - } - return rv; -#else - struct stat x = {0}; - int rc = stat(zFile, &x); -# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode)) - if( rc!=0 ) return 0; - if( STAT_CHR_SRC(x.st_mode) ){ - return sqlite3_fopen(zFile, "rb"); - }else{ - return 0; - } -#endif -#undef STAT_CHR_SRC -} - -/* -** This routine reads a line of text from FILE in, stores -** the text in memory obtained from malloc() and returns a pointer -** to the text. NULL is returned at end of file, or if malloc() -** fails. -** -** If zLine is not NULL then it is a malloced buffer returned from -** a previous call to this routine that may be reused. -*/ -static char *local_getline(char *zLine, FILE *in){ - int nLine = zLine==0 ? 0 : 100; - int n = 0; - - while( 1 ){ - if( n+100>nLine ){ - nLine = nLine*2 + 100; - zLine = realloc(zLine, nLine); - shell_check_oom(zLine); - } - if( sqlite3_fgets(&zLine[n], nLine - n, in)==0 ){ - if( n==0 ){ - free(zLine); - return 0; - } - zLine[n] = 0; - break; - } - while( zLine[n] ) n++; - if( n>0 && zLine[n-1]=='\n' ){ - n--; - if( n>0 && zLine[n-1]=='\r' ) n--; - zLine[n] = 0; - break; - } - } - return zLine; -} - -/* -** Retrieve a single line of input text. -** -** If in==0 then read from standard input and prompt before each line. -** If isContinuation is true, then a continuation prompt is appropriate. -** If isContinuation is zero, then the main prompt should be used. -** -** If zPrior is not NULL then it is a buffer from a prior call to this -** routine that can be reused. -** -** The result is stored in space obtained from malloc() and must either -** be freed by the caller or else passed back into this routine via the -** zPrior argument for reuse. -*/ -#ifndef SQLITE_SHELL_FIDDLE -static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ - char *zPrompt; - char *zResult; - if( in!=0 ){ - zResult = local_getline(zPrior, in); - }else{ - zPrompt = isContinuation ? CONTINUATION_PROMPT : mainPrompt; -#if SHELL_USE_LOCAL_GETLINE - sputz(stdout, zPrompt); - fflush(stdout); - do{ - zResult = local_getline(zPrior, stdin); - zPrior = 0; - /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */ - if( zResult==0 ) sqlite3_sleep(50); - }while( zResult==0 && seenInterrupt>0 ); -#else - free(zPrior); - zResult = shell_readline(zPrompt); - while( zResult==0 ){ - /* ^C trap creates a false EOF, so let "interrupt" thread catch up. */ - sqlite3_sleep(50); - if( seenInterrupt==0 ) break; - zResult = shell_readline(""); - } - if( zResult && *zResult ) shell_add_history(zResult); -#endif - } - return zResult; -} -#endif /* !SQLITE_SHELL_FIDDLE */ - -/* -** Return the value of a hexadecimal digit. Return -1 if the input -** is not a hex digit. -*/ -static int hexDigitValue(char c){ - if( c>='0' && c<='9' ) return c - '0'; - if( c>='a' && c<='f' ) return c - 'a' + 10; - if( c>='A' && c<='F' ) return c - 'A' + 10; - return -1; -} - -/* -** Interpret zArg as an integer value, possibly with suffixes. -*/ -static sqlite3_int64 integerValue(const char *zArg){ - sqlite3_int64 v = 0; - static const struct { char *zSuffix; int iMult; } aMult[] = { - { "KiB", 1024 }, - { "MiB", 1024*1024 }, - { "GiB", 1024*1024*1024 }, - { "KB", 1000 }, - { "MB", 1000000 }, - { "GB", 1000000000 }, - { "K", 1000 }, - { "M", 1000000 }, - { "G", 1000000000 }, - }; - int i; - int isNeg = 0; - if( zArg[0]=='-' ){ - isNeg = 1; - zArg++; - }else if( zArg[0]=='+' ){ - zArg++; - } - if( zArg[0]=='0' && zArg[1]=='x' ){ - int x; - zArg += 2; - while( (x = hexDigitValue(zArg[0]))>=0 ){ - v = (v<<4) + x; - zArg++; - } - }else{ - while( IsDigit(zArg[0]) ){ - v = v*10 + zArg[0] - '0'; - zArg++; - } - } - for(i=0; iz); - initText(p); -} - -/* zIn is either a pointer to a NULL-terminated string in memory obtained -** from malloc(), or a NULL pointer. The string pointed to by zAppend is -** added to zIn, and the result returned in memory obtained from malloc(). -** zIn, if it was not NULL, is freed. -** -** If the third argument, quote, is not '\0', then it is used as a -** quote character for zAppend. -*/ -static void appendText(ShellText *p, const char *zAppend, char quote){ - i64 len; - i64 i; - i64 nAppend = strlen30(zAppend); - - len = nAppend+p->n+1; - if( quote ){ - len += 2; - for(i=0; iz==0 || p->n+len>=p->nAlloc ){ - p->nAlloc = p->nAlloc*2 + len + 20; - p->z = realloc(p->z, p->nAlloc); - shell_check_oom(p->z); - } - - if( quote ){ - char *zCsr = p->z+p->n; - *zCsr++ = quote; - for(i=0; in = (int)(zCsr - p->z); - *zCsr = '\0'; - }else{ - memcpy(p->z+p->n, zAppend, nAppend); - p->n += nAppend; - p->z[p->n] = '\0'; - } -} - -/* -** Attempt to determine if identifier zName needs to be quoted, either -** because it contains non-alphanumeric characters, or because it is an -** SQLite keyword. Be conservative in this estimate: When in doubt assume -** that quoting is required. -** -** Return '"' if quoting is required. Return 0 if no quoting is required. -*/ -static char quoteChar(const char *zName){ - int i; - if( zName==0 ) return '"'; - if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"'; - for(i=0; zName[i]; i++){ - if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"'; - } - return sqlite3_keyword_check(zName, i) ? '"' : 0; -} - -/* -** Construct a fake object name and column list to describe the structure -** of the view, virtual table, or table valued function zSchema.zName. -*/ -static char *shellFakeSchema( - sqlite3 *db, /* The database connection containing the vtab */ - const char *zSchema, /* Schema of the database holding the vtab */ - const char *zName /* The name of the virtual table */ -){ - sqlite3_stmt *pStmt = 0; - char *zSql; - ShellText s; - char cQuote; - char *zDiv = "("; - int nRow = 0; - - zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;", - zSchema ? zSchema : "main", zName); - shell_check_oom(zSql); - sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - initText(&s); - if( zSchema ){ - cQuote = quoteChar(zSchema); - if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0; - appendText(&s, zSchema, cQuote); - appendText(&s, ".", 0); - } - cQuote = quoteChar(zName); - appendText(&s, zName, cQuote); - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - const char *zCol = (const char*)sqlite3_column_text(pStmt, 1); - nRow++; - appendText(&s, zDiv, 0); - zDiv = ","; - if( zCol==0 ) zCol = ""; - cQuote = quoteChar(zCol); - appendText(&s, zCol, cQuote); - } - appendText(&s, ")", 0); - sqlite3_finalize(pStmt); - if( nRow==0 ){ - freeText(&s); - s.z = 0; - } - return s.z; -} - -/* -** SQL function: strtod(X) -** -** Use the C-library strtod() function to convert string X into a double. -** Used for comparing the accuracy of SQLite's internal text-to-float conversion -** routines against the C-library. -*/ -static void shellStrtod( - sqlite3_context *pCtx, - int nVal, - sqlite3_value **apVal -){ - char *z = (char*)sqlite3_value_text(apVal[0]); - UNUSED_PARAMETER(nVal); - if( z==0 ) return; - sqlite3_result_double(pCtx, strtod(z,0)); -} - -/* -** SQL function: dtostr(X) -** -** Use the C-library printf() function to convert real value X into a string. -** Used for comparing the accuracy of SQLite's internal float-to-text conversion -** routines against the C-library. -*/ -static void shellDtostr( - sqlite3_context *pCtx, - int nVal, - sqlite3_value **apVal -){ - double r = sqlite3_value_double(apVal[0]); - int n = nVal>=2 ? sqlite3_value_int(apVal[1]) : 26; - char z[400]; - if( n<1 ) n = 1; - if( n>350 ) n = 350; - sqlite3_snprintf(sizeof(z), z, "%#+.*e", n, r); - sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); -} - - -/* -** SQL function: shell_module_schema(X) -** -** Return a fake schema for the table-valued function or eponymous virtual -** table X. -*/ -static void shellModuleSchema( - sqlite3_context *pCtx, - int nVal, - sqlite3_value **apVal -){ - const char *zName; - char *zFake; - UNUSED_PARAMETER(nVal); - zName = (const char*)sqlite3_value_text(apVal[0]); - zFake = zName? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0; - if( zFake ){ - sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake), - -1, sqlite3_free); - free(zFake); - } -} - -/* -** SQL function: shell_add_schema(S,X) -** -** Add the schema name X to the CREATE statement in S and return the result. -** Examples: -** -** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x); -** -** Also works on -** -** CREATE INDEX -** CREATE UNIQUE INDEX -** CREATE VIEW -** CREATE TRIGGER -** CREATE VIRTUAL TABLE -** -** This UDF is used by the .schema command to insert the schema name of -** attached databases into the middle of the sqlite_schema.sql field. -*/ -static void shellAddSchemaName( - sqlite3_context *pCtx, - int nVal, - sqlite3_value **apVal -){ - static const char *aPrefix[] = { - "TABLE", - "INDEX", - "UNIQUE INDEX", - "VIEW", - "TRIGGER", - "VIRTUAL TABLE" - }; - int i = 0; - const char *zIn = (const char*)sqlite3_value_text(apVal[0]); - const char *zSchema = (const char*)sqlite3_value_text(apVal[1]); - const char *zName = (const char*)sqlite3_value_text(apVal[2]); - sqlite3 *db = sqlite3_context_db_handle(pCtx); - UNUSED_PARAMETER(nVal); - if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){ - for(i=0; i -#include -#include -#include -#include -#include -#include - -/* -** We may need several defines that should have been in "sys/stat.h". -*/ - -#ifndef S_ISREG -#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) -#endif - -#ifndef S_ISDIR -#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) -#endif - -#ifndef S_ISLNK -#define S_ISLNK(mode) (0) -#endif - -/* -** We may need to provide the "mode_t" type. -*/ - -#ifndef MODE_T_DEFINED - #define MODE_T_DEFINED - typedef unsigned short mode_t; -#endif - -/* -** We may need to provide the "ino_t" type. -*/ - -#ifndef INO_T_DEFINED - #define INO_T_DEFINED - typedef unsigned short ino_t; -#endif - -/* -** We need to define "NAME_MAX" if it was not present in "limits.h". -*/ - -#ifndef NAME_MAX -# ifdef FILENAME_MAX -# define NAME_MAX (FILENAME_MAX) -# else -# define NAME_MAX (260) -# endif -#endif - -/* -** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T". -*/ - -#ifndef NULL_INTPTR_T -# define NULL_INTPTR_T ((intptr_t)(0)) -#endif - -#ifndef BAD_INTPTR_T -# define BAD_INTPTR_T ((intptr_t)(-1)) -#endif - -/* -** We need to provide the necessary structures and related types. -*/ - -#ifndef DIRENT_DEFINED -#define DIRENT_DEFINED -typedef struct DIRENT DIRENT; -typedef DIRENT *LPDIRENT; -struct DIRENT { - ino_t d_ino; /* Sequence number, do not use. */ - unsigned d_attributes; /* Win32 file attributes. */ - char d_name[NAME_MAX + 1]; /* Name within the directory. */ -}; -#endif - -#ifndef DIR_DEFINED -#define DIR_DEFINED -typedef struct DIR DIR; -typedef DIR *LPDIR; -struct DIR { - intptr_t d_handle; /* Value returned by "_findfirst". */ - DIRENT d_first; /* DIRENT constructed based on "_findfirst". */ - DIRENT d_next; /* DIRENT constructed based on "_findnext". */ -}; -#endif - -/* -** Provide a macro, for use by the implementation, to determine if a -** particular directory entry should be skipped over when searching for -** the next directory entry that should be returned by the readdir() or -** readdir_r() functions. -*/ - -#ifndef is_filtered -# define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM)) -#endif - -/* -** Provide the function prototype for the POSIX compatible getenv() -** function. This function is not thread-safe. -*/ - -extern const char *windirent_getenv(const char *name); - -/* -** Finally, we can provide the function prototypes for the opendir(), -** readdir(), readdir_r(), and closedir() POSIX functions. -*/ - -extern LPDIR opendir(const char *dirname); -extern LPDIRENT readdir(LPDIR dirp); -extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result); -extern INT closedir(LPDIR dirp); - -#endif /* defined(WIN32) && defined(_MSC_VER) */ - -/************************* End test_windirent.h ********************/ -/************************* Begin test_windirent.c ******************/ -/* -** 2015 November 30 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains code to implement most of the opendir() family of -** POSIX functions on Win32 using the MSVCRT. -*/ - -#if defined(_WIN32) && defined(_MSC_VER) -/* #include "test_windirent.h" */ - -/* -** Implementation of the POSIX getenv() function using the Win32 API. -** This function is not thread-safe. -*/ -const char *windirent_getenv( - const char *name -){ - static char value[32768]; /* Maximum length, per MSDN */ - DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */ - DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */ - - memset(value, 0, sizeof(value)); - dwRet = GetEnvironmentVariableA(name, value, dwSize); - if( dwRet==0 || dwRet>dwSize ){ - /* - ** The function call to GetEnvironmentVariableA() failed -OR- - ** the buffer is not large enough. Either way, return NULL. - */ - return 0; - }else{ - /* - ** The function call to GetEnvironmentVariableA() succeeded - ** -AND- the buffer contains the entire value. - */ - return value; - } -} - -/* -** Implementation of the POSIX opendir() function using the MSVCRT. -*/ -LPDIR opendir( - const char *dirname -){ - struct _finddata_t data; - LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR)); - SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]); - - if( dirp==NULL ) return NULL; - memset(dirp, 0, sizeof(DIR)); - - /* TODO: Remove this if Unix-style root paths are not used. */ - if( sqlite3_stricmp(dirname, "/")==0 ){ - dirname = windirent_getenv("SystemDrive"); - } - - memset(&data, 0, sizeof(struct _finddata_t)); - _snprintf(data.name, namesize, "%s\\*", dirname); - dirp->d_handle = _findfirst(data.name, &data); - - if( dirp->d_handle==BAD_INTPTR_T ){ - closedir(dirp); - return NULL; - } - - /* TODO: Remove this block to allow hidden and/or system files. */ - if( is_filtered(data) ){ -next: - - memset(&data, 0, sizeof(struct _finddata_t)); - if( _findnext(dirp->d_handle, &data)==-1 ){ - closedir(dirp); - return NULL; - } - - /* TODO: Remove this block to allow hidden and/or system files. */ - if( is_filtered(data) ) goto next; - } - - dirp->d_first.d_attributes = data.attrib; - strncpy(dirp->d_first.d_name, data.name, NAME_MAX); - dirp->d_first.d_name[NAME_MAX] = '\0'; - - return dirp; -} - -/* -** Implementation of the POSIX readdir() function using the MSVCRT. -*/ -LPDIRENT readdir( - LPDIR dirp -){ - struct _finddata_t data; - - if( dirp==NULL ) return NULL; - - if( dirp->d_first.d_ino==0 ){ - dirp->d_first.d_ino++; - dirp->d_next.d_ino++; - - return &dirp->d_first; - } - -next: - - memset(&data, 0, sizeof(struct _finddata_t)); - if( _findnext(dirp->d_handle, &data)==-1 ) return NULL; - - /* TODO: Remove this block to allow hidden and/or system files. */ - if( is_filtered(data) ) goto next; - - dirp->d_next.d_ino++; - dirp->d_next.d_attributes = data.attrib; - strncpy(dirp->d_next.d_name, data.name, NAME_MAX); - dirp->d_next.d_name[NAME_MAX] = '\0'; - - return &dirp->d_next; -} - -/* -** Implementation of the POSIX readdir_r() function using the MSVCRT. -*/ -INT readdir_r( - LPDIR dirp, - LPDIRENT entry, - LPDIRENT *result -){ - struct _finddata_t data; - - if( dirp==NULL ) return EBADF; - - if( dirp->d_first.d_ino==0 ){ - dirp->d_first.d_ino++; - dirp->d_next.d_ino++; - - entry->d_ino = dirp->d_first.d_ino; - entry->d_attributes = dirp->d_first.d_attributes; - strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX); - entry->d_name[NAME_MAX] = '\0'; - - *result = entry; - return 0; - } - -next: - - memset(&data, 0, sizeof(struct _finddata_t)); - if( _findnext(dirp->d_handle, &data)==-1 ){ - *result = NULL; - return ENOENT; - } - - /* TODO: Remove this block to allow hidden and/or system files. */ - if( is_filtered(data) ) goto next; - - entry->d_ino = (ino_t)-1; /* not available */ - entry->d_attributes = data.attrib; - strncpy(entry->d_name, data.name, NAME_MAX); - entry->d_name[NAME_MAX] = '\0'; - - *result = entry; - return 0; -} - -/* -** Implementation of the POSIX closedir() function using the MSVCRT. -*/ -INT closedir( - LPDIR dirp -){ - INT result = 0; - - if( dirp==NULL ) return EINVAL; - - if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){ - result = _findclose(dirp->d_handle); - } - - sqlite3_free(dirp); - return result; -} - -#endif /* defined(WIN32) && defined(_MSC_VER) */ - -/************************* End test_windirent.c ********************/ -#define dirent DIRENT -#endif -/************************* Begin ../ext/misc/memtrace.c ******************/ -/* -** 2019-01-21 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file implements an extension that uses the SQLITE_CONFIG_MALLOC -** mechanism to add a tracing layer on top of SQLite. If this extension -** is registered prior to sqlite3_initialize(), it will cause all memory -** allocation activities to be logged on standard output, or to some other -** FILE specified by the initializer. -** -** This file needs to be compiled into the application that uses it. -** -** This extension is used to implement the --memtrace option of the -** command-line shell. -*/ -#include -#include -#include - -/* The original memory allocation routines */ -static sqlite3_mem_methods memtraceBase; -static FILE *memtraceOut; - -/* Methods that trace memory allocations */ -static void *memtraceMalloc(int n){ - if( memtraceOut ){ - fprintf(memtraceOut, "MEMTRACE: allocate %d bytes\n", - memtraceBase.xRoundup(n)); - } - return memtraceBase.xMalloc(n); -} -static void memtraceFree(void *p){ - if( p==0 ) return; - if( memtraceOut ){ - fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p)); - } - memtraceBase.xFree(p); -} -static void *memtraceRealloc(void *p, int n){ - if( p==0 ) return memtraceMalloc(n); - if( n==0 ){ - memtraceFree(p); - return 0; - } - if( memtraceOut ){ - fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n", - memtraceBase.xSize(p), memtraceBase.xRoundup(n)); - } - return memtraceBase.xRealloc(p, n); -} -static int memtraceSize(void *p){ - return memtraceBase.xSize(p); -} -static int memtraceRoundup(int n){ - return memtraceBase.xRoundup(n); -} -static int memtraceInit(void *p){ - return memtraceBase.xInit(p); -} -static void memtraceShutdown(void *p){ - memtraceBase.xShutdown(p); -} - -/* The substitute memory allocator */ -static sqlite3_mem_methods ersaztMethods = { - memtraceMalloc, - memtraceFree, - memtraceRealloc, - memtraceSize, - memtraceRoundup, - memtraceInit, - memtraceShutdown, - 0 -}; - -/* Begin tracing memory allocations to out. */ -int sqlite3MemTraceActivate(FILE *out){ - int rc = SQLITE_OK; - if( memtraceBase.xMalloc==0 ){ - rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase); - if( rc==SQLITE_OK ){ - rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods); - } - } - memtraceOut = out; - return rc; -} - -/* Deactivate memory tracing */ -int sqlite3MemTraceDeactivate(void){ - int rc = SQLITE_OK; - if( memtraceBase.xMalloc!=0 ){ - rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase); - if( rc==SQLITE_OK ){ - memset(&memtraceBase, 0, sizeof(memtraceBase)); - } - } - memtraceOut = 0; - return rc; -} - -/************************* End ../ext/misc/memtrace.c ********************/ -/************************* Begin ../ext/misc/pcachetrace.c ******************/ -/* -** 2023-06-21 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file implements an extension that uses the SQLITE_CONFIG_PCACHE2 -** mechanism to add a tracing layer on top of pluggable page cache of -** SQLite. If this extension is registered prior to sqlite3_initialize(), -** it will cause all page cache activities to be logged on standard output, -** or to some other FILE specified by the initializer. -** -** This file needs to be compiled into the application that uses it. -** -** This extension is used to implement the --pcachetrace option of the -** command-line shell. -*/ -#include -#include -#include - -/* The original page cache routines */ -static sqlite3_pcache_methods2 pcacheBase; -static FILE *pcachetraceOut; - -/* Methods that trace pcache activity */ -static int pcachetraceInit(void *pArg){ - int nRes; - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p)\n", pArg); - } - nRes = pcacheBase.xInit(pArg); - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xInit(%p) -> %d\n", pArg, nRes); - } - return nRes; -} -static void pcachetraceShutdown(void *pArg){ - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xShutdown(%p)\n", pArg); - } - pcacheBase.xShutdown(pArg); -} -static sqlite3_pcache *pcachetraceCreate(int szPage, int szExtra, int bPurge){ - sqlite3_pcache *pRes; - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d)\n", - szPage, szExtra, bPurge); - } - pRes = pcacheBase.xCreate(szPage, szExtra, bPurge); - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xCreate(%d,%d,%d) -> %p\n", - szPage, szExtra, bPurge, pRes); - } - return pRes; -} -static void pcachetraceCachesize(sqlite3_pcache *p, int nCachesize){ - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xCachesize(%p, %d)\n", p, nCachesize); - } - pcacheBase.xCachesize(p, nCachesize); -} -static int pcachetracePagecount(sqlite3_pcache *p){ - int nRes; - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p)\n", p); - } - nRes = pcacheBase.xPagecount(p); - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xPagecount(%p) -> %d\n", p, nRes); - } - return nRes; -} -static sqlite3_pcache_page *pcachetraceFetch( - sqlite3_pcache *p, - unsigned key, - int crFg -){ - sqlite3_pcache_page *pRes; - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d)\n", p, key, crFg); - } - pRes = pcacheBase.xFetch(p, key, crFg); - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xFetch(%p,%u,%d) -> %p\n", - p, key, crFg, pRes); - } - return pRes; -} -static void pcachetraceUnpin( - sqlite3_pcache *p, - sqlite3_pcache_page *pPg, - int bDiscard -){ - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xUnpin(%p, %p, %d)\n", - p, pPg, bDiscard); - } - pcacheBase.xUnpin(p, pPg, bDiscard); -} -static void pcachetraceRekey( - sqlite3_pcache *p, - sqlite3_pcache_page *pPg, - unsigned oldKey, - unsigned newKey -){ - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xRekey(%p, %p, %u, %u)\n", - p, pPg, oldKey, newKey); - } - pcacheBase.xRekey(p, pPg, oldKey, newKey); -} -static void pcachetraceTruncate(sqlite3_pcache *p, unsigned n){ - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xTruncate(%p, %u)\n", p, n); - } - pcacheBase.xTruncate(p, n); -} -static void pcachetraceDestroy(sqlite3_pcache *p){ - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xDestroy(%p)\n", p); - } - pcacheBase.xDestroy(p); -} -static void pcachetraceShrink(sqlite3_pcache *p){ - if( pcachetraceOut ){ - fprintf(pcachetraceOut, "PCACHETRACE: xShrink(%p)\n", p); - } - pcacheBase.xShrink(p); -} - -/* The substitute pcache methods */ -static sqlite3_pcache_methods2 ersaztPcacheMethods = { - 0, - 0, - pcachetraceInit, - pcachetraceShutdown, - pcachetraceCreate, - pcachetraceCachesize, - pcachetracePagecount, - pcachetraceFetch, - pcachetraceUnpin, - pcachetraceRekey, - pcachetraceTruncate, - pcachetraceDestroy, - pcachetraceShrink -}; - -/* Begin tracing memory allocations to out. */ -int sqlite3PcacheTraceActivate(FILE *out){ - int rc = SQLITE_OK; - if( pcacheBase.xFetch==0 ){ - rc = sqlite3_config(SQLITE_CONFIG_GETPCACHE2, &pcacheBase); - if( rc==SQLITE_OK ){ - rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &ersaztPcacheMethods); - } - } - pcachetraceOut = out; - return rc; -} - -/* Deactivate memory tracing */ -int sqlite3PcacheTraceDeactivate(void){ - int rc = SQLITE_OK; - if( pcacheBase.xFetch!=0 ){ - rc = sqlite3_config(SQLITE_CONFIG_PCACHE2, &pcacheBase); - if( rc==SQLITE_OK ){ - memset(&pcacheBase, 0, sizeof(pcacheBase)); - } - } - pcachetraceOut = 0; - return rc; -} - -/************************* End ../ext/misc/pcachetrace.c ********************/ -/************************* Begin ../ext/misc/shathree.c ******************/ -/* -** 2017-03-08 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This SQLite extension implements functions that compute SHA3 hashes -** in the way described by the (U.S.) NIST FIPS 202 SHA-3 Standard. -** Two SQL functions are implemented: -** -** sha3(X,SIZE) -** sha3_agg(Y,SIZE) -** sha3_query(Z,SIZE) -** -** The sha3(X) function computes the SHA3 hash of the input X, or NULL if -** X is NULL. If inputs X is text, the UTF-8 rendering of that text is -** used to compute the hash. If X is a BLOB, then the binary data of the -** blob is used to compute the hash. If X is an integer or real number, -** then that number if converted into UTF-8 text and the hash is computed -** over the text. -** -** The sha3_agg(Y) function computes the SHA3 hash of all Y inputs. Since -** order is important for the hash, it is recommended that the Y expression -** by followed by an ORDER BY clause to guarantee that the inputs occur -** in the desired order. -** -** The sha3_query(Y) function evaluates all queries in the SQL statements of Y -** and returns a hash of their results. -** -** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm -** is used. If SIZE is included it must be one of the integers 224, 256, -** 384, or 512, to determine SHA3 hash variant that is computed. -** -** Because the sha3_agg() and sha3_query() functions compute a hash over -** multiple values, the values are encode to use include type information. -** -** In sha3_agg(), the sequence of bytes that gets hashed for each input -** Y depends on the datatype of Y: -** -** typeof(Y)='null' A single "N" is hashed. (One byte) -** -** typeof(Y)='integer' The data hash is the character "I" followed -** by an 8-byte big-endian binary of the -** 64-bit signed integer. (Nine bytes total.) -** -** typeof(Y)='real' The character "F" followed by an 8-byte -** big-ending binary of the double. (Nine -** bytes total.) -** -** typeof(Y)='text' The hash is over prefix "Tnnn:" followed -** by the UTF8 encoding of the text. The "nnn" -** in the prefix is the minimum-length decimal -** representation of the octet_length of the text. -** Notice the ":" at the end of the prefix, which -** is needed to separate the prefix from the -** content in cases where the content starts -** with a digit. -** -** typeof(Y)='blob' The hash is taken over prefix "Bnnn:" followed -** by the binary content of the blob. The "nnn" -** in the prefix is the mimimum-length decimal -** representation of the byte-length of the blob. -** -** According to the rules above, all of the following SELECT statements -** should return TRUE: -** -** SELECT sha3(1) = sha3('1'); -** -** SELECT sha3('hello') = sha3(x'68656c6c6f'); -** -** WITH a(x) AS (VALUES('xyzzy')) -** SELECT sha3_agg(x) = sha3('T5:xyzzy') FROM a; -** -** WITH a(x) AS (VALUES(x'010203')) -** SELECT sha3_agg(x) = sha3(x'42333a010203') FROM a; -** -** WITH a(x) AS (VALUES(0x123456)) -** SELECT sha3_agg(x) = sha3(x'490000000000123456') FROM a; -** -** WITH a(x) AS (VALUES(100.015625)) -** SELECT sha3_agg(x) = sha3(x'464059010000000000') FROM a; -** -** WITH a(x) AS (VALUES(NULL)) -** SELECT sha3_agg(x) = sha3('N') FROM a; -** -** -** In sha3_query(), individual column values are encoded as with -** sha3_agg(), but with the addition that a single "R" character is -** inserted at the start of each row. -** -** Note that sha3_agg() hashes rows for which Y is NULL. Add a FILTER -** clause if NULL rows should be excluded: -** -** SELECT sha3_agg(x ORDER BY rowid) FILTER(WHERE x NOT NULL) FROM t1; -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include -#include - -#ifndef SQLITE_AMALGAMATION -/* typedef sqlite3_uint64 u64; */ -#endif /* SQLITE_AMALGAMATION */ - -/****************************************************************************** -** The Hash Engine -*/ -/* -** Macros to determine whether the machine is big or little endian, -** and whether or not that determination is run-time or compile-time. -** -** For best performance, an attempt is made to guess at the byte-order -** using C-preprocessor macros. If that is unsuccessful, or if -** -DSHA3_BYTEORDER=0 is set, then byte-order is determined -** at run-time. -*/ -#ifndef SHA3_BYTEORDER -# if defined(i386) || defined(__i386__) || defined(_M_IX86) || \ - defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ - defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \ - defined(__arm__) -# define SHA3_BYTEORDER 1234 -# elif defined(sparc) || defined(__ppc__) -# define SHA3_BYTEORDER 4321 -# else -# define SHA3_BYTEORDER 0 -# endif -#endif - - -/* -** State structure for a SHA3 hash in progress -*/ -typedef struct SHA3Context SHA3Context; -struct SHA3Context { - union { - u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */ - unsigned char x[1600]; /* ... or 1600 bytes */ - } u; - unsigned nRate; /* Bytes of input accepted per Keccak iteration */ - unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */ - unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */ - unsigned iSize; /* 224, 256, 358, or 512 */ -}; - -/* -** A single step of the Keccak mixing function for a 1600-bit state -*/ -static void KeccakF1600Step(SHA3Context *p){ - int i; - u64 b0, b1, b2, b3, b4; - u64 c0, c1, c2, c3, c4; - u64 d0, d1, d2, d3, d4; - static const u64 RC[] = { - 0x0000000000000001ULL, 0x0000000000008082ULL, - 0x800000000000808aULL, 0x8000000080008000ULL, - 0x000000000000808bULL, 0x0000000080000001ULL, - 0x8000000080008081ULL, 0x8000000000008009ULL, - 0x000000000000008aULL, 0x0000000000000088ULL, - 0x0000000080008009ULL, 0x000000008000000aULL, - 0x000000008000808bULL, 0x800000000000008bULL, - 0x8000000000008089ULL, 0x8000000000008003ULL, - 0x8000000000008002ULL, 0x8000000000000080ULL, - 0x000000000000800aULL, 0x800000008000000aULL, - 0x8000000080008081ULL, 0x8000000000008080ULL, - 0x0000000080000001ULL, 0x8000000080008008ULL - }; -# define a00 (p->u.s[0]) -# define a01 (p->u.s[1]) -# define a02 (p->u.s[2]) -# define a03 (p->u.s[3]) -# define a04 (p->u.s[4]) -# define a10 (p->u.s[5]) -# define a11 (p->u.s[6]) -# define a12 (p->u.s[7]) -# define a13 (p->u.s[8]) -# define a14 (p->u.s[9]) -# define a20 (p->u.s[10]) -# define a21 (p->u.s[11]) -# define a22 (p->u.s[12]) -# define a23 (p->u.s[13]) -# define a24 (p->u.s[14]) -# define a30 (p->u.s[15]) -# define a31 (p->u.s[16]) -# define a32 (p->u.s[17]) -# define a33 (p->u.s[18]) -# define a34 (p->u.s[19]) -# define a40 (p->u.s[20]) -# define a41 (p->u.s[21]) -# define a42 (p->u.s[22]) -# define a43 (p->u.s[23]) -# define a44 (p->u.s[24]) -# define ROL64(a,x) ((a<>(64-x))) - - for(i=0; i<24; i+=4){ - c0 = a00^a10^a20^a30^a40; - c1 = a01^a11^a21^a31^a41; - c2 = a02^a12^a22^a32^a42; - c3 = a03^a13^a23^a33^a43; - c4 = a04^a14^a24^a34^a44; - d0 = c4^ROL64(c1, 1); - d1 = c0^ROL64(c2, 1); - d2 = c1^ROL64(c3, 1); - d3 = c2^ROL64(c4, 1); - d4 = c3^ROL64(c0, 1); - - b0 = (a00^d0); - b1 = ROL64((a11^d1), 44); - b2 = ROL64((a22^d2), 43); - b3 = ROL64((a33^d3), 21); - b4 = ROL64((a44^d4), 14); - a00 = b0 ^((~b1)& b2 ); - a00 ^= RC[i]; - a11 = b1 ^((~b2)& b3 ); - a22 = b2 ^((~b3)& b4 ); - a33 = b3 ^((~b4)& b0 ); - a44 = b4 ^((~b0)& b1 ); - - b2 = ROL64((a20^d0), 3); - b3 = ROL64((a31^d1), 45); - b4 = ROL64((a42^d2), 61); - b0 = ROL64((a03^d3), 28); - b1 = ROL64((a14^d4), 20); - a20 = b0 ^((~b1)& b2 ); - a31 = b1 ^((~b2)& b3 ); - a42 = b2 ^((~b3)& b4 ); - a03 = b3 ^((~b4)& b0 ); - a14 = b4 ^((~b0)& b1 ); - - b4 = ROL64((a40^d0), 18); - b0 = ROL64((a01^d1), 1); - b1 = ROL64((a12^d2), 6); - b2 = ROL64((a23^d3), 25); - b3 = ROL64((a34^d4), 8); - a40 = b0 ^((~b1)& b2 ); - a01 = b1 ^((~b2)& b3 ); - a12 = b2 ^((~b3)& b4 ); - a23 = b3 ^((~b4)& b0 ); - a34 = b4 ^((~b0)& b1 ); - - b1 = ROL64((a10^d0), 36); - b2 = ROL64((a21^d1), 10); - b3 = ROL64((a32^d2), 15); - b4 = ROL64((a43^d3), 56); - b0 = ROL64((a04^d4), 27); - a10 = b0 ^((~b1)& b2 ); - a21 = b1 ^((~b2)& b3 ); - a32 = b2 ^((~b3)& b4 ); - a43 = b3 ^((~b4)& b0 ); - a04 = b4 ^((~b0)& b1 ); - - b3 = ROL64((a30^d0), 41); - b4 = ROL64((a41^d1), 2); - b0 = ROL64((a02^d2), 62); - b1 = ROL64((a13^d3), 55); - b2 = ROL64((a24^d4), 39); - a30 = b0 ^((~b1)& b2 ); - a41 = b1 ^((~b2)& b3 ); - a02 = b2 ^((~b3)& b4 ); - a13 = b3 ^((~b4)& b0 ); - a24 = b4 ^((~b0)& b1 ); - - c0 = a00^a20^a40^a10^a30; - c1 = a11^a31^a01^a21^a41; - c2 = a22^a42^a12^a32^a02; - c3 = a33^a03^a23^a43^a13; - c4 = a44^a14^a34^a04^a24; - d0 = c4^ROL64(c1, 1); - d1 = c0^ROL64(c2, 1); - d2 = c1^ROL64(c3, 1); - d3 = c2^ROL64(c4, 1); - d4 = c3^ROL64(c0, 1); - - b0 = (a00^d0); - b1 = ROL64((a31^d1), 44); - b2 = ROL64((a12^d2), 43); - b3 = ROL64((a43^d3), 21); - b4 = ROL64((a24^d4), 14); - a00 = b0 ^((~b1)& b2 ); - a00 ^= RC[i+1]; - a31 = b1 ^((~b2)& b3 ); - a12 = b2 ^((~b3)& b4 ); - a43 = b3 ^((~b4)& b0 ); - a24 = b4 ^((~b0)& b1 ); - - b2 = ROL64((a40^d0), 3); - b3 = ROL64((a21^d1), 45); - b4 = ROL64((a02^d2), 61); - b0 = ROL64((a33^d3), 28); - b1 = ROL64((a14^d4), 20); - a40 = b0 ^((~b1)& b2 ); - a21 = b1 ^((~b2)& b3 ); - a02 = b2 ^((~b3)& b4 ); - a33 = b3 ^((~b4)& b0 ); - a14 = b4 ^((~b0)& b1 ); - - b4 = ROL64((a30^d0), 18); - b0 = ROL64((a11^d1), 1); - b1 = ROL64((a42^d2), 6); - b2 = ROL64((a23^d3), 25); - b3 = ROL64((a04^d4), 8); - a30 = b0 ^((~b1)& b2 ); - a11 = b1 ^((~b2)& b3 ); - a42 = b2 ^((~b3)& b4 ); - a23 = b3 ^((~b4)& b0 ); - a04 = b4 ^((~b0)& b1 ); - - b1 = ROL64((a20^d0), 36); - b2 = ROL64((a01^d1), 10); - b3 = ROL64((a32^d2), 15); - b4 = ROL64((a13^d3), 56); - b0 = ROL64((a44^d4), 27); - a20 = b0 ^((~b1)& b2 ); - a01 = b1 ^((~b2)& b3 ); - a32 = b2 ^((~b3)& b4 ); - a13 = b3 ^((~b4)& b0 ); - a44 = b4 ^((~b0)& b1 ); - - b3 = ROL64((a10^d0), 41); - b4 = ROL64((a41^d1), 2); - b0 = ROL64((a22^d2), 62); - b1 = ROL64((a03^d3), 55); - b2 = ROL64((a34^d4), 39); - a10 = b0 ^((~b1)& b2 ); - a41 = b1 ^((~b2)& b3 ); - a22 = b2 ^((~b3)& b4 ); - a03 = b3 ^((~b4)& b0 ); - a34 = b4 ^((~b0)& b1 ); - - c0 = a00^a40^a30^a20^a10; - c1 = a31^a21^a11^a01^a41; - c2 = a12^a02^a42^a32^a22; - c3 = a43^a33^a23^a13^a03; - c4 = a24^a14^a04^a44^a34; - d0 = c4^ROL64(c1, 1); - d1 = c0^ROL64(c2, 1); - d2 = c1^ROL64(c3, 1); - d3 = c2^ROL64(c4, 1); - d4 = c3^ROL64(c0, 1); - - b0 = (a00^d0); - b1 = ROL64((a21^d1), 44); - b2 = ROL64((a42^d2), 43); - b3 = ROL64((a13^d3), 21); - b4 = ROL64((a34^d4), 14); - a00 = b0 ^((~b1)& b2 ); - a00 ^= RC[i+2]; - a21 = b1 ^((~b2)& b3 ); - a42 = b2 ^((~b3)& b4 ); - a13 = b3 ^((~b4)& b0 ); - a34 = b4 ^((~b0)& b1 ); - - b2 = ROL64((a30^d0), 3); - b3 = ROL64((a01^d1), 45); - b4 = ROL64((a22^d2), 61); - b0 = ROL64((a43^d3), 28); - b1 = ROL64((a14^d4), 20); - a30 = b0 ^((~b1)& b2 ); - a01 = b1 ^((~b2)& b3 ); - a22 = b2 ^((~b3)& b4 ); - a43 = b3 ^((~b4)& b0 ); - a14 = b4 ^((~b0)& b1 ); - - b4 = ROL64((a10^d0), 18); - b0 = ROL64((a31^d1), 1); - b1 = ROL64((a02^d2), 6); - b2 = ROL64((a23^d3), 25); - b3 = ROL64((a44^d4), 8); - a10 = b0 ^((~b1)& b2 ); - a31 = b1 ^((~b2)& b3 ); - a02 = b2 ^((~b3)& b4 ); - a23 = b3 ^((~b4)& b0 ); - a44 = b4 ^((~b0)& b1 ); - - b1 = ROL64((a40^d0), 36); - b2 = ROL64((a11^d1), 10); - b3 = ROL64((a32^d2), 15); - b4 = ROL64((a03^d3), 56); - b0 = ROL64((a24^d4), 27); - a40 = b0 ^((~b1)& b2 ); - a11 = b1 ^((~b2)& b3 ); - a32 = b2 ^((~b3)& b4 ); - a03 = b3 ^((~b4)& b0 ); - a24 = b4 ^((~b0)& b1 ); - - b3 = ROL64((a20^d0), 41); - b4 = ROL64((a41^d1), 2); - b0 = ROL64((a12^d2), 62); - b1 = ROL64((a33^d3), 55); - b2 = ROL64((a04^d4), 39); - a20 = b0 ^((~b1)& b2 ); - a41 = b1 ^((~b2)& b3 ); - a12 = b2 ^((~b3)& b4 ); - a33 = b3 ^((~b4)& b0 ); - a04 = b4 ^((~b0)& b1 ); - - c0 = a00^a30^a10^a40^a20; - c1 = a21^a01^a31^a11^a41; - c2 = a42^a22^a02^a32^a12; - c3 = a13^a43^a23^a03^a33; - c4 = a34^a14^a44^a24^a04; - d0 = c4^ROL64(c1, 1); - d1 = c0^ROL64(c2, 1); - d2 = c1^ROL64(c3, 1); - d3 = c2^ROL64(c4, 1); - d4 = c3^ROL64(c0, 1); - - b0 = (a00^d0); - b1 = ROL64((a01^d1), 44); - b2 = ROL64((a02^d2), 43); - b3 = ROL64((a03^d3), 21); - b4 = ROL64((a04^d4), 14); - a00 = b0 ^((~b1)& b2 ); - a00 ^= RC[i+3]; - a01 = b1 ^((~b2)& b3 ); - a02 = b2 ^((~b3)& b4 ); - a03 = b3 ^((~b4)& b0 ); - a04 = b4 ^((~b0)& b1 ); - - b2 = ROL64((a10^d0), 3); - b3 = ROL64((a11^d1), 45); - b4 = ROL64((a12^d2), 61); - b0 = ROL64((a13^d3), 28); - b1 = ROL64((a14^d4), 20); - a10 = b0 ^((~b1)& b2 ); - a11 = b1 ^((~b2)& b3 ); - a12 = b2 ^((~b3)& b4 ); - a13 = b3 ^((~b4)& b0 ); - a14 = b4 ^((~b0)& b1 ); - - b4 = ROL64((a20^d0), 18); - b0 = ROL64((a21^d1), 1); - b1 = ROL64((a22^d2), 6); - b2 = ROL64((a23^d3), 25); - b3 = ROL64((a24^d4), 8); - a20 = b0 ^((~b1)& b2 ); - a21 = b1 ^((~b2)& b3 ); - a22 = b2 ^((~b3)& b4 ); - a23 = b3 ^((~b4)& b0 ); - a24 = b4 ^((~b0)& b1 ); - - b1 = ROL64((a30^d0), 36); - b2 = ROL64((a31^d1), 10); - b3 = ROL64((a32^d2), 15); - b4 = ROL64((a33^d3), 56); - b0 = ROL64((a34^d4), 27); - a30 = b0 ^((~b1)& b2 ); - a31 = b1 ^((~b2)& b3 ); - a32 = b2 ^((~b3)& b4 ); - a33 = b3 ^((~b4)& b0 ); - a34 = b4 ^((~b0)& b1 ); - - b3 = ROL64((a40^d0), 41); - b4 = ROL64((a41^d1), 2); - b0 = ROL64((a42^d2), 62); - b1 = ROL64((a43^d3), 55); - b2 = ROL64((a44^d4), 39); - a40 = b0 ^((~b1)& b2 ); - a41 = b1 ^((~b2)& b3 ); - a42 = b2 ^((~b3)& b4 ); - a43 = b3 ^((~b4)& b0 ); - a44 = b4 ^((~b0)& b1 ); - } -} - -/* -** Initialize a new hash. iSize determines the size of the hash -** in bits and should be one of 224, 256, 384, or 512. Or iSize -** can be zero to use the default hash size of 256 bits. -*/ -static void SHA3Init(SHA3Context *p, int iSize){ - memset(p, 0, sizeof(*p)); - p->iSize = iSize; - if( iSize>=128 && iSize<=512 ){ - p->nRate = (1600 - ((iSize + 31)&~31)*2)/8; - }else{ - p->nRate = (1600 - 2*256)/8; - } -#if SHA3_BYTEORDER==1234 - /* Known to be little-endian at compile-time. No-op */ -#elif SHA3_BYTEORDER==4321 - p->ixMask = 7; /* Big-endian */ -#else - { - static unsigned int one = 1; - if( 1==*(unsigned char*)&one ){ - /* Little endian. No byte swapping. */ - p->ixMask = 0; - }else{ - /* Big endian. Byte swap. */ - p->ixMask = 7; - } - } -#endif -} - -/* -** Make consecutive calls to the SHA3Update function to add new content -** to the hash -*/ -static void SHA3Update( - SHA3Context *p, - const unsigned char *aData, - unsigned int nData -){ - unsigned int i = 0; - if( aData==0 ) return; -#if SHA3_BYTEORDER==1234 - if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){ - for(; i+7u.s[p->nLoaded/8] ^= *(u64*)&aData[i]; - p->nLoaded += 8; - if( p->nLoaded>=p->nRate ){ - KeccakF1600Step(p); - p->nLoaded = 0; - } - } - } -#endif - for(; iu.x[p->nLoaded] ^= aData[i]; -#elif SHA3_BYTEORDER==4321 - p->u.x[p->nLoaded^0x07] ^= aData[i]; -#else - p->u.x[p->nLoaded^p->ixMask] ^= aData[i]; -#endif - p->nLoaded++; - if( p->nLoaded==p->nRate ){ - KeccakF1600Step(p); - p->nLoaded = 0; - } - } -} - -/* -** After all content has been added, invoke SHA3Final() to compute -** the final hash. The function returns a pointer to the binary -** hash value. -*/ -static unsigned char *SHA3Final(SHA3Context *p){ - unsigned int i; - if( p->nLoaded==p->nRate-1 ){ - const unsigned char c1 = 0x86; - SHA3Update(p, &c1, 1); - }else{ - const unsigned char c2 = 0x06; - const unsigned char c3 = 0x80; - SHA3Update(p, &c2, 1); - p->nLoaded = p->nRate - 1; - SHA3Update(p, &c3, 1); - } - for(i=0; inRate; i++){ - p->u.x[i+p->nRate] = p->u.x[i^p->ixMask]; - } - return &p->u.x[p->nRate]; -} -/* End of the hashing logic -*****************************************************************************/ - -/* -** Implementation of the sha3(X,SIZE) function. -** -** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default -** size is 256. If X is a BLOB, it is hashed as is. -** For all other non-NULL types of input, X is converted into a UTF-8 string -** and the string is hashed without the trailing 0x00 terminator. The hash -** of a NULL value is NULL. -*/ -static void sha3Func( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - SHA3Context cx; - int eType = sqlite3_value_type(argv[0]); - int nByte = sqlite3_value_bytes(argv[0]); - int iSize; - if( argc==1 ){ - iSize = 256; - }else{ - iSize = sqlite3_value_int(argv[1]); - if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){ - sqlite3_result_error(context, "SHA3 size should be one of: 224 256 " - "384 512", -1); - return; - } - } - if( eType==SQLITE_NULL ) return; - SHA3Init(&cx, iSize); - if( eType==SQLITE_BLOB ){ - SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte); - }else{ - SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte); - } - sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT); -} - -/* Compute a string using sqlite3_vsnprintf() with a maximum length -** of 50 bytes and add it to the hash. -*/ -static void sha3_step_vformat( - SHA3Context *p, /* Add content to this context */ - const char *zFormat, - ... -){ - va_list ap; - int n; - char zBuf[50]; - va_start(ap, zFormat); - sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap); - va_end(ap); - n = (int)strlen(zBuf); - SHA3Update(p, (unsigned char*)zBuf, n); -} - -/* -** Update a SHA3Context using a single sqlite3_value. -*/ -static void sha3UpdateFromValue(SHA3Context *p, sqlite3_value *pVal){ - switch( sqlite3_value_type(pVal) ){ - case SQLITE_NULL: { - SHA3Update(p, (const unsigned char*)"N",1); - break; - } - case SQLITE_INTEGER: { - sqlite3_uint64 u; - int j; - unsigned char x[9]; - sqlite3_int64 v = sqlite3_value_int64(pVal); - memcpy(&u, &v, 8); - for(j=8; j>=1; j--){ - x[j] = u & 0xff; - u >>= 8; - } - x[0] = 'I'; - SHA3Update(p, x, 9); - break; - } - case SQLITE_FLOAT: { - sqlite3_uint64 u; - int j; - unsigned char x[9]; - double r = sqlite3_value_double(pVal); - memcpy(&u, &r, 8); - for(j=8; j>=1; j--){ - x[j] = u & 0xff; - u >>= 8; - } - x[0] = 'F'; - SHA3Update(p,x,9); - break; - } - case SQLITE_TEXT: { - int n2 = sqlite3_value_bytes(pVal); - const unsigned char *z2 = sqlite3_value_text(pVal); - sha3_step_vformat(p,"T%d:",n2); - SHA3Update(p, z2, n2); - break; - } - case SQLITE_BLOB: { - int n2 = sqlite3_value_bytes(pVal); - const unsigned char *z2 = sqlite3_value_blob(pVal); - sha3_step_vformat(p,"B%d:",n2); - SHA3Update(p, z2, n2); - break; - } - } -} - -/* -** Implementation of the sha3_query(SQL,SIZE) function. -** -** This function compiles and runs the SQL statement(s) given in the -** argument. The results are hashed using a SIZE-bit SHA3. The default -** size is 256. -** -** The format of the byte stream that is hashed is summarized as follows: -** -** S: -** R -** N -** I -** F -** B: -** T: -** -** is the original SQL text for each statement run and is -** the size of that text. The SQL text is UTF-8. A single R character -** occurs before the start of each row. N means a NULL value. -** I mean an 8-byte little-endian integer . F is a floating point -** number with an 8-byte little-endian IEEE floating point value . -** B means blobs of bytes. T means text rendered as -** bytes of UTF-8. The and values are expressed as an ASCII -** text integers. -** -** For each SQL statement in the X input, there is one S segment. Each -** S segment is followed by zero or more R segments, one for each row in the -** result set. After each R, there are one or more N, I, F, B, or T segments, -** one for each column in the result set. Segments are concatentated directly -** with no delimiters of any kind. -*/ -static void sha3QueryFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - sqlite3 *db = sqlite3_context_db_handle(context); - const char *zSql = (const char*)sqlite3_value_text(argv[0]); - sqlite3_stmt *pStmt = 0; - int nCol; /* Number of columns in the result set */ - int i; /* Loop counter */ - int rc; - int n; - const char *z; - SHA3Context cx; - int iSize; - - if( argc==1 ){ - iSize = 256; - }else{ - iSize = sqlite3_value_int(argv[1]); - if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){ - sqlite3_result_error(context, "SHA3 size should be one of: 224 256 " - "384 512", -1); - return; - } - } - if( zSql==0 ) return; - SHA3Init(&cx, iSize); - while( zSql[0] ){ - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql); - if( rc ){ - char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s", - zSql, sqlite3_errmsg(db)); - sqlite3_finalize(pStmt); - sqlite3_result_error(context, zMsg, -1); - sqlite3_free(zMsg); - return; - } - if( !sqlite3_stmt_readonly(pStmt) ){ - char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt)); - sqlite3_finalize(pStmt); - sqlite3_result_error(context, zMsg, -1); - sqlite3_free(zMsg); - return; - } - nCol = sqlite3_column_count(pStmt); - z = sqlite3_sql(pStmt); - if( z ){ - n = (int)strlen(z); - sha3_step_vformat(&cx,"S%d:",n); - SHA3Update(&cx,(unsigned char*)z,n); - } - - /* Compute a hash over the result of the query */ - while( SQLITE_ROW==sqlite3_step(pStmt) ){ - SHA3Update(&cx,(const unsigned char*)"R",1); - for(i=0; inRate==0 ){ - int sz = 256; - if( argc==2 ){ - sz = sqlite3_value_int(argv[1]); - if( sz!=224 && sz!=384 && sz!=512 ){ - sz = 256; - } - } - SHA3Init(p, sz); - } - sha3UpdateFromValue(p, argv[0]); -} - - -/* -** xFinal function for sha3_agg(). -*/ -static void sha3AggFinal(sqlite3_context *context){ - SHA3Context *p; - p = (SHA3Context*)sqlite3_aggregate_context(context, sizeof(*p)); - if( p==0 ) return; - if( p->iSize ){ - sqlite3_result_blob(context, SHA3Final(p), p->iSize/8, SQLITE_TRANSIENT); - } -} - - - -#ifdef _WIN32 - -#endif -int sqlite3_shathree_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; /* Unused parameter */ - rc = sqlite3_create_function(db, "sha3", 1, - SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, - 0, sha3Func, 0, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "sha3", 2, - SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, - 0, sha3Func, 0, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "sha3_agg", 1, - SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, - 0, 0, sha3AggStep, sha3AggFinal); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "sha3_agg", 2, - SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, - 0, 0, sha3AggStep, sha3AggFinal); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "sha3_query", 1, - SQLITE_UTF8 | SQLITE_DIRECTONLY, - 0, sha3QueryFunc, 0, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "sha3_query", 2, - SQLITE_UTF8 | SQLITE_DIRECTONLY, - 0, sha3QueryFunc, 0, 0); - } - return rc; -} - -/************************* End ../ext/misc/shathree.c ********************/ -/************************* Begin ../ext/misc/sha1.c ******************/ -/* -** 2017-01-27 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This SQLite extension implements functions that compute SHA1 hashes. -** Two SQL functions are implemented: -** -** sha1(X) -** sha1_query(Y) -** -** The sha1(X) function computes the SHA1 hash of the input X, or NULL if -** X is NULL. -** -** The sha1_query(Y) function evalutes all queries in the SQL statements of Y -** and returns a hash of their results. -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include -#include - -/****************************************************************************** -** The Hash Engine -*/ -/* Context for the SHA1 hash */ -typedef struct SHA1Context SHA1Context; -struct SHA1Context { - unsigned int state[5]; - unsigned int count[2]; - unsigned char buffer[64]; -}; - -#define SHA_ROT(x,l,r) ((x) << (l) | (x) >> (r)) -#define rol(x,k) SHA_ROT(x,k,32-(k)) -#define ror(x,k) SHA_ROT(x,32-(k),k) - -#define blk0le(i) (block[i] = (ror(block[i],8)&0xFF00FF00) \ - |(rol(block[i],8)&0x00FF00FF)) -#define blk0be(i) block[i] -#define blk(i) (block[i&15] = rol(block[(i+13)&15]^block[(i+8)&15] \ - ^block[(i+2)&15]^block[i&15],1)) - -/* - * (R0+R1), R2, R3, R4 are the different operations (rounds) used in SHA1 - * - * Rl0() for little-endian and Rb0() for big-endian. Endianness is - * determined at run-time. - */ -#define Rl0(v,w,x,y,z,i) \ - z+=((w&(x^y))^y)+blk0le(i)+0x5A827999+rol(v,5);w=ror(w,2); -#define Rb0(v,w,x,y,z,i) \ - z+=((w&(x^y))^y)+blk0be(i)+0x5A827999+rol(v,5);w=ror(w,2); -#define R1(v,w,x,y,z,i) \ - z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=ror(w,2); -#define R2(v,w,x,y,z,i) \ - z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=ror(w,2); -#define R3(v,w,x,y,z,i) \ - z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=ror(w,2); -#define R4(v,w,x,y,z,i) \ - z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=ror(w,2); - -/* - * Hash a single 512-bit block. This is the core of the algorithm. - */ -static void SHA1Transform(unsigned int state[5], const unsigned char buffer[64]){ - unsigned int qq[5]; /* a, b, c, d, e; */ - static int one = 1; - unsigned int block[16]; - memcpy(block, buffer, 64); - memcpy(qq,state,5*sizeof(unsigned int)); - -#define a qq[0] -#define b qq[1] -#define c qq[2] -#define d qq[3] -#define e qq[4] - - /* Copy p->state[] to working vars */ - /* - a = state[0]; - b = state[1]; - c = state[2]; - d = state[3]; - e = state[4]; - */ - - /* 4 rounds of 20 operations each. Loop unrolled. */ - if( 1 == *(unsigned char*)&one ){ - Rl0(a,b,c,d,e, 0); Rl0(e,a,b,c,d, 1); Rl0(d,e,a,b,c, 2); Rl0(c,d,e,a,b, 3); - Rl0(b,c,d,e,a, 4); Rl0(a,b,c,d,e, 5); Rl0(e,a,b,c,d, 6); Rl0(d,e,a,b,c, 7); - Rl0(c,d,e,a,b, 8); Rl0(b,c,d,e,a, 9); Rl0(a,b,c,d,e,10); Rl0(e,a,b,c,d,11); - Rl0(d,e,a,b,c,12); Rl0(c,d,e,a,b,13); Rl0(b,c,d,e,a,14); Rl0(a,b,c,d,e,15); - }else{ - Rb0(a,b,c,d,e, 0); Rb0(e,a,b,c,d, 1); Rb0(d,e,a,b,c, 2); Rb0(c,d,e,a,b, 3); - Rb0(b,c,d,e,a, 4); Rb0(a,b,c,d,e, 5); Rb0(e,a,b,c,d, 6); Rb0(d,e,a,b,c, 7); - Rb0(c,d,e,a,b, 8); Rb0(b,c,d,e,a, 9); Rb0(a,b,c,d,e,10); Rb0(e,a,b,c,d,11); - Rb0(d,e,a,b,c,12); Rb0(c,d,e,a,b,13); Rb0(b,c,d,e,a,14); Rb0(a,b,c,d,e,15); - } - R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); - R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); - R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); - R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); - R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); - R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); - R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); - R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); - R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); - R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); - R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); - R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); - R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); - R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); - R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); - R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); - - /* Add the working vars back into context.state[] */ - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - state[4] += e; - -#undef a -#undef b -#undef c -#undef d -#undef e -} - - -/* Initialize a SHA1 context */ -static void hash_init(SHA1Context *p){ - /* SHA1 initialization constants */ - p->state[0] = 0x67452301; - p->state[1] = 0xEFCDAB89; - p->state[2] = 0x98BADCFE; - p->state[3] = 0x10325476; - p->state[4] = 0xC3D2E1F0; - p->count[0] = p->count[1] = 0; -} - -/* Add new content to the SHA1 hash */ -static void hash_step( - SHA1Context *p, /* Add content to this context */ - const unsigned char *data, /* Data to be added */ - unsigned int len /* Number of bytes in data */ -){ - unsigned int i, j; - - j = p->count[0]; - if( (p->count[0] += len << 3) < j ){ - p->count[1] += (len>>29)+1; - } - j = (j >> 3) & 63; - if( (j + len) > 63 ){ - (void)memcpy(&p->buffer[j], data, (i = 64-j)); - SHA1Transform(p->state, p->buffer); - for(; i + 63 < len; i += 64){ - SHA1Transform(p->state, &data[i]); - } - j = 0; - }else{ - i = 0; - } - (void)memcpy(&p->buffer[j], &data[i], len - i); -} - -/* Compute a string using sqlite3_vsnprintf() and hash it */ -static void hash_step_vformat( - SHA1Context *p, /* Add content to this context */ - const char *zFormat, - ... -){ - va_list ap; - int n; - char zBuf[50]; - va_start(ap, zFormat); - sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap); - va_end(ap); - n = (int)strlen(zBuf); - hash_step(p, (unsigned char*)zBuf, n); -} - - -/* Add padding and compute the message digest. Render the -** message digest as lower-case hexadecimal and put it into -** zOut[]. zOut[] must be at least 41 bytes long. */ -static void hash_finish( - SHA1Context *p, /* The SHA1 context to finish and render */ - char *zOut, /* Store hex or binary hash here */ - int bAsBinary /* 1 for binary hash, 0 for hex hash */ -){ - unsigned int i; - unsigned char finalcount[8]; - unsigned char digest[20]; - static const char zEncode[] = "0123456789abcdef"; - - for (i = 0; i < 8; i++){ - finalcount[i] = (unsigned char)((p->count[(i >= 4 ? 0 : 1)] - >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */ - } - hash_step(p, (const unsigned char *)"\200", 1); - while ((p->count[0] & 504) != 448){ - hash_step(p, (const unsigned char *)"\0", 1); - } - hash_step(p, finalcount, 8); /* Should cause a SHA1Transform() */ - for (i = 0; i < 20; i++){ - digest[i] = (unsigned char)((p->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); - } - if( bAsBinary ){ - memcpy(zOut, digest, 20); - }else{ - for(i=0; i<20; i++){ - zOut[i*2] = zEncode[(digest[i]>>4)&0xf]; - zOut[i*2+1] = zEncode[digest[i] & 0xf]; - } - zOut[i*2]= 0; - } -} -/* End of the hashing logic -*****************************************************************************/ - -/* -** Implementation of the sha1(X) function. -** -** Return a lower-case hexadecimal rendering of the SHA1 hash of the -** argument X. If X is a BLOB, it is hashed as is. For all other -** types of input, X is converted into a UTF-8 string and the string -** is hash without the trailing 0x00 terminator. The hash of a NULL -** value is NULL. -*/ -static void sha1Func( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - SHA1Context cx; - int eType = sqlite3_value_type(argv[0]); - int nByte = sqlite3_value_bytes(argv[0]); - char zOut[44]; - - assert( argc==1 ); - if( eType==SQLITE_NULL ) return; - hash_init(&cx); - if( eType==SQLITE_BLOB ){ - hash_step(&cx, sqlite3_value_blob(argv[0]), nByte); - }else{ - hash_step(&cx, sqlite3_value_text(argv[0]), nByte); - } - if( sqlite3_user_data(context)!=0 ){ - hash_finish(&cx, zOut, 1); - sqlite3_result_blob(context, zOut, 20, SQLITE_TRANSIENT); - }else{ - hash_finish(&cx, zOut, 0); - sqlite3_result_blob(context, zOut, 40, SQLITE_TRANSIENT); - } -} - -/* -** Implementation of the sha1_query(SQL) function. -** -** This function compiles and runs the SQL statement(s) given in the -** argument. The results are hashed using SHA1 and that hash is returned. -** -** The original SQL text is included as part of the hash. -** -** The hash is not just a concatenation of the outputs. Each query -** is delimited and each row and value within the query is delimited, -** with all values being marked with their datatypes. -*/ -static void sha1QueryFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - sqlite3 *db = sqlite3_context_db_handle(context); - const char *zSql = (const char*)sqlite3_value_text(argv[0]); - sqlite3_stmt *pStmt = 0; - int nCol; /* Number of columns in the result set */ - int i; /* Loop counter */ - int rc; - int n; - const char *z; - SHA1Context cx; - char zOut[44]; - - assert( argc==1 ); - if( zSql==0 ) return; - hash_init(&cx); - while( zSql[0] ){ - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql); - if( rc ){ - char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s", - zSql, sqlite3_errmsg(db)); - sqlite3_finalize(pStmt); - sqlite3_result_error(context, zMsg, -1); - sqlite3_free(zMsg); - return; - } - if( !sqlite3_stmt_readonly(pStmt) ){ - char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt)); - sqlite3_finalize(pStmt); - sqlite3_result_error(context, zMsg, -1); - sqlite3_free(zMsg); - return; - } - nCol = sqlite3_column_count(pStmt); - z = sqlite3_sql(pStmt); - n = (int)strlen(z); - hash_step_vformat(&cx,"S%d:",n); - hash_step(&cx,(unsigned char*)z,n); - - /* Compute a hash over the result of the query */ - while( SQLITE_ROW==sqlite3_step(pStmt) ){ - hash_step(&cx,(const unsigned char*)"R",1); - for(i=0; i=1; j--){ - x[j] = u & 0xff; - u >>= 8; - } - x[0] = 'I'; - hash_step(&cx, x, 9); - break; - } - case SQLITE_FLOAT: { - sqlite3_uint64 u; - int j; - unsigned char x[9]; - double r = sqlite3_column_double(pStmt,i); - memcpy(&u, &r, 8); - for(j=8; j>=1; j--){ - x[j] = u & 0xff; - u >>= 8; - } - x[0] = 'F'; - hash_step(&cx,x,9); - break; - } - case SQLITE_TEXT: { - int n2 = sqlite3_column_bytes(pStmt, i); - const unsigned char *z2 = sqlite3_column_text(pStmt, i); - hash_step_vformat(&cx,"T%d:",n2); - hash_step(&cx, z2, n2); - break; - } - case SQLITE_BLOB: { - int n2 = sqlite3_column_bytes(pStmt, i); - const unsigned char *z2 = sqlite3_column_blob(pStmt, i); - hash_step_vformat(&cx,"B%d:",n2); - hash_step(&cx, z2, n2); - break; - } - } - } - } - sqlite3_finalize(pStmt); - } - hash_finish(&cx, zOut, 0); - sqlite3_result_text(context, zOut, 40, SQLITE_TRANSIENT); -} - - -#ifdef _WIN32 - -#endif -int sqlite3_sha_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - static int one = 1; - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; /* Unused parameter */ - rc = sqlite3_create_function(db, "sha1", 1, - SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, - 0, sha1Func, 0, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "sha1b", 1, - SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, - (void*)&one, sha1Func, 0, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "sha1_query", 1, - SQLITE_UTF8|SQLITE_DIRECTONLY, 0, - sha1QueryFunc, 0, 0); - } - return rc; -} - -/************************* End ../ext/misc/sha1.c ********************/ -/************************* Begin ../ext/misc/uint.c ******************/ -/* -** 2020-04-14 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This SQLite extension implements the UINT collating sequence. -** -** UINT works like BINARY for text, except that embedded strings -** of digits compare in numeric order. -** -** * Leading zeros are handled properly, in the sense that -** they do not mess of the maginitude comparison of embedded -** strings of digits. "x00123y" is equal to "x123y". -** -** * Only unsigned integers are recognized. Plus and minus -** signs are ignored. Decimal points and exponential notation -** are ignored. -** -** * Embedded integers can be of arbitrary length. Comparison -** is *not* limited integers that can be expressed as a -** 64-bit machine integer. -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include -#include - -/* -** Compare text in lexicographic order, except strings of digits -** compare in numeric order. -*/ -static int uintCollFunc( - void *notUsed, - int nKey1, const void *pKey1, - int nKey2, const void *pKey2 -){ - const unsigned char *zA = (const unsigned char*)pKey1; - const unsigned char *zB = (const unsigned char*)pKey2; - int i=0, j=0, x; - (void)notUsed; - while( i -#include -#include -#include - -/* Mark a function parameter as unused, to suppress nuisance compiler -** warnings. */ -#ifndef UNUSED_PARAMETER -# define UNUSED_PARAMETER(X) (void)(X) -#endif - - -/* A decimal object */ -typedef struct Decimal Decimal; -struct Decimal { - char sign; /* 0 for positive, 1 for negative */ - char oom; /* True if an OOM is encountered */ - char isNull; /* True if holds a NULL rather than a number */ - char isInit; /* True upon initialization */ - int nDigit; /* Total number of digits */ - int nFrac; /* Number of digits to the right of the decimal point */ - signed char *a; /* Array of digits. Most significant first. */ -}; - -/* -** Release memory held by a Decimal, but do not free the object itself. -*/ -static void decimal_clear(Decimal *p){ - sqlite3_free(p->a); -} - -/* -** Destroy a Decimal object -*/ -static void decimal_free(Decimal *p){ - if( p ){ - decimal_clear(p); - sqlite3_free(p); - } -} - -/* -** Allocate a new Decimal object initialized to the text in zIn[]. -** Return NULL if any kind of error occurs. -*/ -static Decimal *decimalNewFromText(const char *zIn, int n){ - Decimal *p = 0; - int i; - int iExp = 0; - - p = sqlite3_malloc( sizeof(*p) ); - if( p==0 ) goto new_from_text_failed; - p->sign = 0; - p->oom = 0; - p->isInit = 1; - p->isNull = 0; - p->nDigit = 0; - p->nFrac = 0; - p->a = sqlite3_malloc64( n+1 ); - if( p->a==0 ) goto new_from_text_failed; - for(i=0; isspace(zIn[i]); i++){} - if( zIn[i]=='-' ){ - p->sign = 1; - i++; - }else if( zIn[i]=='+' ){ - i++; - } - while( i='0' && c<='9' ){ - p->a[p->nDigit++] = c - '0'; - }else if( c=='.' ){ - p->nFrac = p->nDigit + 1; - }else if( c=='e' || c=='E' ){ - int j = i+1; - int neg = 0; - if( j>=n ) break; - if( zIn[j]=='-' ){ - neg = 1; - j++; - }else if( zIn[j]=='+' ){ - j++; - } - while( j='0' && zIn[j]<='9' ){ - iExp = iExp*10 + zIn[j] - '0'; - } - j++; - } - if( neg ) iExp = -iExp; - break; - } - i++; - } - if( p->nFrac ){ - p->nFrac = p->nDigit - (p->nFrac - 1); - } - if( iExp>0 ){ - if( p->nFrac>0 ){ - if( iExp<=p->nFrac ){ - p->nFrac -= iExp; - iExp = 0; - }else{ - iExp -= p->nFrac; - p->nFrac = 0; - } - } - if( iExp>0 ){ - p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 ); - if( p->a==0 ) goto new_from_text_failed; - memset(p->a+p->nDigit, 0, iExp); - p->nDigit += iExp; - } - }else if( iExp<0 ){ - int nExtra; - iExp = -iExp; - nExtra = p->nDigit - p->nFrac - 1; - if( nExtra ){ - if( nExtra>=iExp ){ - p->nFrac += iExp; - iExp = 0; - }else{ - iExp -= nExtra; - p->nFrac = p->nDigit - 1; - } - } - if( iExp>0 ){ - p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 ); - if( p->a==0 ) goto new_from_text_failed; - memmove(p->a+iExp, p->a, p->nDigit); - memset(p->a, 0, iExp); - p->nDigit += iExp; - p->nFrac += iExp; - } - } - return p; - -new_from_text_failed: - if( p ){ - if( p->a ) sqlite3_free(p->a); - sqlite3_free(p); - } - return 0; -} - -/* Forward reference */ -static Decimal *decimalFromDouble(double); - -/* -** Allocate a new Decimal object from an sqlite3_value. Return a pointer -** to the new object, or NULL if there is an error. If the pCtx argument -** is not NULL, then errors are reported on it as well. -** -** If the pIn argument is SQLITE_TEXT or SQLITE_INTEGER, it is converted -** directly into a Decimal. For SQLITE_FLOAT or for SQLITE_BLOB of length -** 8 bytes, the resulting double value is expanded into its decimal equivalent. -** If pIn is NULL or if it is a BLOB that is not exactly 8 bytes in length, -** then NULL is returned. -*/ -static Decimal *decimal_new( - sqlite3_context *pCtx, /* Report error here, if not null */ - sqlite3_value *pIn, /* Construct the decimal object from this */ - int bTextOnly /* Always interpret pIn as text if true */ -){ - Decimal *p = 0; - int eType = sqlite3_value_type(pIn); - if( bTextOnly && (eType==SQLITE_FLOAT || eType==SQLITE_BLOB) ){ - eType = SQLITE_TEXT; - } - switch( eType ){ - case SQLITE_TEXT: - case SQLITE_INTEGER: { - const char *zIn = (const char*)sqlite3_value_text(pIn); - int n = sqlite3_value_bytes(pIn); - p = decimalNewFromText(zIn, n); - if( p==0 ) goto new_failed; - break; - } - - case SQLITE_FLOAT: { - p = decimalFromDouble(sqlite3_value_double(pIn)); - break; - } - - case SQLITE_BLOB: { - const unsigned char *x; - unsigned int i; - sqlite3_uint64 v = 0; - double r; - - if( sqlite3_value_bytes(pIn)!=sizeof(r) ) break; - x = sqlite3_value_blob(pIn); - for(i=0; ioom ){ - sqlite3_result_error_nomem(pCtx); - return; - } - if( p->isNull ){ - sqlite3_result_null(pCtx); - return; - } - z = sqlite3_malloc( p->nDigit+4 ); - if( z==0 ){ - sqlite3_result_error_nomem(pCtx); - return; - } - i = 0; - if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){ - p->sign = 0; - } - if( p->sign ){ - z[0] = '-'; - i = 1; - } - n = p->nDigit - p->nFrac; - if( n<=0 ){ - z[i++] = '0'; - } - j = 0; - while( n>1 && p->a[j]==0 ){ - j++; - n--; - } - while( n>0 ){ - z[i++] = p->a[j] + '0'; - j++; - n--; - } - if( p->nFrac ){ - z[i++] = '.'; - do{ - z[i++] = p->a[j] + '0'; - j++; - }while( jnDigit ); - } - z[i] = 0; - sqlite3_result_text(pCtx, z, i, sqlite3_free); -} - -/* -** Make the given Decimal the result in an format similar to '%+#e'. -** In other words, show exponential notation with leading and trailing -** zeros omitted. -*/ -static void decimal_result_sci(sqlite3_context *pCtx, Decimal *p){ - char *z; /* The output buffer */ - int i; /* Loop counter */ - int nZero; /* Number of leading zeros */ - int nDigit; /* Number of digits not counting trailing zeros */ - int nFrac; /* Digits to the right of the decimal point */ - int exp; /* Exponent value */ - signed char zero; /* Zero value */ - signed char *a; /* Array of digits */ - - if( p==0 || p->oom ){ - sqlite3_result_error_nomem(pCtx); - return; - } - if( p->isNull ){ - sqlite3_result_null(pCtx); - return; - } - for(nDigit=p->nDigit; nDigit>0 && p->a[nDigit-1]==0; nDigit--){} - for(nZero=0; nZeroa[nZero]==0; nZero++){} - nFrac = p->nFrac + (nDigit - p->nDigit); - nDigit -= nZero; - z = sqlite3_malloc( nDigit+20 ); - if( z==0 ){ - sqlite3_result_error_nomem(pCtx); - return; - } - if( nDigit==0 ){ - zero = 0; - a = &zero; - nDigit = 1; - nFrac = 0; - }else{ - a = &p->a[nZero]; - } - if( p->sign && nDigit>0 ){ - z[0] = '-'; - }else{ - z[0] = '+'; - } - z[1] = a[0]+'0'; - z[2] = '.'; - if( nDigit==1 ){ - z[3] = '0'; - i = 4; - }else{ - for(i=1; iisNull==0 -** pB!=0 -** pB->isNull==0 -*/ -static int decimal_cmp(const Decimal *pA, const Decimal *pB){ - int nASig, nBSig, rc, n; - if( pA->sign!=pB->sign ){ - return pA->sign ? -1 : +1; - } - if( pA->sign ){ - const Decimal *pTemp = pA; - pA = pB; - pB = pTemp; - } - nASig = pA->nDigit - pA->nFrac; - nBSig = pB->nDigit - pB->nFrac; - if( nASig!=nBSig ){ - return nASig - nBSig; - } - n = pA->nDigit; - if( n>pB->nDigit ) n = pB->nDigit; - rc = memcmp(pA->a, pB->a, n); - if( rc==0 ){ - rc = pA->nDigit - pB->nDigit; - } - return rc; -} - -/* -** SQL Function: decimal_cmp(X, Y) -** -** Return negative, zero, or positive if X is less then, equal to, or -** greater than Y. -*/ -static void decimalCmpFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *pA = 0, *pB = 0; - int rc; - - UNUSED_PARAMETER(argc); - pA = decimal_new(context, argv[0], 1); - if( pA==0 || pA->isNull ) goto cmp_done; - pB = decimal_new(context, argv[1], 1); - if( pB==0 || pB->isNull ) goto cmp_done; - rc = decimal_cmp(pA, pB); - if( rc<0 ) rc = -1; - else if( rc>0 ) rc = +1; - sqlite3_result_int(context, rc); -cmp_done: - decimal_free(pA); - decimal_free(pB); -} - -/* -** Expand the Decimal so that it has a least nDigit digits and nFrac -** digits to the right of the decimal point. -*/ -static void decimal_expand(Decimal *p, int nDigit, int nFrac){ - int nAddSig; - int nAddFrac; - if( p==0 ) return; - nAddFrac = nFrac - p->nFrac; - nAddSig = (nDigit - p->nDigit) - nAddFrac; - if( nAddFrac==0 && nAddSig==0 ) return; - p->a = sqlite3_realloc64(p->a, nDigit+1); - if( p->a==0 ){ - p->oom = 1; - return; - } - if( nAddSig ){ - memmove(p->a+nAddSig, p->a, p->nDigit); - memset(p->a, 0, nAddSig); - p->nDigit += nAddSig; - } - if( nAddFrac ){ - memset(p->a+p->nDigit, 0, nAddFrac); - p->nDigit += nAddFrac; - p->nFrac += nAddFrac; - } -} - -/* -** Add the value pB into pA. A := A + B. -** -** Both pA and pB might become denormalized by this routine. -*/ -static void decimal_add(Decimal *pA, Decimal *pB){ - int nSig, nFrac, nDigit; - int i, rc; - if( pA==0 ){ - return; - } - if( pA->oom || pB==0 || pB->oom ){ - pA->oom = 1; - return; - } - if( pA->isNull || pB->isNull ){ - pA->isNull = 1; - return; - } - nSig = pA->nDigit - pA->nFrac; - if( nSig && pA->a[0]==0 ) nSig--; - if( nSignDigit-pB->nFrac ){ - nSig = pB->nDigit - pB->nFrac; - } - nFrac = pA->nFrac; - if( nFracnFrac ) nFrac = pB->nFrac; - nDigit = nSig + nFrac + 1; - decimal_expand(pA, nDigit, nFrac); - decimal_expand(pB, nDigit, nFrac); - if( pA->oom || pB->oom ){ - pA->oom = 1; - }else{ - if( pA->sign==pB->sign ){ - int carry = 0; - for(i=nDigit-1; i>=0; i--){ - int x = pA->a[i] + pB->a[i] + carry; - if( x>=10 ){ - carry = 1; - pA->a[i] = x - 10; - }else{ - carry = 0; - pA->a[i] = x; - } - } - }else{ - signed char *aA, *aB; - int borrow = 0; - rc = memcmp(pA->a, pB->a, nDigit); - if( rc<0 ){ - aA = pB->a; - aB = pA->a; - pA->sign = !pA->sign; - }else{ - aA = pA->a; - aB = pB->a; - } - for(i=nDigit-1; i>=0; i--){ - int x = aA[i] - aB[i] - borrow; - if( x<0 ){ - pA->a[i] = x+10; - borrow = 1; - }else{ - pA->a[i] = x; - borrow = 0; - } - } - } - } -} - -/* -** Multiply A by B. A := A * B -** -** All significant digits after the decimal point are retained. -** Trailing zeros after the decimal point are omitted as long as -** the number of digits after the decimal point is no less than -** either the number of digits in either input. -*/ -static void decimalMul(Decimal *pA, Decimal *pB){ - signed char *acc = 0; - int i, j, k; - int minFrac; - - if( pA==0 || pA->oom || pA->isNull - || pB==0 || pB->oom || pB->isNull - ){ - goto mul_end; - } - acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 ); - if( acc==0 ){ - pA->oom = 1; - goto mul_end; - } - memset(acc, 0, pA->nDigit + pB->nDigit + 2); - minFrac = pA->nFrac; - if( pB->nFracnFrac; - for(i=pA->nDigit-1; i>=0; i--){ - signed char f = pA->a[i]; - int carry = 0, x; - for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){ - x = acc[k] + f*pB->a[j] + carry; - acc[k] = x%10; - carry = x/10; - } - x = acc[k] + carry; - acc[k] = x%10; - acc[k-1] += x/10; - } - sqlite3_free(pA->a); - pA->a = acc; - acc = 0; - pA->nDigit += pB->nDigit + 2; - pA->nFrac += pB->nFrac; - pA->sign ^= pB->sign; - while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){ - pA->nFrac--; - pA->nDigit--; - } - -mul_end: - sqlite3_free(acc); -} - -/* -** Create a new Decimal object that contains an integer power of 2. -*/ -static Decimal *decimalPow2(int N){ - Decimal *pA = 0; /* The result to be returned */ - Decimal *pX = 0; /* Multiplier */ - if( N<-20000 || N>20000 ) goto pow2_fault; - pA = decimalNewFromText("1.0", 3); - if( pA==0 || pA->oom ) goto pow2_fault; - if( N==0 ) return pA; - if( N>0 ){ - pX = decimalNewFromText("2.0", 3); - }else{ - N = -N; - pX = decimalNewFromText("0.5", 3); - } - if( pX==0 || pX->oom ) goto pow2_fault; - while( 1 /* Exit by break */ ){ - if( N & 1 ){ - decimalMul(pA, pX); - if( pA->oom ) goto pow2_fault; - } - N >>= 1; - if( N==0 ) break; - decimalMul(pX, pX); - } - decimal_free(pX); - return pA; - -pow2_fault: - decimal_free(pA); - decimal_free(pX); - return 0; -} - -/* -** Use an IEEE754 binary64 ("double") to generate a new Decimal object. -*/ -static Decimal *decimalFromDouble(double r){ - sqlite3_int64 m, a; - int e; - int isNeg; - Decimal *pA; - Decimal *pX; - char zNum[100]; - if( r<0.0 ){ - isNeg = 1; - r = -r; - }else{ - isNeg = 0; - } - memcpy(&a,&r,sizeof(a)); - if( a==0 ){ - e = 0; - m = 0; - }else{ - e = a>>52; - m = a & ((((sqlite3_int64)1)<<52)-1); - if( e==0 ){ - m <<= 1; - }else{ - m |= ((sqlite3_int64)1)<<52; - } - while( e<1075 && m>0 && (m&1)==0 ){ - m >>= 1; - e++; - } - if( isNeg ) m = -m; - e = e - 1075; - if( e>971 ){ - return 0; /* A NaN or an Infinity */ - } - } - - /* At this point m is the integer significand and e is the exponent */ - sqlite3_snprintf(sizeof(zNum), zNum, "%lld", m); - pA = decimalNewFromText(zNum, (int)strlen(zNum)); - pX = decimalPow2(e); - decimalMul(pA, pX); - decimal_free(pX); - return pA; -} - -/* -** SQL Function: decimal(X) -** OR: decimal_exp(X) -** -** Convert input X into decimal and then back into text. -** -** If X is originally a float, then a full decimal expansion of that floating -** point value is done. Or if X is an 8-byte blob, it is interpreted -** as a float and similarly expanded. -** -** The decimal_exp(X) function returns the result in exponential notation. -** decimal(X) returns a complete decimal, without the e+NNN at the end. -*/ -static void decimalFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *p = decimal_new(context, argv[0], 0); - UNUSED_PARAMETER(argc); - if( p ){ - if( sqlite3_user_data(context)!=0 ){ - decimal_result_sci(context, p); - }else{ - decimal_result(context, p); - } - decimal_free(p); - } -} - -/* -** Compare text in decimal order. -*/ -static int decimalCollFunc( - void *notUsed, - int nKey1, const void *pKey1, - int nKey2, const void *pKey2 -){ - const unsigned char *zA = (const unsigned char*)pKey1; - const unsigned char *zB = (const unsigned char*)pKey2; - Decimal *pA = decimalNewFromText((const char*)zA, nKey1); - Decimal *pB = decimalNewFromText((const char*)zB, nKey2); - int rc; - UNUSED_PARAMETER(notUsed); - if( pA==0 || pB==0 ){ - rc = 0; - }else{ - rc = decimal_cmp(pA, pB); - } - decimal_free(pA); - decimal_free(pB); - return rc; -} - - -/* -** SQL Function: decimal_add(X, Y) -** decimal_sub(X, Y) -** -** Return the sum or difference of X and Y. -*/ -static void decimalAddFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *pA = decimal_new(context, argv[0], 1); - Decimal *pB = decimal_new(context, argv[1], 1); - UNUSED_PARAMETER(argc); - decimal_add(pA, pB); - decimal_result(context, pA); - decimal_free(pA); - decimal_free(pB); -} -static void decimalSubFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *pA = decimal_new(context, argv[0], 1); - Decimal *pB = decimal_new(context, argv[1], 1); - UNUSED_PARAMETER(argc); - if( pB ){ - pB->sign = !pB->sign; - decimal_add(pA, pB); - decimal_result(context, pA); - } - decimal_free(pA); - decimal_free(pB); -} - -/* Aggregate funcion: decimal_sum(X) -** -** Works like sum() except that it uses decimal arithmetic for unlimited -** precision. -*/ -static void decimalSumStep( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *p; - Decimal *pArg; - UNUSED_PARAMETER(argc); - p = sqlite3_aggregate_context(context, sizeof(*p)); - if( p==0 ) return; - if( !p->isInit ){ - p->isInit = 1; - p->a = sqlite3_malloc(2); - if( p->a==0 ){ - p->oom = 1; - }else{ - p->a[0] = 0; - } - p->nDigit = 1; - p->nFrac = 0; - } - if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; - pArg = decimal_new(context, argv[0], 1); - decimal_add(p, pArg); - decimal_free(pArg); -} -static void decimalSumInverse( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *p; - Decimal *pArg; - UNUSED_PARAMETER(argc); - p = sqlite3_aggregate_context(context, sizeof(*p)); - if( p==0 ) return; - if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; - pArg = decimal_new(context, argv[0], 1); - if( pArg ) pArg->sign = !pArg->sign; - decimal_add(p, pArg); - decimal_free(pArg); -} -static void decimalSumValue(sqlite3_context *context){ - Decimal *p = sqlite3_aggregate_context(context, 0); - if( p==0 ) return; - decimal_result(context, p); -} -static void decimalSumFinalize(sqlite3_context *context){ - Decimal *p = sqlite3_aggregate_context(context, 0); - if( p==0 ) return; - decimal_result(context, p); - decimal_clear(p); -} - -/* -** SQL Function: decimal_mul(X, Y) -** -** Return the product of X and Y. -*/ -static void decimalMulFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Decimal *pA = decimal_new(context, argv[0], 1); - Decimal *pB = decimal_new(context, argv[1], 1); - UNUSED_PARAMETER(argc); - if( pA==0 || pA->oom || pA->isNull - || pB==0 || pB->oom || pB->isNull - ){ - goto mul_end; - } - decimalMul(pA, pB); - if( pA->oom ){ - goto mul_end; - } - decimal_result(context, pA); - -mul_end: - decimal_free(pA); - decimal_free(pB); -} - -/* -** SQL Function: decimal_pow2(N) -** -** Return the N-th power of 2. N must be an integer. -*/ -static void decimalPow2Func( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - UNUSED_PARAMETER(argc); - if( sqlite3_value_type(argv[0])==SQLITE_INTEGER ){ - Decimal *pA = decimalPow2(sqlite3_value_int(argv[0])); - decimal_result_sci(context, pA); - decimal_free(pA); - } -} - -#ifdef _WIN32 - -#endif -int sqlite3_decimal_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - static const struct { - const char *zFuncName; - int nArg; - int iArg; - void (*xFunc)(sqlite3_context*,int,sqlite3_value**); - } aFunc[] = { - { "decimal", 1, 0, decimalFunc }, - { "decimal_exp", 1, 1, decimalFunc }, - { "decimal_cmp", 2, 0, decimalCmpFunc }, - { "decimal_add", 2, 0, decimalAddFunc }, - { "decimal_sub", 2, 0, decimalSubFunc }, - { "decimal_mul", 2, 0, decimalMulFunc }, - { "decimal_pow2", 1, 0, decimalPow2Func }, - }; - unsigned int i; - (void)pzErrMsg; /* Unused parameter */ - - SQLITE_EXTENSION_INIT2(pApi); - - for(i=0; i<(int)(sizeof(aFunc)/sizeof(aFunc[0])) && rc==SQLITE_OK; i++){ - rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg, - SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, - aFunc[i].iArg ? db : 0, aFunc[i].xFunc, 0, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_create_window_function(db, "decimal_sum", 1, - SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0, - decimalSumStep, decimalSumFinalize, - decimalSumValue, decimalSumInverse, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8, - 0, decimalCollFunc); - } - return rc; -} - -/************************* End ../ext/misc/decimal.c ********************/ -/************************* Begin ../ext/misc/percentile.c ******************/ -/* -** 2013-05-28 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains code to implement the percentile(Y,P) SQL function -** and similar as described below: -** -** (1) The percentile(Y,P) function is an aggregate function taking -** exactly two arguments. -** -** (2) If the P argument to percentile(Y,P) is not the same for every -** row in the aggregate then an error is thrown. The word "same" -** in the previous sentence means that the value differ by less -** than 0.001. -** -** (3) If the P argument to percentile(Y,P) evaluates to anything other -** than a number in the range of 0.0 to 100.0 inclusive then an -** error is thrown. -** -** (4) If any Y argument to percentile(Y,P) evaluates to a value that -** is not NULL and is not numeric then an error is thrown. -** -** (5) If any Y argument to percentile(Y,P) evaluates to plus or minus -** infinity then an error is thrown. (SQLite always interprets NaN -** values as NULL.) -** -** (6) Both Y and P in percentile(Y,P) can be arbitrary expressions, -** including CASE WHEN expressions. -** -** (7) The percentile(Y,P) aggregate is able to handle inputs of at least -** one million (1,000,000) rows. -** -** (8) If there are no non-NULL values for Y, then percentile(Y,P) -** returns NULL. -** -** (9) If there is exactly one non-NULL value for Y, the percentile(Y,P) -** returns the one Y value. -** -** (10) If there N non-NULL values of Y where N is two or more and -** the Y values are ordered from least to greatest and a graph is -** drawn from 0 to N-1 such that the height of the graph at J is -** the J-th Y value and such that straight lines are drawn between -** adjacent Y values, then the percentile(Y,P) function returns -** the height of the graph at P*(N-1)/100. -** -** (11) The percentile(Y,P) function always returns either a floating -** point number or NULL. -** -** (12) The percentile(Y,P) is implemented as a single C99 source-code -** file that compiles into a shared-library or DLL that can be loaded -** into SQLite using the sqlite3_load_extension() interface. -** -** (13) A separate median(Y) function is the equivalent percentile(Y,50). -** -** (14) A separate percentile_cont(Y,P) function is equivalent to -** percentile(Y,P/100.0). In other words, the fraction value in -** the second argument is in the range of 0 to 1 instead of 0 to 100. -** -** (15) A separate percentile_disc(Y,P) function is like -** percentile_cont(Y,P) except that instead of returning the weighted -** average of the nearest two input values, it returns the next lower -** value. So the percentile_disc(Y,P) will always return a value -** that was one of the inputs. -** -** (16) All of median(), percentile(Y,P), percentile_cont(Y,P) and -** percentile_disc(Y,P) can be used as window functions. -** -** Differences from standard SQL: -** -** * The percentile_cont(X,P) function is equivalent to the following in -** standard SQL: -** -** (percentile_cont(P) WITHIN GROUP (ORDER BY X)) -** -** The SQLite syntax is much more compact. The standard SQL syntax -** is also supported if SQLite is compiled with the -** -DSQLITE_ENABLE_ORDERED_SET_AGGREGATES option. -** -** * No median(X) function exists in the SQL standard. App developers -** are expected to write "percentile_cont(0.5)WITHIN GROUP(ORDER BY X)". -** -** * No percentile(Y,P) function exists in the SQL standard. Instead of -** percential(Y,P), developers must write this: -** "percentile_cont(P/100.0) WITHIN GROUP (ORDER BY Y)". Note that -** the fraction parameter to percentile() goes from 0 to 100 whereas -** the fraction parameter in SQL standard percentile_cont() goes from -** 0 to 1. -** -** Implementation notes as of 2024-08-31: -** -** * The regular aggregate-function versions of these routines work -** by accumulating all values in an array of doubles, then sorting -** that array using quicksort before computing the answer. Thus -** the runtime is O(NlogN) where N is the number of rows of input. -** -** * For the window-function versions of these routines, the array of -** inputs is sorted as soon as the first value is computed. Thereafter, -** the array is kept in sorted order using an insert-sort. This -** results in O(N*K) performance where K is the size of the window. -** One can imagine alternative implementations that give O(N*logN*logK) -** performance, but they require more complex logic and data structures. -** The developers have elected to keep the asymptotically slower -** algorithm for now, for simplicity, under the theory that window -** functions are seldom used and when they are, the window size K is -** often small. The developers might revisit that decision later, -** should the need arise. -*/ -#if defined(SQLITE3_H) - /* no-op */ -#elif defined(SQLITE_STATIC_PERCENTILE) -/* # include "sqlite3.h" */ -#else -/* # include "sqlite3ext.h" */ - SQLITE_EXTENSION_INIT1 -#endif -#include -#include -#include - -/* The following object is the group context for a single percentile() -** aggregate. Remember all input Y values until the very end. -** Those values are accumulated in the Percentile.a[] array. -*/ -typedef struct Percentile Percentile; -struct Percentile { - unsigned nAlloc; /* Number of slots allocated for a[] */ - unsigned nUsed; /* Number of slots actually used in a[] */ - char bSorted; /* True if a[] is already in sorted order */ - char bKeepSorted; /* True if advantageous to keep a[] sorted */ - char bPctValid; /* True if rPct is valid */ - double rPct; /* Fraction. 0.0 to 1.0 */ - double *a; /* Array of Y values */ -}; - -/* Details of each function in the percentile family */ -typedef struct PercentileFunc PercentileFunc; -struct PercentileFunc { - const char *zName; /* Function name */ - char nArg; /* Number of arguments */ - char mxFrac; /* Maximum value of the "fraction" input */ - char bDiscrete; /* True for percentile_disc() */ -}; -static const PercentileFunc aPercentFunc[] = { - { "median", 1, 1, 0 }, - { "percentile", 2, 100, 0 }, - { "percentile_cont", 2, 1, 0 }, - { "percentile_disc", 2, 1, 1 }, -}; - -/* -** Return TRUE if the input floating-point number is an infinity. -*/ -static int percentIsInfinity(double r){ - sqlite3_uint64 u; - assert( sizeof(u)==sizeof(r) ); - memcpy(&u, &r, sizeof(u)); - return ((u>>52)&0x7ff)==0x7ff; -} - -/* -** Return TRUE if two doubles differ by 0.001 or less. -*/ -static int percentSameValue(double a, double b){ - a -= b; - return a>=-0.001 && a<=0.001; -} - -/* -** Search p (which must have p->bSorted) looking for an entry with -** value y. Return the index of that entry. -** -** If bExact is true, return -1 if the entry is not found. -** -** If bExact is false, return the index at which a new entry with -** value y should be insert in order to keep the values in sorted -** order. The smallest return value in this case will be 0, and -** the largest return value will be p->nUsed. -*/ -static int percentBinarySearch(Percentile *p, double y, int bExact){ - int iFirst = 0; /* First element of search range */ - int iLast = p->nUsed - 1; /* Last element of search range */ - while( iLast>=iFirst ){ - int iMid = (iFirst+iLast)/2; - double x = p->a[iMid]; - if( xy ){ - iLast = iMid - 1; - }else{ - return iMid; - } - } - if( bExact ) return -1; - return iFirst; -} - -/* -** Generate an error for a percentile function. -** -** The error format string must have exactly one occurrance of "%%s()" -** (with two '%' characters). That substring will be replaced by the name -** of the function. -*/ -static void percentError(sqlite3_context *pCtx, const char *zFormat, ...){ - PercentileFunc *pFunc = (PercentileFunc*)sqlite3_user_data(pCtx); - char *zMsg1; - char *zMsg2; - va_list ap; - - va_start(ap, zFormat); - zMsg1 = sqlite3_vmprintf(zFormat, ap); - va_end(ap); - zMsg2 = zMsg1 ? sqlite3_mprintf(zMsg1, pFunc->zName) : 0; - sqlite3_result_error(pCtx, zMsg2, -1); - sqlite3_free(zMsg1); - sqlite3_free(zMsg2); -} - -/* -** The "step" function for percentile(Y,P) is called once for each -** input row. -*/ -static void percentStep(sqlite3_context *pCtx, int argc, sqlite3_value **argv){ - Percentile *p; - double rPct; - int eType; - double y; - assert( argc==2 || argc==1 ); - - if( argc==1 ){ - /* Requirement 13: median(Y) is the same as percentile(Y,50). */ - rPct = 0.5; - }else{ - /* Requirement 3: P must be a number between 0 and 100 */ - PercentileFunc *pFunc = (PercentileFunc*)sqlite3_user_data(pCtx); - eType = sqlite3_value_numeric_type(argv[1]); - rPct = sqlite3_value_double(argv[1])/(double)pFunc->mxFrac; - if( (eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT) - || rPct<0.0 || rPct>1.0 - ){ - percentError(pCtx, "the fraction argument to %%s()" - " is not between 0.0 and %.1f", - (double)pFunc->mxFrac); - return; - } - } - - /* Allocate the session context. */ - p = (Percentile*)sqlite3_aggregate_context(pCtx, sizeof(*p)); - if( p==0 ) return; - - /* Remember the P value. Throw an error if the P value is different - ** from any prior row, per Requirement (2). */ - if( !p->bPctValid ){ - p->rPct = rPct; - p->bPctValid = 1; - }else if( !percentSameValue(p->rPct,rPct) ){ - percentError(pCtx, "the fraction argument to %%s()" - " is not the same for all input rows"); - return; - } - - /* Ignore rows for which Y is NULL */ - eType = sqlite3_value_type(argv[0]); - if( eType==SQLITE_NULL ) return; - - /* If not NULL, then Y must be numeric. Otherwise throw an error. - ** Requirement 4 */ - if( eType!=SQLITE_INTEGER && eType!=SQLITE_FLOAT ){ - percentError(pCtx, "input to %%s() is not numeric"); - return; - } - - /* Throw an error if the Y value is infinity or NaN */ - y = sqlite3_value_double(argv[0]); - if( percentIsInfinity(y) ){ - percentError(pCtx, "Inf input to %%s()"); - return; - } - - /* Allocate and store the Y */ - if( p->nUsed>=p->nAlloc ){ - unsigned n = p->nAlloc*2 + 250; - double *a = sqlite3_realloc64(p->a, sizeof(double)*n); - if( a==0 ){ - sqlite3_free(p->a); - memset(p, 0, sizeof(*p)); - sqlite3_result_error_nomem(pCtx); - return; - } - p->nAlloc = n; - p->a = a; - } - if( p->nUsed==0 ){ - p->a[p->nUsed++] = y; - p->bSorted = 1; - }else if( !p->bSorted || y>=p->a[p->nUsed-1] ){ - p->a[p->nUsed++] = y; - }else if( p->bKeepSorted ){ - int i; - i = percentBinarySearch(p, y, 0); - if( i<(int)p->nUsed ){ - memmove(&p->a[i+1], &p->a[i], (p->nUsed-i)*sizeof(p->a[0])); - } - p->a[i] = y; - p->nUsed++; - }else{ - p->a[p->nUsed++] = y; - p->bSorted = 0; - } -} - -/* -** Interchange two doubles. -*/ -#define SWAP_DOUBLE(X,Y) {double ttt=(X);(X)=(Y);(Y)=ttt;} - -/* -** Sort an array of doubles. -** -** Algorithm: quicksort -** -** This is implemented separately rather than using the qsort() routine -** from the standard library because: -** -** (1) To avoid a dependency on qsort() -** (2) To avoid the function call to the comparison routine for each -** comparison. -*/ -static void percentSort(double *a, unsigned int n){ - int iLt; /* Entries before a[iLt] are less than rPivot */ - int iGt; /* Entries at or after a[iGt] are greater than rPivot */ - int i; /* Loop counter */ - double rPivot; /* The pivot value */ - - assert( n>=2 ); - if( a[0]>a[n-1] ){ - SWAP_DOUBLE(a[0],a[n-1]) - } - if( n==2 ) return; - iGt = n-1; - i = n/2; - if( a[0]>a[i] ){ - SWAP_DOUBLE(a[0],a[i]) - }else if( a[i]>a[iGt] ){ - SWAP_DOUBLE(a[i],a[iGt]) - } - if( n==3 ) return; - rPivot = a[i]; - iLt = i = 1; - do{ - if( a[i]iLt ) SWAP_DOUBLE(a[i],a[iLt]) - iLt++; - i++; - }else if( a[i]>rPivot ){ - do{ - iGt--; - }while( iGt>i && a[iGt]>rPivot ); - SWAP_DOUBLE(a[i],a[iGt]) - }else{ - i++; - } - }while( i=2 ) percentSort(a, iLt); - if( n-iGt>=2 ) percentSort(a+iGt, n-iGt); - -/* Uncomment for testing */ -#if 0 - for(i=0; ibSorted==0 ){ - assert( p->nUsed>1 ); - percentSort(p->a, p->nUsed); - p->bSorted = 1; - } - p->bKeepSorted = 1; - - /* Find and remove the row */ - i = percentBinarySearch(p, y, 1); - if( i>=0 ){ - p->nUsed--; - if( i<(int)p->nUsed ){ - memmove(&p->a[i], &p->a[i+1], (p->nUsed - i)*sizeof(p->a[0])); - } - } -} - -/* -** Compute the final output of percentile(). Clean up all allocated -** memory if and only if bIsFinal is true. -*/ -static void percentCompute(sqlite3_context *pCtx, int bIsFinal){ - Percentile *p; - PercentileFunc *pFunc = (PercentileFunc*)sqlite3_user_data(pCtx); - unsigned i1, i2; - double v1, v2; - double ix, vx; - p = (Percentile*)sqlite3_aggregate_context(pCtx, 0); - if( p==0 ) return; - if( p->a==0 ) return; - if( p->nUsed ){ - if( p->bSorted==0 ){ - assert( p->nUsed>1 ); - percentSort(p->a, p->nUsed); - p->bSorted = 1; - } - ix = p->rPct*(p->nUsed-1); - i1 = (unsigned)ix; - if( pFunc->bDiscrete ){ - vx = p->a[i1]; - }else{ - i2 = ix==(double)i1 || i1==p->nUsed-1 ? i1 : i1+1; - v1 = p->a[i1]; - v2 = p->a[i2]; - vx = v1 + (v2-v1)*(ix-i1); - } - sqlite3_result_double(pCtx, vx); - } - if( bIsFinal ){ - sqlite3_free(p->a); - memset(p, 0, sizeof(*p)); - }else{ - p->bKeepSorted = 1; - } -} -static void percentFinal(sqlite3_context *pCtx){ - percentCompute(pCtx, 1); -} -static void percentValue(sqlite3_context *pCtx){ - percentCompute(pCtx, 0); -} - -#if defined(_WIN32) && !defined(SQLITE3_H) && !defined(SQLITE_STATIC_PERCENTILE) - -#endif -int sqlite3_percentile_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - unsigned int i; -#if defined(SQLITE3_H) || defined(SQLITE_STATIC_PERCENTILE) - (void)pApi; /* Unused parameter */ -#else - SQLITE_EXTENSION_INIT2(pApi); -#endif - (void)pzErrMsg; /* Unused parameter */ - for(i=0; i -** *Nix: gcc -O2 -shared -I$SQDIR -fPIC -o base64.so base64.c -** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR -o base64.dylib base64.c -** Win32: gcc -O2 -shared -I%SQDIR% -o base64.dll base64.c -** Win32: cl /Os -I%SQDIR% base64.c -link -dll -out:base64.dll -*/ - -#include - -/* #include "sqlite3ext.h" */ - -#ifndef deliberate_fall_through -/* Quiet some compilers about some of our intentional code. */ -# if GCC_VERSION>=7000000 -# define deliberate_fall_through __attribute__((fallthrough)); -# else -# define deliberate_fall_through -# endif -#endif - -SQLITE_EXTENSION_INIT1; - -#define PC 0x80 /* pad character */ -#define WS 0x81 /* whitespace */ -#define ND 0x82 /* Not above or digit-value */ -#define PAD_CHAR '=' - -#ifndef U8_TYPEDEF -/* typedef unsigned char u8; */ -#define U8_TYPEDEF -#endif - -/* Decoding table, ASCII (7-bit) value to base 64 digit value or other */ -static const u8 b64DigitValues[128] = { - /* HT LF VT FF CR */ - ND,ND,ND,ND, ND,ND,ND,ND, ND,WS,WS,WS, WS,WS,ND,ND, - /* US */ - ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,ND, - /*sp + / */ - WS,ND,ND,ND, ND,ND,ND,ND, ND,ND,ND,62, ND,ND,ND,63, - /* 0 1 5 9 = */ - 52,53,54,55, 56,57,58,59, 60,61,ND,ND, ND,PC,ND,ND, - /* A O */ - ND, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - /* P Z */ - 15,16,17,18, 19,20,21,22, 23,24,25,ND, ND,ND,ND,ND, - /* a o */ - ND,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - /* p z */ - 41,42,43,44, 45,46,47,48, 49,50,51,ND, ND,ND,ND,ND -}; - -static const char b64Numerals[64+1] -= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -#define BX_DV_PROTO(c) \ - ((((u8)(c))<0x80)? (u8)(b64DigitValues[(u8)(c)]) : 0x80) -#define IS_BX_DIGIT(bdp) (((u8)(bdp))<0x80) -#define IS_BX_WS(bdp) ((bdp)==WS) -#define IS_BX_PAD(bdp) ((bdp)==PC) -#define BX_NUMERAL(dv) (b64Numerals[(u8)(dv)]) -/* Width of base64 lines. Should be an integer multiple of 4. */ -#define B64_DARK_MAX 72 - -/* Encode a byte buffer into base64 text with linefeeds appended to limit -** encoded group lengths to B64_DARK_MAX or to terminate the last group. -*/ -static char* toBase64( u8 *pIn, int nbIn, char *pOut ){ - int nCol = 0; - while( nbIn >= 3 ){ - /* Do the bit-shuffle, exploiting unsigned input to avoid masking. */ - pOut[0] = BX_NUMERAL(pIn[0]>>2); - pOut[1] = BX_NUMERAL(((pIn[0]<<4)|(pIn[1]>>4))&0x3f); - pOut[2] = BX_NUMERAL(((pIn[1]&0xf)<<2)|(pIn[2]>>6)); - pOut[3] = BX_NUMERAL(pIn[2]&0x3f); - pOut += 4; - nbIn -= 3; - pIn += 3; - if( (nCol += 4)>=B64_DARK_MAX || nbIn<=0 ){ - *pOut++ = '\n'; - nCol = 0; - } - } - if( nbIn > 0 ){ - signed char nco = nbIn+1; - int nbe; - unsigned long qv = *pIn++; - for( nbe=1; nbe<3; ++nbe ){ - qv <<= 8; - if( nbe=0; --nbe ){ - char ce = (nbe>= 6; - pOut[nbe] = ce; - } - pOut += 4; - *pOut++ = '\n'; - } - *pOut = 0; - return pOut; -} - -/* Skip over text which is not base64 numeral(s). */ -static char * skipNonB64( char *s, int nc ){ - char c; - while( nc-- > 0 && (c = *s) && !IS_BX_DIGIT(BX_DV_PROTO(c)) ) ++s; - return s; -} - -/* Decode base64 text into a byte buffer. */ -static u8* fromBase64( char *pIn, int ncIn, u8 *pOut ){ - if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn; - while( ncIn>0 && *pIn!=PAD_CHAR ){ - static signed char nboi[] = { 0, 0, 1, 2, 3 }; - char *pUse = skipNonB64(pIn, ncIn); - unsigned long qv = 0L; - int nti, nbo, nac; - ncIn -= (pUse - pIn); - pIn = pUse; - nti = (ncIn>4)? 4 : ncIn; - ncIn -= nti; - nbo = nboi[nti]; - if( nbo==0 ) break; - for( nac=0; nac<4; ++nac ){ - char c = (nac>8) & 0xff; - case 1: - pOut[0] = (qv>>16) & 0xff; - } - pOut += nbo; - } - return pOut; -} - -/* This function does the work for the SQLite base64(x) UDF. */ -static void base64(sqlite3_context *context, int na, sqlite3_value *av[]){ - int nb, nc, nv = sqlite3_value_bytes(av[0]); - int nvMax = sqlite3_limit(sqlite3_context_db_handle(context), - SQLITE_LIMIT_LENGTH, -1); - char *cBuf; - u8 *bBuf; - assert(na==1); - switch( sqlite3_value_type(av[0]) ){ - case SQLITE_BLOB: - nb = nv; - nc = 4*(nv+2/3); /* quads needed */ - nc += (nc+(B64_DARK_MAX-1))/B64_DARK_MAX + 1; /* LFs and a 0-terminator */ - if( nvMax < nc ){ - sqlite3_result_error(context, "blob expanded to base64 too big", -1); - return; - } - bBuf = (u8*)sqlite3_value_blob(av[0]); - if( !bBuf ){ - if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){ - goto memFail; - } - sqlite3_result_text(context,"",-1,SQLITE_STATIC); - break; - } - cBuf = sqlite3_malloc(nc); - if( !cBuf ) goto memFail; - nc = (int)(toBase64(bBuf, nb, cBuf) - cBuf); - sqlite3_result_text(context, cBuf, nc, sqlite3_free); - break; - case SQLITE_TEXT: - nc = nv; - nb = 3*((nv+3)/4); /* may overestimate due to LF and padding */ - if( nvMax < nb ){ - sqlite3_result_error(context, "blob from base64 may be too big", -1); - return; - }else if( nb<1 ){ - nb = 1; - } - cBuf = (char *)sqlite3_value_text(av[0]); - if( !cBuf ){ - if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){ - goto memFail; - } - sqlite3_result_zeroblob(context, 0); - break; - } - bBuf = sqlite3_malloc(nb); - if( !bBuf ) goto memFail; - nb = (int)(fromBase64(cBuf, nc, bBuf) - bBuf); - sqlite3_result_blob(context, bBuf, nb, sqlite3_free); - break; - default: - sqlite3_result_error(context, "base64 accepts only blob or text", -1); - return; - } - return; - memFail: - sqlite3_result_error(context, "base64 OOM", -1); -} - -/* -** Establish linkage to running SQLite library. -*/ -#ifndef SQLITE_SHELL_EXTFUNCS -#ifdef _WIN32 - -#endif -int sqlite3_base_init -#else -static int sqlite3_base64_init -#endif -(sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){ - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErr; - return sqlite3_create_function - (db, "base64", 1, - SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8, - 0, base64, 0, 0); -} - -/* -** Define some macros to allow this extension to be built into the shell -** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This -** allows shell.c, as distributed, to have this extension built in. -*/ -#define BASE64_INIT(db) sqlite3_base64_init(db, 0, 0) -#define BASE64_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */ - -/************************* End ../ext/misc/base64.c ********************/ -#undef sqlite3_base_init -#define sqlite3_base_init sqlite3_base85_init -#define OMIT_BASE85_CHECKER -/************************* Begin ../ext/misc/base85.c ******************/ -/* -** 2022-11-16 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This is a utility for converting binary to base85 or vice-versa. -** It can be built as a standalone program or an SQLite3 extension. -** -** Much like base64 representations, base85 can be sent through a -** sane USASCII channel unmolested. It also plays nicely in CSV or -** written as TCL brace-enclosed literals or SQL string literals. -** It is not suited for unmodified use in XML-like documents. -** -** The encoding used resembles Ascii85, but was devised by the author -** (Larry Brasfield) before Mozilla, Adobe, ZMODEM or other Ascii85 -** variant sources existed, in the 1984 timeframe on a VAX mainframe. -** Further, this is an independent implementation of a base85 system. -** Hence, the author has rightfully put this into the public domain. -** -** Base85 numerals are taken from the set of 7-bit USASCII codes, -** excluding control characters and Space ! " ' ( ) { | } ~ Del -** in code order representing digit values 0 to 84 (base 10.) -** -** Groups of 4 bytes, interpreted as big-endian 32-bit values, -** are represented as 5-digit base85 numbers with MS to LS digit -** order. Groups of 1-3 bytes are represented with 2-4 digits, -** still big-endian but 8-24 bit values. (Using big-endian yields -** the simplest transition to byte groups smaller than 4 bytes. -** These byte groups can also be considered base-256 numbers.) -** Groups of 0 bytes are represented with 0 digits and vice-versa. -** No pad characters are used; Encoded base85 numeral sequence -** (aka "group") length maps 1-to-1 to the decoded binary length. -** -** Any character not in the base85 numeral set delimits groups. -** When base85 is streamed or stored in containers of indefinite -** size, newline is used to separate it into sub-sequences of no -** more than 80 digits so that fgets() can be used to read it. -** -** Length limitations are not imposed except that the runtime -** SQLite string or blob length limits are respected. Otherwise, -** any length binary sequence can be represented and recovered. -** Base85 sequences can be concatenated by separating them with -** a non-base85 character; the conversion to binary will then -** be the concatenation of the represented binary sequences. - -** The standalone program either converts base85 on stdin to create -** a binary file or converts a binary file to base85 on stdout. -** Read or make it blurt its help for invocation details. -** -** The SQLite3 extension creates a function, base85(x), which will -** either convert text base85 to a blob or a blob to text base85 -** and return the result (or throw an error for other types.) -** Unless built with OMIT_BASE85_CHECKER defined, it also creates a -** function, is_base85(t), which returns 1 iff the text t contains -** nothing other than base85 numerals and whitespace, or 0 otherwise. -** -** To build the extension: -** Set shell variable SQDIR= -** and variable OPTS to -DOMIT_BASE85_CHECKER if is_base85() unwanted. -** *Nix: gcc -O2 -shared -I$SQDIR $OPTS -fPIC -o base85.so base85.c -** OSX: gcc -O2 -dynamiclib -fPIC -I$SQDIR $OPTS -o base85.dylib base85.c -** Win32: gcc -O2 -shared -I%SQDIR% %OPTS% -o base85.dll base85.c -** Win32: cl /Os -I%SQDIR% %OPTS% base85.c -link -dll -out:base85.dll -** -** To build the standalone program, define PP symbol BASE85_STANDALONE. Eg. -** *Nix or OSX: gcc -O2 -DBASE85_STANDALONE base85.c -o base85 -** Win32: gcc -O2 -DBASE85_STANDALONE -o base85.exe base85.c -** Win32: cl /Os /MD -DBASE85_STANDALONE base85.c -*/ - -#include -#include -#include -#include -#ifndef OMIT_BASE85_CHECKER -# include -#endif - -#ifndef BASE85_STANDALONE - -/* # include "sqlite3ext.h" */ - -SQLITE_EXTENSION_INIT1; - -#else - -# ifdef _WIN32 -# include -# include -# else -# define setmode(fd,m) -# endif - -static char *zHelp = - "Usage: base85 \n" - " is either -r to read or -w to write ,\n" - " content to be converted to/from base85 on stdout/stdin.\n" - " names a binary file to be rendered or created.\n" - " Or, the name '-' refers to the stdin or stdout stream.\n" - ; - -static void sayHelp(){ - printf("%s", zHelp); -} -#endif - -#ifndef U8_TYPEDEF -/* typedef unsigned char u8; */ -#define U8_TYPEDEF -#endif - -/* Classify c according to interval within USASCII set w.r.t. base85 - * Values of 1 and 3 are base85 numerals. Values of 0, 2, or 4 are not. - */ -#define B85_CLASS( c ) (((c)>='#')+((c)>'&')+((c)>='*')+((c)>'z')) - -/* Provide digitValue to b85Numeral offset as a function of above class. */ -static u8 b85_cOffset[] = { 0, '#', 0, '*'-4, 0 }; -#define B85_DNOS( c ) b85_cOffset[B85_CLASS(c)] - -/* Say whether c is a base85 numeral. */ -#define IS_B85( c ) (B85_CLASS(c) & 1) - -#if 0 /* Not used, */ -static u8 base85DigitValue( char c ){ - u8 dv = (u8)(c - '#'); - if( dv>87 ) return 0xff; - return (dv > 3)? dv-3 : dv; -} -#endif - -/* Width of base64 lines. Should be an integer multiple of 5. */ -#define B85_DARK_MAX 80 - - -static char * skipNonB85( char *s, int nc ){ - char c; - while( nc-- > 0 && (c = *s) && !IS_B85(c) ) ++s; - return s; -} - -/* Convert small integer, known to be in 0..84 inclusive, to base85 numeral. - * Do not use the macro form with argument expression having a side-effect.*/ -#if 0 -static char base85Numeral( u8 b ){ - return (b < 4)? (char)(b + '#') : (char)(b - 4 + '*'); -} -#else -# define base85Numeral( dn )\ - ((char)(((dn) < 4)? (char)((dn) + '#') : (char)((dn) - 4 + '*'))) -#endif - -static char *putcs(char *pc, char *s){ - char c; - while( (c = *s++)!=0 ) *pc++ = c; - return pc; -} - -/* Encode a byte buffer into base85 text. If pSep!=0, it's a C string -** to be appended to encoded groups to limit their length to B85_DARK_MAX -** or to terminate the last group (to aid concatenation.) -*/ -static char* toBase85( u8 *pIn, int nbIn, char *pOut, char *pSep ){ - int nCol = 0; - while( nbIn >= 4 ){ - int nco = 5; - unsigned long qbv = (((unsigned long)pIn[0])<<24) | - (pIn[1]<<16) | (pIn[2]<<8) | pIn[3]; - while( nco > 0 ){ - unsigned nqv = (unsigned)(qbv/85UL); - unsigned char dv = qbv - 85UL*nqv; - qbv = nqv; - pOut[--nco] = base85Numeral(dv); - } - nbIn -= 4; - pIn += 4; - pOut += 5; - if( pSep && (nCol += 5)>=B85_DARK_MAX ){ - pOut = putcs(pOut, pSep); - nCol = 0; - } - } - if( nbIn > 0 ){ - int nco = nbIn + 1; - unsigned long qv = *pIn++; - int nbe = 1; - while( nbe++ < nbIn ){ - qv = (qv<<8) | *pIn++; - } - nCol += nco; - while( nco > 0 ){ - u8 dv = (u8)(qv % 85); - qv /= 85; - pOut[--nco] = base85Numeral(dv); - } - pOut += (nbIn+1); - } - if( pSep && nCol>0 ) pOut = putcs(pOut, pSep); - *pOut = 0; - return pOut; -} - -/* Decode base85 text into a byte buffer. */ -static u8* fromBase85( char *pIn, int ncIn, u8 *pOut ){ - if( ncIn>0 && pIn[ncIn-1]=='\n' ) --ncIn; - while( ncIn>0 ){ - static signed char nboi[] = { 0, 0, 1, 2, 3, 4 }; - char *pUse = skipNonB85(pIn, ncIn); - unsigned long qv = 0L; - int nti, nbo; - ncIn -= (pUse - pIn); - pIn = pUse; - nti = (ncIn>5)? 5 : ncIn; - nbo = nboi[nti]; - if( nbo==0 ) break; - while( nti>0 ){ - char c = *pIn++; - u8 cdo = B85_DNOS(c); - --ncIn; - if( cdo==0 ) break; - qv = 85 * qv + (c - cdo); - --nti; - } - nbo -= nti; /* Adjust for early (non-digit) end of group. */ - switch( nbo ){ - case 4: - *pOut++ = (qv >> 24)&0xff; - case 3: - *pOut++ = (qv >> 16)&0xff; - case 2: - *pOut++ = (qv >> 8)&0xff; - case 1: - *pOut++ = qv&0xff; - case 0: - break; - } - } - return pOut; -} - -#ifndef OMIT_BASE85_CHECKER -/* Say whether input char sequence is all (base85 and/or whitespace).*/ -static int allBase85( char *p, int len ){ - char c; - while( len-- > 0 && (c = *p++) != 0 ){ - if( !IS_B85(c) && !isspace(c) ) return 0; - } - return 1; -} -#endif - -#ifndef BASE85_STANDALONE - -# ifndef OMIT_BASE85_CHECKER -/* This function does the work for the SQLite is_base85(t) UDF. */ -static void is_base85(sqlite3_context *context, int na, sqlite3_value *av[]){ - assert(na==1); - switch( sqlite3_value_type(av[0]) ){ - case SQLITE_TEXT: - { - int rv = allBase85( (char *)sqlite3_value_text(av[0]), - sqlite3_value_bytes(av[0]) ); - sqlite3_result_int(context, rv); - } - break; - case SQLITE_NULL: - sqlite3_result_null(context); - break; - default: - sqlite3_result_error(context, "is_base85 accepts only text or NULL", -1); - return; - } -} -# endif - -/* This function does the work for the SQLite base85(x) UDF. */ -static void base85(sqlite3_context *context, int na, sqlite3_value *av[]){ - int nb, nc, nv = sqlite3_value_bytes(av[0]); - int nvMax = sqlite3_limit(sqlite3_context_db_handle(context), - SQLITE_LIMIT_LENGTH, -1); - char *cBuf; - u8 *bBuf; - assert(na==1); - switch( sqlite3_value_type(av[0]) ){ - case SQLITE_BLOB: - nb = nv; - /* ulongs tail newlines tailenc+nul*/ - nc = 5*(nv/4) + nv%4 + nv/64+1 + 2; - if( nvMax < nc ){ - sqlite3_result_error(context, "blob expanded to base85 too big", -1); - return; - } - bBuf = (u8*)sqlite3_value_blob(av[0]); - if( !bBuf ){ - if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){ - goto memFail; - } - sqlite3_result_text(context,"",-1,SQLITE_STATIC); - break; - } - cBuf = sqlite3_malloc(nc); - if( !cBuf ) goto memFail; - nc = (int)(toBase85(bBuf, nb, cBuf, "\n") - cBuf); - sqlite3_result_text(context, cBuf, nc, sqlite3_free); - break; - case SQLITE_TEXT: - nc = nv; - nb = 4*(nv/5) + nv%5; /* may overestimate */ - if( nvMax < nb ){ - sqlite3_result_error(context, "blob from base85 may be too big", -1); - return; - }else if( nb<1 ){ - nb = 1; - } - cBuf = (char *)sqlite3_value_text(av[0]); - if( !cBuf ){ - if( SQLITE_NOMEM==sqlite3_errcode(sqlite3_context_db_handle(context)) ){ - goto memFail; - } - sqlite3_result_zeroblob(context, 0); - break; - } - bBuf = sqlite3_malloc(nb); - if( !bBuf ) goto memFail; - nb = (int)(fromBase85(cBuf, nc, bBuf) - bBuf); - sqlite3_result_blob(context, bBuf, nb, sqlite3_free); - break; - default: - sqlite3_result_error(context, "base85 accepts only blob or text.", -1); - return; - } - return; - memFail: - sqlite3_result_error(context, "base85 OOM", -1); -} - -/* -** Establish linkage to running SQLite library. -*/ -#ifndef SQLITE_SHELL_EXTFUNCS -#ifdef _WIN32 - -#endif -int sqlite3_base_init -#else -static int sqlite3_base85_init -#endif -(sqlite3 *db, char **pzErr, const sqlite3_api_routines *pApi){ - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErr; -# ifndef OMIT_BASE85_CHECKER - { - int rc = sqlite3_create_function - (db, "is_base85", 1, - SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_UTF8, - 0, is_base85, 0, 0); - if( rc!=SQLITE_OK ) return rc; - } -# endif - return sqlite3_create_function - (db, "base85", 1, - SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS|SQLITE_DIRECTONLY|SQLITE_UTF8, - 0, base85, 0, 0); -} - -/* -** Define some macros to allow this extension to be built into the shell -** conveniently, in conjunction with use of SQLITE_SHELL_EXTFUNCS. This -** allows shell.c, as distributed, to have this extension built in. -*/ -# define BASE85_INIT(db) sqlite3_base85_init(db, 0, 0) -# define BASE85_EXPOSE(db, pzErr) /* Not needed, ..._init() does this. */ - -#else /* standalone program */ - -int main(int na, char *av[]){ - int cin; - int rc = 0; - u8 bBuf[4*(B85_DARK_MAX/5)]; - char cBuf[5*(sizeof(bBuf)/4)+2]; - size_t nio; -# ifndef OMIT_BASE85_CHECKER - int b85Clean = 1; -# endif - char rw; - FILE *fb = 0, *foc = 0; - char fmode[3] = "xb"; - if( na < 3 || av[1][0]!='-' || (rw = av[1][1])==0 || (rw!='r' && rw!='w') ){ - sayHelp(); - return 0; - } - fmode[0] = rw; - if( av[2][0]=='-' && av[2][1]==0 ){ - switch( rw ){ - case 'r': - fb = stdin; - setmode(fileno(stdin), O_BINARY); - break; - case 'w': - fb = stdout; - setmode(fileno(stdout), O_BINARY); - break; - } - }else{ - fb = fopen(av[2], fmode); - foc = fb; - } - if( !fb ){ - fprintf(stderr, "Cannot open %s for %c\n", av[2], rw); - rc = 1; - }else{ - switch( rw ){ - case 'r': - while( (nio = fread( bBuf, 1, sizeof(bBuf), fb))>0 ){ - toBase85( bBuf, (int)nio, cBuf, 0 ); - fprintf(stdout, "%s\n", cBuf); - } - break; - case 'w': - while( 0 != fgets(cBuf, sizeof(cBuf), stdin) ){ - int nc = strlen(cBuf); - size_t nbo = fromBase85( cBuf, nc, bBuf ) - bBuf; - if( 1 != fwrite(bBuf, nbo, 1, fb) ) rc = 1; -# ifndef OMIT_BASE85_CHECKER - b85Clean &= allBase85( cBuf, nc ); -# endif - } - break; - default: - sayHelp(); - rc = 1; - } - if( foc ) fclose(foc); - } -# ifndef OMIT_BASE85_CHECKER - if( !b85Clean ){ - fprintf(stderr, "Base85 input had non-base85 dark or control content.\n"); - } -# endif - return rc; -} - -#endif - -/************************* End ../ext/misc/base85.c ********************/ -/************************* Begin ../ext/misc/ieee754.c ******************/ -/* -** 2013-04-17 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This SQLite extension implements functions for the exact display -** and input of IEEE754 Binary64 floating-point numbers. -** -** ieee754(X) -** ieee754(Y,Z) -** -** In the first form, the value X should be a floating-point number. -** The function will return a string of the form 'ieee754(Y,Z)' where -** Y and Z are integers such that X==Y*pow(2,Z). -** -** In the second form, Y and Z are integers which are the mantissa and -** base-2 exponent of a new floating point number. The function returns -** a floating-point value equal to Y*pow(2,Z). -** -** Examples: -** -** ieee754(2.0) -> 'ieee754(2,0)' -** ieee754(45.25) -> 'ieee754(181,-2)' -** ieee754(2, 0) -> 2.0 -** ieee754(181, -2) -> 45.25 -** -** Two additional functions break apart the one-argument ieee754() -** result into separate integer values: -** -** ieee754_mantissa(45.25) -> 181 -** ieee754_exponent(45.25) -> -2 -** -** These functions convert binary64 numbers into blobs and back again. -** -** ieee754_from_blob(x'3ff0000000000000') -> 1.0 -** ieee754_to_blob(1.0) -> x'3ff0000000000000' -** -** In all single-argument functions, if the argument is an 8-byte blob -** then that blob is interpreted as a big-endian binary64 value. -** -** -** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES -** ----------------------------------------------- -** -** This extension in combination with the separate 'decimal' extension -** can be used to compute the exact decimal representation of binary64 -** values. To begin, first compute a table of exponent values: -** -** CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT); -** WITH RECURSIVE c(x,v) AS ( -** VALUES(0,'1') -** UNION ALL -** SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971 -** ) INSERT INTO pow2(x,v) SELECT x, v FROM c; -** WITH RECURSIVE c(x,v) AS ( -** VALUES(-1,'0.5') -** UNION ALL -** SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075 -** ) INSERT INTO pow2(x,v) SELECT x, v FROM c; -** -** Then, to compute the exact decimal representation of a floating -** point value (the value 47.49 is used in the example) do: -** -** WITH c(n) AS (VALUES(47.49)) -** ---------------^^^^^---- Replace with whatever you want -** SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v) -** FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n); -** -** Here is a query to show various boundry values for the binary64 -** number format: -** -** WITH c(name,bin) AS (VALUES -** ('minimum positive value', x'0000000000000001'), -** ('maximum subnormal value', x'000fffffffffffff'), -** ('mininum positive nornal value', x'0010000000000000'), -** ('maximum value', x'7fefffffffffffff')) -** SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v) -** FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin); -** -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include - -/* Mark a function parameter as unused, to suppress nuisance compiler -** warnings. */ -#ifndef UNUSED_PARAMETER -# define UNUSED_PARAMETER(X) (void)(X) -#endif - -/* -** Implementation of the ieee754() function -*/ -static void ieee754func( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - if( argc==1 ){ - sqlite3_int64 m, a; - double r; - int e; - int isNeg; - char zResult[100]; - assert( sizeof(m)==sizeof(r) ); - if( sqlite3_value_type(argv[0])==SQLITE_BLOB - && sqlite3_value_bytes(argv[0])==sizeof(r) - ){ - const unsigned char *x = sqlite3_value_blob(argv[0]); - unsigned int i; - sqlite3_uint64 v = 0; - for(i=0; i>52; - m = a & ((((sqlite3_int64)1)<<52)-1); - if( e==0 ){ - m <<= 1; - }else{ - m |= ((sqlite3_int64)1)<<52; - } - while( e<1075 && m>0 && (m&1)==0 ){ - m >>= 1; - e++; - } - if( isNeg ) m = -m; - } - switch( *(int*)sqlite3_user_data(context) ){ - case 0: - sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)", - m, e-1075); - sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT); - break; - case 1: - sqlite3_result_int64(context, m); - break; - case 2: - sqlite3_result_int(context, e-1075); - break; - } - }else{ - sqlite3_int64 m, e, a; - double r; - int isNeg = 0; - m = sqlite3_value_int64(argv[0]); - e = sqlite3_value_int64(argv[1]); - - /* Limit the range of e. Ticket 22dea1cfdb9151e4 2021-03-02 */ - if( e>10000 ){ - e = 10000; - }else if( e<-10000 ){ - e = -10000; - } - - if( m<0 ){ - isNeg = 1; - m = -m; - if( m<0 ) return; - }else if( m==0 && e>-1000 && e<1000 ){ - sqlite3_result_double(context, 0.0); - return; - } - while( (m>>32)&0xffe00000 ){ - m >>= 1; - e++; - } - while( m!=0 && ((m>>32)&0xfff00000)==0 ){ - m <<= 1; - e--; - } - e += 1075; - if( e<=0 ){ - /* Subnormal */ - if( 1-e >= 64 ){ - m = 0; - }else{ - m >>= 1-e; - } - e = 0; - }else if( e>0x7ff ){ - e = 0x7ff; - } - a = m & ((((sqlite3_int64)1)<<52)-1); - a |= e<<52; - if( isNeg ) a |= ((sqlite3_uint64)1)<<63; - memcpy(&r, &a, sizeof(r)); - sqlite3_result_double(context, r); - } -} - -/* -** Functions to convert between blobs and floats. -*/ -static void ieee754func_from_blob( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - UNUSED_PARAMETER(argc); - if( sqlite3_value_type(argv[0])==SQLITE_BLOB - && sqlite3_value_bytes(argv[0])==sizeof(double) - ){ - double r; - const unsigned char *x = sqlite3_value_blob(argv[0]); - unsigned int i; - sqlite3_uint64 v = 0; - for(i=0; i>= 8; - } - sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT); - } -} - -/* -** SQL Function: ieee754_inc(r,N) -** -** Move the floating point value r by N quantums and return the new -** values. -** -** Behind the scenes: this routine merely casts r into a 64-bit unsigned -** integer, adds N, then casts the value back into float. -** -** Example: To find the smallest positive number: -** -** SELECT ieee754_inc(0.0,+1); -*/ -static void ieee754inc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - double r; - sqlite3_int64 N; - sqlite3_uint64 m1, m2; - double r2; - UNUSED_PARAMETER(argc); - r = sqlite3_value_double(argv[0]); - N = sqlite3_value_int64(argv[1]); - memcpy(&m1, &r, 8); - m2 = m1 + N; - memcpy(&r2, &m2, 8); - sqlite3_result_double(context, r2); -} - - -#ifdef _WIN32 - -#endif -int sqlite3_ieee_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - static const struct { - char *zFName; - int nArg; - int iAux; - void (*xFunc)(sqlite3_context*,int,sqlite3_value**); - } aFunc[] = { - { "ieee754", 1, 0, ieee754func }, - { "ieee754", 2, 0, ieee754func }, - { "ieee754_mantissa", 1, 1, ieee754func }, - { "ieee754_exponent", 1, 2, ieee754func }, - { "ieee754_to_blob", 1, 0, ieee754func_to_blob }, - { "ieee754_from_blob", 1, 0, ieee754func_from_blob }, - { "ieee754_inc", 2, 0, ieee754inc }, - }; - unsigned int i; - int rc = SQLITE_OK; - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; /* Unused parameter */ - for(i=0; i= 0 ) -** for each produced value (independent of production time ordering.) -** -** All parameters must be either integer or convertable to integer. -** The start parameter is required. -** The stop parameter defaults to (1<<32)-1 (aka 4294967295 or 0xffffffff) -** The step parameter defaults to 1 and 0 is treated as 1. -** -** Examples: -** -** SELECT * FROM generate_series(0,100,5); -** -** The query above returns integers from 0 through 100 counting by steps -** of 5. -** -** SELECT * FROM generate_series(0,100); -** -** Integers from 0 through 100 with a step size of 1. -** -** SELECT * FROM generate_series(20) LIMIT 10; -** -** Integers 20 through 29. -** -** SELECT * FROM generate_series(0,-100,-5); -** -** Integers 0 -5 -10 ... -100. -** -** SELECT * FROM generate_series(0,-1); -** -** Empty sequence. -** -** HOW IT WORKS -** -** The generate_series "function" is really a virtual table with the -** following schema: -** -** CREATE TABLE generate_series( -** value, -** start HIDDEN, -** stop HIDDEN, -** step HIDDEN -** ); -** -** The virtual table also has a rowid, logically equivalent to n+1 where -** "n" is the ascending integer in the aforesaid production definition. -** -** Function arguments in queries against this virtual table are translated -** into equality constraints against successive hidden columns. In other -** words, the following pairs of queries are equivalent to each other: -** -** SELECT * FROM generate_series(0,100,5); -** SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5; -** -** SELECT * FROM generate_series(0,100); -** SELECT * FROM generate_series WHERE start=0 AND stop=100; -** -** SELECT * FROM generate_series(20) LIMIT 10; -** SELECT * FROM generate_series WHERE start=20 LIMIT 10; -** -** The generate_series virtual table implementation leaves the xCreate method -** set to NULL. This means that it is not possible to do a CREATE VIRTUAL -** TABLE command with "generate_series" as the USING argument. Instead, there -** is a single generate_series virtual table that is always available without -** having to be created first. -** -** The xBestIndex method looks for equality constraints against the hidden -** start, stop, and step columns, and if present, it uses those constraints -** to bound the sequence of generated values. If the equality constraints -** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step. -** xBestIndex returns a small cost when both start and stop are available, -** and a very large cost if either start or stop are unavailable. This -** encourages the query planner to order joins such that the bounds of the -** series are well-defined. -** -** Update on 2024-08-22: -** xBestIndex now also looks for equality and inequality constraints against -** the value column and uses those constraints as additional bounds against -** the sequence range. Thus, a query like this: -** -** SELECT value FROM generate_series($SA,$EA) -** WHERE value BETWEEN $SB AND $EB; -** -** Is logically the same as: -** -** SELECT value FROM generate_series(max($SA,$SB),min($EA,$EB)); -** -** Constraints on the value column can server as substitutes for constraints -** on the hidden start and stop columns. So, the following two queries -** are equivalent: -** -** SELECT value FROM generate_series($S,$E); -** SELECT value FROM generate_series WHERE value BETWEEN $S and $E; -** -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include -#include - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* -** Return that member of a generate_series(...) sequence whose 0-based -** index is ix. The 0th member is given by smBase. The sequence members -** progress per ix increment by smStep. -*/ -static sqlite3_int64 genSeqMember( - sqlite3_int64 smBase, - sqlite3_int64 smStep, - sqlite3_uint64 ix -){ - static const sqlite3_uint64 mxI64 = - ((sqlite3_uint64)0x7fffffff)<<32 | 0xffffffff; - if( ix>=mxI64 ){ - /* Get ix into signed i64 range. */ - ix -= mxI64; - /* With 2's complement ALU, this next can be 1 step, but is split into - * 2 for UBSAN's satisfaction (and hypothetical 1's complement ALUs.) */ - smBase += (mxI64/2) * smStep; - smBase += (mxI64 - mxI64/2) * smStep; - } - /* Under UBSAN (or on 1's complement machines), must do this last term - * in steps to avoid the dreaded (and harmless) signed multiply overlow. */ - if( ix>=2 ){ - sqlite3_int64 ix2 = (sqlite3_int64)ix/2; - smBase += ix2*smStep; - ix -= ix2; - } - return smBase + ((sqlite3_int64)ix)*smStep; -} - -/* typedef unsigned char u8; */ - -typedef struct SequenceSpec { - sqlite3_int64 iOBase; /* Original starting value ("start") */ - sqlite3_int64 iOTerm; /* Original terminal value ("stop") */ - sqlite3_int64 iBase; /* Starting value to actually use */ - sqlite3_int64 iTerm; /* Terminal value to actually use */ - sqlite3_int64 iStep; /* Increment ("step") */ - sqlite3_uint64 uSeqIndexMax; /* maximum sequence index (aka "n") */ - sqlite3_uint64 uSeqIndexNow; /* Current index during generation */ - sqlite3_int64 iValueNow; /* Current value during generation */ - u8 isNotEOF; /* Sequence generation not exhausted */ - u8 isReversing; /* Sequence is being reverse generated */ -} SequenceSpec; - -/* -** Prepare a SequenceSpec for use in generating an integer series -** given initialized iBase, iTerm and iStep values. Sequence is -** initialized per given isReversing. Other members are computed. -*/ -static void setupSequence( SequenceSpec *pss ){ - int bSameSigns; - pss->uSeqIndexMax = 0; - pss->isNotEOF = 0; - bSameSigns = (pss->iBase < 0)==(pss->iTerm < 0); - if( pss->iTerm < pss->iBase ){ - sqlite3_uint64 nuspan = 0; - if( bSameSigns ){ - nuspan = (sqlite3_uint64)(pss->iBase - pss->iTerm); - }else{ - /* Under UBSAN (or on 1's complement machines), must do this in steps. - * In this clause, iBase>=0 and iTerm<0 . */ - nuspan = 1; - nuspan += pss->iBase; - nuspan += -(pss->iTerm+1); - } - if( pss->iStep<0 ){ - pss->isNotEOF = 1; - if( nuspan==ULONG_MAX ){ - pss->uSeqIndexMax = ( pss->iStep>LLONG_MIN )? nuspan/-pss->iStep : 1; - }else if( pss->iStep>LLONG_MIN ){ - pss->uSeqIndexMax = nuspan/-pss->iStep; - } - } - }else if( pss->iTerm > pss->iBase ){ - sqlite3_uint64 puspan = 0; - if( bSameSigns ){ - puspan = (sqlite3_uint64)(pss->iTerm - pss->iBase); - }else{ - /* Under UBSAN (or on 1's complement machines), must do this in steps. - * In this clause, iTerm>=0 and iBase<0 . */ - puspan = 1; - puspan += pss->iTerm; - puspan += -(pss->iBase+1); - } - if( pss->iStep>0 ){ - pss->isNotEOF = 1; - pss->uSeqIndexMax = puspan/pss->iStep; - } - }else if( pss->iTerm == pss->iBase ){ - pss->isNotEOF = 1; - pss->uSeqIndexMax = 0; - } - pss->uSeqIndexNow = (pss->isReversing)? pss->uSeqIndexMax : 0; - pss->iValueNow = (pss->isReversing) - ? genSeqMember(pss->iBase, pss->iStep, pss->uSeqIndexMax) - : pss->iBase; -} - -/* -** Progress sequence generator to yield next value, if any. -** Leave its state to either yield next value or be at EOF. -** Return whether there is a next value, or 0 at EOF. -*/ -static int progressSequence( SequenceSpec *pss ){ - if( !pss->isNotEOF ) return 0; - if( pss->isReversing ){ - if( pss->uSeqIndexNow > 0 ){ - pss->uSeqIndexNow--; - pss->iValueNow -= pss->iStep; - }else{ - pss->isNotEOF = 0; - } - }else{ - if( pss->uSeqIndexNow < pss->uSeqIndexMax ){ - pss->uSeqIndexNow++; - pss->iValueNow += pss->iStep; - }else{ - pss->isNotEOF = 0; - } - } - return pss->isNotEOF; -} - -/* series_cursor is a subclass of sqlite3_vtab_cursor which will -** serve as the underlying representation of a cursor that scans -** over rows of the result -*/ -typedef struct series_cursor series_cursor; -struct series_cursor { - sqlite3_vtab_cursor base; /* Base class - must be first */ - SequenceSpec ss; /* (this) Derived class data */ -}; - -/* -** The seriesConnect() method is invoked to create a new -** series_vtab that describes the generate_series virtual table. -** -** Think of this routine as the constructor for series_vtab objects. -** -** All this routine needs to do is: -** -** (1) Allocate the series_vtab object and initialize all fields. -** -** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the -** result set of queries against generate_series will look like. -*/ -static int seriesConnect( - sqlite3 *db, - void *pUnused, - int argcUnused, const char *const*argvUnused, - sqlite3_vtab **ppVtab, - char **pzErrUnused -){ - sqlite3_vtab *pNew; - int rc; - -/* Column numbers */ -#define SERIES_COLUMN_VALUE 0 -#define SERIES_COLUMN_START 1 -#define SERIES_COLUMN_STOP 2 -#define SERIES_COLUMN_STEP 3 - - (void)pUnused; - (void)argcUnused; - (void)argvUnused; - (void)pzErrUnused; - rc = sqlite3_declare_vtab(db, - "CREATE TABLE x(value,start hidden,stop hidden,step hidden)"); - if( rc==SQLITE_OK ){ - pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) ); - if( pNew==0 ) return SQLITE_NOMEM; - memset(pNew, 0, sizeof(*pNew)); - sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS); - } - return rc; -} - -/* -** This method is the destructor for series_cursor objects. -*/ -static int seriesDisconnect(sqlite3_vtab *pVtab){ - sqlite3_free(pVtab); - return SQLITE_OK; -} - -/* -** Constructor for a new series_cursor object. -*/ -static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){ - series_cursor *pCur; - (void)pUnused; - pCur = sqlite3_malloc( sizeof(*pCur) ); - if( pCur==0 ) return SQLITE_NOMEM; - memset(pCur, 0, sizeof(*pCur)); - *ppCursor = &pCur->base; - return SQLITE_OK; -} - -/* -** Destructor for a series_cursor. -*/ -static int seriesClose(sqlite3_vtab_cursor *cur){ - sqlite3_free(cur); - return SQLITE_OK; -} - - -/* -** Advance a series_cursor to its next row of output. -*/ -static int seriesNext(sqlite3_vtab_cursor *cur){ - series_cursor *pCur = (series_cursor*)cur; - progressSequence( & pCur->ss ); - return SQLITE_OK; -} - -/* -** Return values of columns for the row at which the series_cursor -** is currently pointing. -*/ -static int seriesColumn( - sqlite3_vtab_cursor *cur, /* The cursor */ - sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ - int i /* Which column to return */ -){ - series_cursor *pCur = (series_cursor*)cur; - sqlite3_int64 x = 0; - switch( i ){ - case SERIES_COLUMN_START: x = pCur->ss.iOBase; break; - case SERIES_COLUMN_STOP: x = pCur->ss.iOTerm; break; - case SERIES_COLUMN_STEP: x = pCur->ss.iStep; break; - default: x = pCur->ss.iValueNow; break; - } - sqlite3_result_int64(ctx, x); - return SQLITE_OK; -} - -#ifndef LARGEST_UINT64 -#define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32)) -#define LARGEST_UINT64 (0xffffffff|(((sqlite3_uint64)0xffffffff)<<32)) -#define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64) -#endif - -/* -** Return the rowid for the current row, logically equivalent to n+1 where -** "n" is the ascending integer in the aforesaid production definition. -*/ -static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ - series_cursor *pCur = (series_cursor*)cur; - sqlite3_uint64 n = pCur->ss.uSeqIndexNow; - *pRowid = (sqlite3_int64)((nss.isNotEOF; -} - -/* True to cause run-time checking of the start=, stop=, and/or step= -** parameters. The only reason to do this is for testing the -** constraint checking logic for virtual tables in the SQLite core. -*/ -#ifndef SQLITE_SERIES_CONSTRAINT_VERIFY -# define SQLITE_SERIES_CONSTRAINT_VERIFY 0 -#endif - -/* -** This method is called to "rewind" the series_cursor object back -** to the first row of output. This method is always called at least -** once prior to any call to seriesColumn() or seriesRowid() or -** seriesEof(). -** -** The query plan selected by seriesBestIndex is passed in the idxNum -** parameter. (idxStr is not used in this implementation.) idxNum -** is a bitmask showing which constraints are available: -** -** 0x0001: start=VALUE -** 0x0002: stop=VALUE -** 0x0004: step=VALUE -** 0x0008: descending order -** 0x0010: ascending order -** 0x0020: LIMIT VALUE -** 0x0040: OFFSET VALUE -** 0x0080: value=VALUE -** 0x0100: value>=VALUE -** 0x0200: value>VALUE -** 0x1000: value<=VALUE -** 0x2000: valuess.iBase = sqlite3_value_int64(argv[i++]); - }else{ - pCur->ss.iBase = 0; - } - if( idxNum & 0x02 ){ - pCur->ss.iTerm = sqlite3_value_int64(argv[i++]); - }else{ - pCur->ss.iTerm = 0xffffffff; - } - if( idxNum & 0x04 ){ - pCur->ss.iStep = sqlite3_value_int64(argv[i++]); - if( pCur->ss.iStep==0 ){ - pCur->ss.iStep = 1; - }else if( pCur->ss.iStep<0 ){ - if( (idxNum & 0x10)==0 ) idxNum |= 0x08; - } - }else{ - pCur->ss.iStep = 1; - } - - /* If there are constraints on the value column but there are - ** no constraints on the start, stop, and step columns, then - ** initialize the default range to be the entire range of 64-bit signed - ** integers. This range will contracted by the value column constraints - ** further below. - */ - if( (idxNum & 0x05)==0 && (idxNum & 0x0380)!=0 ){ - pCur->ss.iBase = SMALLEST_INT64; - } - if( (idxNum & 0x06)==0 && (idxNum & 0x3080)!=0 ){ - pCur->ss.iTerm = LARGEST_INT64; - } - pCur->ss.iOBase = pCur->ss.iBase; - pCur->ss.iOTerm = pCur->ss.iTerm; - - /* Extract the LIMIT and OFFSET values, but do not apply them yet. - ** The range must first be constrained by the limits on value. - */ - if( idxNum & 0x20 ){ - iLimit = sqlite3_value_int64(argv[i++]); - if( idxNum & 0x40 ){ - iOffset = sqlite3_value_int64(argv[i++]); - } - } - - if( idxNum & 0x3380 ){ - /* Extract the maximum range of output values determined by - ** constraints on the "value" column. - */ - if( idxNum & 0x0080 ){ - iMin = iMax = sqlite3_value_int64(argv[i++]); - }else{ - if( idxNum & 0x0300 ){ - iMin = sqlite3_value_int64(argv[i++]); - if( idxNum & 0x0200 ){ - if( iMin==LARGEST_INT64 ){ - returnNoRows = 1; - }else{ - iMin++; - } - } - } - if( idxNum & 0x3000 ){ - iMax = sqlite3_value_int64(argv[i++]); - if( idxNum & 0x2000 ){ - if( iMax==SMALLEST_INT64 ){ - returnNoRows = 1; - }else{ - iMax--; - } - } - } - if( iMin>iMax ){ - returnNoRows = 1; - } - } - - /* Try to reduce the range of values to be generated based on - ** constraints on the "value" column. - */ - if( pCur->ss.iStep>0 ){ - sqlite3_int64 szStep = pCur->ss.iStep; - if( pCur->ss.iBasess.iBase; - pCur->ss.iBase += ((d+szStep-1)/szStep)*szStep; - } - if( pCur->ss.iTerm>iMax ){ - sqlite3_uint64 d = pCur->ss.iTerm - iMax; - pCur->ss.iTerm -= ((d+szStep-1)/szStep)*szStep; - } - }else{ - sqlite3_int64 szStep = -pCur->ss.iStep; - assert( szStep>0 ); - if( pCur->ss.iBase>iMax ){ - sqlite3_uint64 d = pCur->ss.iBase - iMax; - pCur->ss.iBase -= ((d+szStep-1)/szStep)*szStep; - } - if( pCur->ss.iTermss.iTerm; - pCur->ss.iTerm += ((d+szStep-1)/szStep)*szStep; - } - } - } - - /* Apply LIMIT and OFFSET constraints, if any */ - if( idxNum & 0x20 ){ - if( iOffset>0 ){ - pCur->ss.iBase += pCur->ss.iStep*iOffset; - } - if( iLimit>=0 ){ - sqlite3_int64 iTerm; - iTerm = pCur->ss.iBase + (iLimit - 1)*pCur->ss.iStep; - if( pCur->ss.iStep<0 ){ - if( iTerm>pCur->ss.iTerm ) pCur->ss.iTerm = iTerm; - }else{ - if( iTermss.iTerm ) pCur->ss.iTerm = iTerm; - } - } - } - - - for(i=0; iss.iBase = 1; - pCur->ss.iTerm = 0; - pCur->ss.iStep = 1; - } - if( idxNum & 0x08 ){ - pCur->ss.isReversing = pCur->ss.iStep > 0; - }else{ - pCur->ss.isReversing = pCur->ss.iStep < 0; - } - setupSequence( &pCur->ss ); - return SQLITE_OK; -} - -/* -** SQLite will invoke this method one or more times while planning a query -** that uses the generate_series virtual table. This routine needs to create -** a query plan for each invocation and compute an estimated cost for that -** plan. -** -** In this implementation idxNum is used to represent the -** query plan. idxStr is unused. -** -** The query plan is represented by bits in idxNum: -** -** 0x0001 start = $num -** 0x0002 stop = $num -** 0x0004 step = $num -** 0x0008 output is in descending order -** 0x0010 output is in ascending order -** 0x0020 LIMIT $num -** 0x0040 OFFSET $num -** 0x0080 value = $num -** 0x0100 value >= $num -** 0x0200 value > $num -** 0x1000 value <= $num -** 0x2000 value < $num -** -** Only one of 0x0100 or 0x0200 will be returned. Similarly, only -** one of 0x1000 or 0x2000 will be returned. If the 0x0080 is set, then -** none of the 0xff00 bits will be set. -** -** The order of parameters passed to xFilter is as follows: -** -** * The argument to start= if bit 0x0001 is in the idxNum mask -** * The argument to stop= if bit 0x0002 is in the idxNum mask -** * The argument to step= if bit 0x0004 is in the idxNum mask -** * The argument to LIMIT if bit 0x0020 is in the idxNum mask -** * The argument to OFFSET if bit 0x0040 is in the idxNum mask -** * The argument to value=, or value>= or value> if any of -** bits 0x0380 are in the idxNum mask -** * The argument to value<= or value< if either of bits 0x3000 -** are in the mask -** -*/ -static int seriesBestIndex( - sqlite3_vtab *pVTab, - sqlite3_index_info *pIdxInfo -){ - int i, j; /* Loop over constraints */ - int idxNum = 0; /* The query plan bitmask */ -#ifndef ZERO_ARGUMENT_GENERATE_SERIES - int bStartSeen = 0; /* EQ constraint seen on the START column */ -#endif - int unusableMask = 0; /* Mask of unusable constraints */ - int nArg = 0; /* Number of arguments that seriesFilter() expects */ - int aIdx[7]; /* Constraints on start, stop, step, LIMIT, OFFSET, - ** and value. aIdx[5] covers value=, value>=, and - ** value>, aIdx[6] covers value<= and value< */ - const struct sqlite3_index_constraint *pConstraint; - - /* This implementation assumes that the start, stop, and step columns - ** are the last three columns in the virtual table. */ - assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 ); - assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 ); - - aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = aIdx[5] = aIdx[6] = -1; - pConstraint = pIdxInfo->aConstraint; - for(i=0; inConstraint; i++, pConstraint++){ - int iCol; /* 0 for start, 1 for stop, 2 for step */ - int iMask; /* bitmask for those column */ - int op = pConstraint->op; - if( op>=SQLITE_INDEX_CONSTRAINT_LIMIT - && op<=SQLITE_INDEX_CONSTRAINT_OFFSET - ){ - if( pConstraint->usable==0 ){ - /* do nothing */ - }else if( op==SQLITE_INDEX_CONSTRAINT_LIMIT ){ - aIdx[3] = i; - idxNum |= 0x20; - }else{ - assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET ); - aIdx[4] = i; - idxNum |= 0x40; - } - continue; - } - if( pConstraint->iColumniColumn==SERIES_COLUMN_VALUE ){ - switch( op ){ - case SQLITE_INDEX_CONSTRAINT_EQ: - case SQLITE_INDEX_CONSTRAINT_IS: { - idxNum |= 0x0080; - idxNum &= ~0x3300; - aIdx[5] = i; - aIdx[6] = -1; - bStartSeen = 1; - break; - } - case SQLITE_INDEX_CONSTRAINT_GE: { - if( idxNum & 0x0080 ) break; - idxNum |= 0x0100; - idxNum &= ~0x0200; - aIdx[5] = i; - bStartSeen = 1; - break; - } - case SQLITE_INDEX_CONSTRAINT_GT: { - if( idxNum & 0x0080 ) break; - idxNum |= 0x0200; - idxNum &= ~0x0100; - aIdx[5] = i; - bStartSeen = 1; - break; - } - case SQLITE_INDEX_CONSTRAINT_LE: { - if( idxNum & 0x0080 ) break; - idxNum |= 0x1000; - idxNum &= ~0x2000; - aIdx[6] = i; - break; - } - case SQLITE_INDEX_CONSTRAINT_LT: { - if( idxNum & 0x0080 ) break; - idxNum |= 0x2000; - idxNum &= ~0x1000; - aIdx[6] = i; - break; - } - } - } - continue; - } - iCol = pConstraint->iColumn - SERIES_COLUMN_START; - assert( iCol>=0 && iCol<=2 ); - iMask = 1 << iCol; -#ifndef ZERO_ARGUMENT_GENERATE_SERIES - if( iCol==0 && op==SQLITE_INDEX_CONSTRAINT_EQ ){ - bStartSeen = 1; - } -#endif - if( pConstraint->usable==0 ){ - unusableMask |= iMask; - continue; - }else if( op==SQLITE_INDEX_CONSTRAINT_EQ ){ - idxNum |= iMask; - aIdx[iCol] = i; - } - } - if( aIdx[3]==0 ){ - /* Ignore OFFSET if LIMIT is omitted */ - idxNum &= ~0x60; - aIdx[4] = 0; - } - for(i=0; i<7; i++){ - if( (j = aIdx[i])>=0 ){ - pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg; - pIdxInfo->aConstraintUsage[j].omit = - !SQLITE_SERIES_CONSTRAINT_VERIFY || i>=3; - } - } - /* The current generate_column() implementation requires at least one - ** argument (the START value). Legacy versions assumed START=0 if the - ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES - ** to obtain the legacy behavior */ -#ifndef ZERO_ARGUMENT_GENERATE_SERIES - if( !bStartSeen ){ - sqlite3_free(pVTab->zErrMsg); - pVTab->zErrMsg = sqlite3_mprintf( - "first argument to \"generate_series()\" missing or unusable"); - return SQLITE_ERROR; - } -#endif - if( (unusableMask & ~idxNum)!=0 ){ - /* The start, stop, and step columns are inputs. Therefore if there - ** are unusable constraints on any of start, stop, or step then - ** this plan is unusable */ - return SQLITE_CONSTRAINT; - } - if( (idxNum & 0x03)==0x03 ){ - /* Both start= and stop= boundaries are available. This is the - ** the preferred case */ - pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0)); - pIdxInfo->estimatedRows = 1000; - if( pIdxInfo->nOrderBy>=1 && pIdxInfo->aOrderBy[0].iColumn==0 ){ - if( pIdxInfo->aOrderBy[0].desc ){ - idxNum |= 0x08; - }else{ - idxNum |= 0x10; - } - pIdxInfo->orderByConsumed = 1; - } - }else if( (idxNum & 0x21)==0x21 ){ - /* We have start= and LIMIT */ - pIdxInfo->estimatedRows = 2500; - }else{ - /* If either boundary is missing, we have to generate a huge span - ** of numbers. Make this case very expensive so that the query - ** planner will work hard to avoid it. */ - pIdxInfo->estimatedRows = 2147483647; - } - pIdxInfo->idxNum = idxNum; -#ifdef SQLITE_INDEX_SCAN_HEX - pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_HEX; -#endif - return SQLITE_OK; -} - -/* -** This following structure defines all the methods for the -** generate_series virtual table. -*/ -static sqlite3_module seriesModule = { - 0, /* iVersion */ - 0, /* xCreate */ - seriesConnect, /* xConnect */ - seriesBestIndex, /* xBestIndex */ - seriesDisconnect, /* xDisconnect */ - 0, /* xDestroy */ - seriesOpen, /* xOpen - open a cursor */ - seriesClose, /* xClose - close a cursor */ - seriesFilter, /* xFilter - configure scan constraints */ - seriesNext, /* xNext - advance a cursor */ - seriesEof, /* xEof - check for end of scan */ - seriesColumn, /* xColumn - read data */ - seriesRowid, /* xRowid - read data */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindMethod */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0, /* xShadowName */ - 0 /* xIntegrity */ -}; - -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -#ifdef _WIN32 - -#endif -int sqlite3_series_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - SQLITE_EXTENSION_INIT2(pApi); -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){ - *pzErrMsg = sqlite3_mprintf( - "generate_series() requires SQLite 3.8.12 or later"); - return SQLITE_ERROR; - } - rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0); -#endif - return rc; -} - -/************************* End ../ext/misc/series.c ********************/ -/************************* Begin ../ext/misc/regexp.c ******************/ -/* -** 2012-11-13 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** The code in this file implements a compact but reasonably -** efficient regular-expression matcher for posix extended regular -** expressions against UTF8 text. -** -** This file is an SQLite extension. It registers a single function -** named "regexp(A,B)" where A is the regular expression and B is the -** string to be matched. By registering this function, SQLite will also -** then implement the "B regexp A" operator. Note that with the function -** the regular expression comes first, but with the operator it comes -** second. -** -** The following regular expression syntax is supported: -** -** X* zero or more occurrences of X -** X+ one or more occurrences of X -** X? zero or one occurrences of X -** X{p,q} between p and q occurrences of X -** (X) match X -** X|Y X or Y -** ^X X occurring at the beginning of the string -** X$ X occurring at the end of the string -** . Match any single character -** \c Character c where c is one of \{}()[]|*+?. -** \c C-language escapes for c in afnrtv. ex: \t or \n -** \uXXXX Where XXXX is exactly 4 hex digits, unicode value XXXX -** \xXX Where XX is exactly 2 hex digits, unicode value XX -** [abc] Any single character from the set abc -** [^abc] Any single character not in the set abc -** [a-z] Any single character in the range a-z -** [^a-z] Any single character not in the range a-z -** \b Word boundary -** \w Word character. [A-Za-z0-9_] -** \W Non-word character -** \d Digit -** \D Non-digit -** \s Whitespace character -** \S Non-whitespace character -** -** A nondeterministic finite automaton (NFA) is used for matching, so the -** performance is bounded by O(N*M) where N is the size of the regular -** expression and M is the size of the input string. The matcher never -** exhibits exponential behavior. Note that the X{p,q} operator expands -** to p copies of X following by q-p copies of X? and that the size of the -** regular expression in the O(N*M) performance bound is computed after -** this expansion. -*/ -#include -#include -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 - -/* -** The following #defines change the names of some functions implemented in -** this file to prevent name collisions with C-library functions of the -** same name. -*/ -#define re_match sqlite3re_match -#define re_compile sqlite3re_compile -#define re_free sqlite3re_free - -/* The end-of-input character */ -#define RE_EOF 0 /* End of input */ -#define RE_START 0xfffffff /* Start of input - larger than an UTF-8 */ - -/* The NFA is implemented as sequence of opcodes taken from the following -** set. Each opcode has a single integer argument. -*/ -#define RE_OP_MATCH 1 /* Match the one character in the argument */ -#define RE_OP_ANY 2 /* Match any one character. (Implements ".") */ -#define RE_OP_ANYSTAR 3 /* Special optimized version of .* */ -#define RE_OP_FORK 4 /* Continue to both next and opcode at iArg */ -#define RE_OP_GOTO 5 /* Jump to opcode at iArg */ -#define RE_OP_ACCEPT 6 /* Halt and indicate a successful match */ -#define RE_OP_CC_INC 7 /* Beginning of a [...] character class */ -#define RE_OP_CC_EXC 8 /* Beginning of a [^...] character class */ -#define RE_OP_CC_VALUE 9 /* Single value in a character class */ -#define RE_OP_CC_RANGE 10 /* Range of values in a character class */ -#define RE_OP_WORD 11 /* Perl word character [A-Za-z0-9_] */ -#define RE_OP_NOTWORD 12 /* Not a perl word character */ -#define RE_OP_DIGIT 13 /* digit: [0-9] */ -#define RE_OP_NOTDIGIT 14 /* Not a digit */ -#define RE_OP_SPACE 15 /* space: [ \t\n\r\v\f] */ -#define RE_OP_NOTSPACE 16 /* Not a digit */ -#define RE_OP_BOUNDARY 17 /* Boundary between word and non-word */ -#define RE_OP_ATSTART 18 /* Currently at the start of the string */ - -#if defined(SQLITE_DEBUG) -/* Opcode names used for symbolic debugging */ -static const char *ReOpName[] = { - "EOF", - "MATCH", - "ANY", - "ANYSTAR", - "FORK", - "GOTO", - "ACCEPT", - "CC_INC", - "CC_EXC", - "CC_VALUE", - "CC_RANGE", - "WORD", - "NOTWORD", - "DIGIT", - "NOTDIGIT", - "SPACE", - "NOTSPACE", - "BOUNDARY", - "ATSTART", -}; -#endif /* SQLITE_DEBUG */ - - -/* Each opcode is a "state" in the NFA */ -typedef unsigned short ReStateNumber; - -/* Because this is an NFA and not a DFA, multiple states can be active at -** once. An instance of the following object records all active states in -** the NFA. The implementation is optimized for the common case where the -** number of actives states is small. -*/ -typedef struct ReStateSet { - unsigned nState; /* Number of current states */ - ReStateNumber *aState; /* Current states */ -} ReStateSet; - -/* An input string read one character at a time. -*/ -typedef struct ReInput ReInput; -struct ReInput { - const unsigned char *z; /* All text */ - int i; /* Next byte to read */ - int mx; /* EOF when i>=mx */ -}; - -/* A compiled NFA (or an NFA that is in the process of being compiled) is -** an instance of the following object. -*/ -typedef struct ReCompiled ReCompiled; -struct ReCompiled { - ReInput sIn; /* Regular expression text */ - const char *zErr; /* Error message to return */ - char *aOp; /* Operators for the virtual machine */ - int *aArg; /* Arguments to each operator */ - unsigned (*xNextChar)(ReInput*); /* Next character function */ - unsigned char zInit[12]; /* Initial text to match */ - int nInit; /* Number of bytes in zInit */ - unsigned nState; /* Number of entries in aOp[] and aArg[] */ - unsigned nAlloc; /* Slots allocated for aOp[] and aArg[] */ -}; - -/* Add a state to the given state set if it is not already there */ -static void re_add_state(ReStateSet *pSet, int newState){ - unsigned i; - for(i=0; inState; i++) if( pSet->aState[i]==newState ) return; - pSet->aState[pSet->nState++] = (ReStateNumber)newState; -} - -/* Extract the next unicode character from *pzIn and return it. Advance -** *pzIn to the first byte past the end of the character returned. To -** be clear: this routine converts utf8 to unicode. This routine is -** optimized for the common case where the next character is a single byte. -*/ -static unsigned re_next_char(ReInput *p){ - unsigned c; - if( p->i>=p->mx ) return 0; - c = p->z[p->i++]; - if( c>=0x80 ){ - if( (c&0xe0)==0xc0 && p->imx && (p->z[p->i]&0xc0)==0x80 ){ - c = (c&0x1f)<<6 | (p->z[p->i++]&0x3f); - if( c<0x80 ) c = 0xfffd; - }else if( (c&0xf0)==0xe0 && p->i+1mx && (p->z[p->i]&0xc0)==0x80 - && (p->z[p->i+1]&0xc0)==0x80 ){ - c = (c&0x0f)<<12 | ((p->z[p->i]&0x3f)<<6) | (p->z[p->i+1]&0x3f); - p->i += 2; - if( c<=0x7ff || (c>=0xd800 && c<=0xdfff) ) c = 0xfffd; - }else if( (c&0xf8)==0xf0 && p->i+2mx && (p->z[p->i]&0xc0)==0x80 - && (p->z[p->i+1]&0xc0)==0x80 && (p->z[p->i+2]&0xc0)==0x80 ){ - c = (c&0x07)<<18 | ((p->z[p->i]&0x3f)<<12) | ((p->z[p->i+1]&0x3f)<<6) - | (p->z[p->i+2]&0x3f); - p->i += 3; - if( c<=0xffff || c>0x10ffff ) c = 0xfffd; - }else{ - c = 0xfffd; - } - } - return c; -} -static unsigned re_next_char_nocase(ReInput *p){ - unsigned c = re_next_char(p); - if( c>='A' && c<='Z' ) c += 'a' - 'A'; - return c; -} - -/* Return true if c is a perl "word" character: [A-Za-z0-9_] */ -static int re_word_char(int c){ - return (c>='0' && c<='9') || (c>='a' && c<='z') - || (c>='A' && c<='Z') || c=='_'; -} - -/* Return true if c is a "digit" character: [0-9] */ -static int re_digit_char(int c){ - return (c>='0' && c<='9'); -} - -/* Return true if c is a perl "space" character: [ \t\r\n\v\f] */ -static int re_space_char(int c){ - return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f'; -} - -/* Run a compiled regular expression on the zero-terminated input -** string zIn[]. Return true on a match and false if there is no match. -*/ -static int re_match(ReCompiled *pRe, const unsigned char *zIn, int nIn){ - ReStateSet aStateSet[2], *pThis, *pNext; - ReStateNumber aSpace[100]; - ReStateNumber *pToFree; - unsigned int i = 0; - unsigned int iSwap = 0; - int c = RE_START; - int cPrev = 0; - int rc = 0; - ReInput in; - - in.z = zIn; - in.i = 0; - in.mx = nIn>=0 ? nIn : (int)strlen((char const*)zIn); - - /* Look for the initial prefix match, if there is one. */ - if( pRe->nInit ){ - unsigned char x = pRe->zInit[0]; - while( in.i+pRe->nInit<=in.mx - && (zIn[in.i]!=x || - strncmp((const char*)zIn+in.i, (const char*)pRe->zInit, pRe->nInit)!=0) - ){ - in.i++; - } - if( in.i+pRe->nInit>in.mx ) return 0; - c = RE_START-1; - } - - if( pRe->nState<=(sizeof(aSpace)/(sizeof(aSpace[0])*2)) ){ - pToFree = 0; - aStateSet[0].aState = aSpace; - }else{ - pToFree = sqlite3_malloc64( sizeof(ReStateNumber)*2*pRe->nState ); - if( pToFree==0 ) return -1; - aStateSet[0].aState = pToFree; - } - aStateSet[1].aState = &aStateSet[0].aState[pRe->nState]; - pNext = &aStateSet[1]; - pNext->nState = 0; - re_add_state(pNext, 0); - while( c!=RE_EOF && pNext->nState>0 ){ - cPrev = c; - c = pRe->xNextChar(&in); - pThis = pNext; - pNext = &aStateSet[iSwap]; - iSwap = 1 - iSwap; - pNext->nState = 0; - for(i=0; inState; i++){ - int x = pThis->aState[i]; - switch( pRe->aOp[x] ){ - case RE_OP_MATCH: { - if( pRe->aArg[x]==c ) re_add_state(pNext, x+1); - break; - } - case RE_OP_ATSTART: { - if( cPrev==RE_START ) re_add_state(pThis, x+1); - break; - } - case RE_OP_ANY: { - if( c!=0 ) re_add_state(pNext, x+1); - break; - } - case RE_OP_WORD: { - if( re_word_char(c) ) re_add_state(pNext, x+1); - break; - } - case RE_OP_NOTWORD: { - if( !re_word_char(c) && c!=0 ) re_add_state(pNext, x+1); - break; - } - case RE_OP_DIGIT: { - if( re_digit_char(c) ) re_add_state(pNext, x+1); - break; - } - case RE_OP_NOTDIGIT: { - if( !re_digit_char(c) && c!=0 ) re_add_state(pNext, x+1); - break; - } - case RE_OP_SPACE: { - if( re_space_char(c) ) re_add_state(pNext, x+1); - break; - } - case RE_OP_NOTSPACE: { - if( !re_space_char(c) && c!=0 ) re_add_state(pNext, x+1); - break; - } - case RE_OP_BOUNDARY: { - if( re_word_char(c)!=re_word_char(cPrev) ) re_add_state(pThis, x+1); - break; - } - case RE_OP_ANYSTAR: { - re_add_state(pNext, x); - re_add_state(pThis, x+1); - break; - } - case RE_OP_FORK: { - re_add_state(pThis, x+pRe->aArg[x]); - re_add_state(pThis, x+1); - break; - } - case RE_OP_GOTO: { - re_add_state(pThis, x+pRe->aArg[x]); - break; - } - case RE_OP_ACCEPT: { - rc = 1; - goto re_match_end; - } - case RE_OP_CC_EXC: { - if( c==0 ) break; - /* fall-through */ goto re_op_cc_inc; - } - case RE_OP_CC_INC: re_op_cc_inc: { - int j = 1; - int n = pRe->aArg[x]; - int hit = 0; - for(j=1; j>0 && jaOp[x+j]==RE_OP_CC_VALUE ){ - if( pRe->aArg[x+j]==c ){ - hit = 1; - j = -1; - } - }else{ - if( pRe->aArg[x+j]<=c && pRe->aArg[x+j+1]>=c ){ - hit = 1; - j = -1; - }else{ - j++; - } - } - } - if( pRe->aOp[x]==RE_OP_CC_EXC ) hit = !hit; - if( hit ) re_add_state(pNext, x+n); - break; - } - } - } - } - for(i=0; inState; i++){ - int x = pNext->aState[i]; - while( pRe->aOp[x]==RE_OP_GOTO ) x += pRe->aArg[x]; - if( pRe->aOp[x]==RE_OP_ACCEPT ){ rc = 1; break; } - } -re_match_end: - sqlite3_free(pToFree); - return rc; -} - -/* Resize the opcode and argument arrays for an RE under construction. -*/ -static int re_resize(ReCompiled *p, int N){ - char *aOp; - int *aArg; - aOp = sqlite3_realloc64(p->aOp, N*sizeof(p->aOp[0])); - if( aOp==0 ) return 1; - p->aOp = aOp; - aArg = sqlite3_realloc64(p->aArg, N*sizeof(p->aArg[0])); - if( aArg==0 ) return 1; - p->aArg = aArg; - p->nAlloc = N; - return 0; -} - -/* Insert a new opcode and argument into an RE under construction. The -** insertion point is just prior to existing opcode iBefore. -*/ -static int re_insert(ReCompiled *p, int iBefore, int op, int arg){ - int i; - if( p->nAlloc<=p->nState && re_resize(p, p->nAlloc*2) ) return 0; - for(i=p->nState; i>iBefore; i--){ - p->aOp[i] = p->aOp[i-1]; - p->aArg[i] = p->aArg[i-1]; - } - p->nState++; - p->aOp[iBefore] = (char)op; - p->aArg[iBefore] = arg; - return iBefore; -} - -/* Append a new opcode and argument to the end of the RE under construction. -*/ -static int re_append(ReCompiled *p, int op, int arg){ - return re_insert(p, p->nState, op, arg); -} - -/* Make a copy of N opcodes starting at iStart onto the end of the RE -** under construction. -*/ -static void re_copy(ReCompiled *p, int iStart, int N){ - if( p->nState+N>=p->nAlloc && re_resize(p, p->nAlloc*2+N) ) return; - memcpy(&p->aOp[p->nState], &p->aOp[iStart], N*sizeof(p->aOp[0])); - memcpy(&p->aArg[p->nState], &p->aArg[iStart], N*sizeof(p->aArg[0])); - p->nState += N; -} - -/* Return true if c is a hexadecimal digit character: [0-9a-fA-F] -** If c is a hex digit, also set *pV = (*pV)*16 + valueof(c). If -** c is not a hex digit *pV is unchanged. -*/ -static int re_hex(int c, int *pV){ - if( c>='0' && c<='9' ){ - c -= '0'; - }else if( c>='a' && c<='f' ){ - c -= 'a' - 10; - }else if( c>='A' && c<='F' ){ - c -= 'A' - 10; - }else{ - return 0; - } - *pV = (*pV)*16 + (c & 0xff); - return 1; -} - -/* A backslash character has been seen, read the next character and -** return its interpretation. -*/ -static unsigned re_esc_char(ReCompiled *p){ - static const char zEsc[] = "afnrtv\\()*.+?[$^{|}]"; - static const char zTrans[] = "\a\f\n\r\t\v"; - int i, v = 0; - char c; - if( p->sIn.i>=p->sIn.mx ) return 0; - c = p->sIn.z[p->sIn.i]; - if( c=='u' && p->sIn.i+4sIn.mx ){ - const unsigned char *zIn = p->sIn.z + p->sIn.i; - if( re_hex(zIn[1],&v) - && re_hex(zIn[2],&v) - && re_hex(zIn[3],&v) - && re_hex(zIn[4],&v) - ){ - p->sIn.i += 5; - return v; - } - } - if( c=='x' && p->sIn.i+2sIn.mx ){ - const unsigned char *zIn = p->sIn.z + p->sIn.i; - if( re_hex(zIn[1],&v) - && re_hex(zIn[2],&v) - ){ - p->sIn.i += 3; - return v; - } - } - for(i=0; zEsc[i] && zEsc[i]!=c; i++){} - if( zEsc[i] ){ - if( i<6 ) c = zTrans[i]; - p->sIn.i++; - }else{ - p->zErr = "unknown \\ escape"; - } - return c; -} - -/* Forward declaration */ -static const char *re_subcompile_string(ReCompiled*); - -/* Peek at the next byte of input */ -static unsigned char rePeek(ReCompiled *p){ - return p->sIn.isIn.mx ? p->sIn.z[p->sIn.i] : 0; -} - -/* Compile RE text into a sequence of opcodes. Continue up to the -** first unmatched ")" character, then return. If an error is found, -** return a pointer to the error message string. -*/ -static const char *re_subcompile_re(ReCompiled *p){ - const char *zErr; - int iStart, iEnd, iGoto; - iStart = p->nState; - zErr = re_subcompile_string(p); - if( zErr ) return zErr; - while( rePeek(p)=='|' ){ - iEnd = p->nState; - re_insert(p, iStart, RE_OP_FORK, iEnd + 2 - iStart); - iGoto = re_append(p, RE_OP_GOTO, 0); - p->sIn.i++; - zErr = re_subcompile_string(p); - if( zErr ) return zErr; - p->aArg[iGoto] = p->nState - iGoto; - } - return 0; -} - -/* Compile an element of regular expression text (anything that can be -** an operand to the "|" operator). Return NULL on success or a pointer -** to the error message if there is a problem. -*/ -static const char *re_subcompile_string(ReCompiled *p){ - int iPrev = -1; - int iStart; - unsigned c; - const char *zErr; - while( (c = p->xNextChar(&p->sIn))!=0 ){ - iStart = p->nState; - switch( c ){ - case '|': - case ')': { - p->sIn.i--; - return 0; - } - case '(': { - zErr = re_subcompile_re(p); - if( zErr ) return zErr; - if( rePeek(p)!=')' ) return "unmatched '('"; - p->sIn.i++; - break; - } - case '.': { - if( rePeek(p)=='*' ){ - re_append(p, RE_OP_ANYSTAR, 0); - p->sIn.i++; - }else{ - re_append(p, RE_OP_ANY, 0); - } - break; - } - case '*': { - if( iPrev<0 ) return "'*' without operand"; - re_insert(p, iPrev, RE_OP_GOTO, p->nState - iPrev + 1); - re_append(p, RE_OP_FORK, iPrev - p->nState + 1); - break; - } - case '+': { - if( iPrev<0 ) return "'+' without operand"; - re_append(p, RE_OP_FORK, iPrev - p->nState); - break; - } - case '?': { - if( iPrev<0 ) return "'?' without operand"; - re_insert(p, iPrev, RE_OP_FORK, p->nState - iPrev+1); - break; - } - case '$': { - re_append(p, RE_OP_MATCH, RE_EOF); - break; - } - case '^': { - re_append(p, RE_OP_ATSTART, 0); - break; - } - case '{': { - int m = 0, n = 0; - int sz, j; - if( iPrev<0 ) return "'{m,n}' without operand"; - while( (c=rePeek(p))>='0' && c<='9' ){ m = m*10 + c - '0'; p->sIn.i++; } - n = m; - if( c==',' ){ - p->sIn.i++; - n = 0; - while( (c=rePeek(p))>='0' && c<='9' ){ n = n*10 + c-'0'; p->sIn.i++; } - } - if( c!='}' ) return "unmatched '{'"; - if( n>0 && nsIn.i++; - sz = p->nState - iPrev; - if( m==0 ){ - if( n==0 ) return "both m and n are zero in '{m,n}'"; - re_insert(p, iPrev, RE_OP_FORK, sz+1); - iPrev++; - n--; - }else{ - for(j=1; j0 ){ - re_append(p, RE_OP_FORK, -sz); - } - break; - } - case '[': { - unsigned int iFirst = p->nState; - if( rePeek(p)=='^' ){ - re_append(p, RE_OP_CC_EXC, 0); - p->sIn.i++; - }else{ - re_append(p, RE_OP_CC_INC, 0); - } - while( (c = p->xNextChar(&p->sIn))!=0 ){ - if( c=='[' && rePeek(p)==':' ){ - return "POSIX character classes not supported"; - } - if( c=='\\' ) c = re_esc_char(p); - if( rePeek(p)=='-' ){ - re_append(p, RE_OP_CC_RANGE, c); - p->sIn.i++; - c = p->xNextChar(&p->sIn); - if( c=='\\' ) c = re_esc_char(p); - re_append(p, RE_OP_CC_RANGE, c); - }else{ - re_append(p, RE_OP_CC_VALUE, c); - } - if( rePeek(p)==']' ){ p->sIn.i++; break; } - } - if( c==0 ) return "unclosed '['"; - if( p->nState>iFirst ) p->aArg[iFirst] = p->nState - iFirst; - break; - } - case '\\': { - int specialOp = 0; - switch( rePeek(p) ){ - case 'b': specialOp = RE_OP_BOUNDARY; break; - case 'd': specialOp = RE_OP_DIGIT; break; - case 'D': specialOp = RE_OP_NOTDIGIT; break; - case 's': specialOp = RE_OP_SPACE; break; - case 'S': specialOp = RE_OP_NOTSPACE; break; - case 'w': specialOp = RE_OP_WORD; break; - case 'W': specialOp = RE_OP_NOTWORD; break; - } - if( specialOp ){ - p->sIn.i++; - re_append(p, specialOp, 0); - }else{ - c = re_esc_char(p); - re_append(p, RE_OP_MATCH, c); - } - break; - } - default: { - re_append(p, RE_OP_MATCH, c); - break; - } - } - iPrev = iStart; - } - return 0; -} - -/* Free and reclaim all the memory used by a previously compiled -** regular expression. Applications should invoke this routine once -** for every call to re_compile() to avoid memory leaks. -*/ -static void re_free(ReCompiled *pRe){ - if( pRe ){ - sqlite3_free(pRe->aOp); - sqlite3_free(pRe->aArg); - sqlite3_free(pRe); - } -} - -/* -** Compile a textual regular expression in zIn[] into a compiled regular -** expression suitable for us by re_match() and return a pointer to the -** compiled regular expression in *ppRe. Return NULL on success or an -** error message if something goes wrong. -*/ -static const char *re_compile(ReCompiled **ppRe, const char *zIn, int noCase){ - ReCompiled *pRe; - const char *zErr; - int i, j; - - *ppRe = 0; - pRe = sqlite3_malloc( sizeof(*pRe) ); - if( pRe==0 ){ - return "out of memory"; - } - memset(pRe, 0, sizeof(*pRe)); - pRe->xNextChar = noCase ? re_next_char_nocase : re_next_char; - if( re_resize(pRe, 30) ){ - re_free(pRe); - return "out of memory"; - } - if( zIn[0]=='^' ){ - zIn++; - }else{ - re_append(pRe, RE_OP_ANYSTAR, 0); - } - pRe->sIn.z = (unsigned char*)zIn; - pRe->sIn.i = 0; - pRe->sIn.mx = (int)strlen(zIn); - zErr = re_subcompile_re(pRe); - if( zErr ){ - re_free(pRe); - return zErr; - } - if( pRe->sIn.i>=pRe->sIn.mx ){ - re_append(pRe, RE_OP_ACCEPT, 0); - *ppRe = pRe; - }else{ - re_free(pRe); - return "unrecognized character"; - } - - /* The following is a performance optimization. If the regex begins with - ** ".*" (if the input regex lacks an initial "^") and afterwards there are - ** one or more matching characters, enter those matching characters into - ** zInit[]. The re_match() routine can then search ahead in the input - ** string looking for the initial match without having to run the whole - ** regex engine over the string. Do not worry about trying to match - ** unicode characters beyond plane 0 - those are very rare and this is - ** just an optimization. */ - if( pRe->aOp[0]==RE_OP_ANYSTAR && !noCase ){ - for(j=0, i=1; j<(int)sizeof(pRe->zInit)-2 && pRe->aOp[i]==RE_OP_MATCH; i++){ - unsigned x = pRe->aArg[i]; - if( x<=0x7f ){ - pRe->zInit[j++] = (unsigned char)x; - }else if( x<=0x7ff ){ - pRe->zInit[j++] = (unsigned char)(0xc0 | (x>>6)); - pRe->zInit[j++] = 0x80 | (x&0x3f); - }else if( x<=0xffff ){ - pRe->zInit[j++] = (unsigned char)(0xe0 | (x>>12)); - pRe->zInit[j++] = 0x80 | ((x>>6)&0x3f); - pRe->zInit[j++] = 0x80 | (x&0x3f); - }else{ - break; - } - } - if( j>0 && pRe->zInit[j-1]==0 ) j--; - pRe->nInit = j; - } - return pRe->zErr; -} - -/* -** Implementation of the regexp() SQL function. This function implements -** the build-in REGEXP operator. The first argument to the function is the -** pattern and the second argument is the string. So, the SQL statements: -** -** A REGEXP B -** -** is implemented as regexp(B,A). -*/ -static void re_sql_func( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - ReCompiled *pRe; /* Compiled regular expression */ - const char *zPattern; /* The regular expression */ - const unsigned char *zStr;/* String being searched */ - const char *zErr; /* Compile error message */ - int setAux = 0; /* True to invoke sqlite3_set_auxdata() */ - - (void)argc; /* Unused */ - pRe = sqlite3_get_auxdata(context, 0); - if( pRe==0 ){ - zPattern = (const char*)sqlite3_value_text(argv[0]); - if( zPattern==0 ) return; - zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0); - if( zErr ){ - re_free(pRe); - sqlite3_result_error(context, zErr, -1); - return; - } - if( pRe==0 ){ - sqlite3_result_error_nomem(context); - return; - } - setAux = 1; - } - zStr = (const unsigned char*)sqlite3_value_text(argv[1]); - if( zStr!=0 ){ - sqlite3_result_int(context, re_match(pRe, zStr, -1)); - } - if( setAux ){ - sqlite3_set_auxdata(context, 0, pRe, (void(*)(void*))re_free); - } -} - -#if defined(SQLITE_DEBUG) -/* -** This function is used for testing and debugging only. It is only available -** if the SQLITE_DEBUG compile-time option is used. -** -** Compile a regular expression and then convert the compiled expression into -** text and return that text. -*/ -static void re_bytecode_func( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const char *zPattern; - const char *zErr; - ReCompiled *pRe; - sqlite3_str *pStr; - int i; - int n; - char *z; - (void)argc; - - zPattern = (const char*)sqlite3_value_text(argv[0]); - if( zPattern==0 ) return; - zErr = re_compile(&pRe, zPattern, sqlite3_user_data(context)!=0); - if( zErr ){ - re_free(pRe); - sqlite3_result_error(context, zErr, -1); - return; - } - if( pRe==0 ){ - sqlite3_result_error_nomem(context); - return; - } - pStr = sqlite3_str_new(0); - if( pStr==0 ) goto re_bytecode_func_err; - if( pRe->nInit>0 ){ - sqlite3_str_appendf(pStr, "INIT "); - for(i=0; inInit; i++){ - sqlite3_str_appendf(pStr, "%02x", pRe->zInit[i]); - } - sqlite3_str_appendf(pStr, "\n"); - } - for(i=0; (unsigned)inState; i++){ - sqlite3_str_appendf(pStr, "%-8s %4d\n", - ReOpName[(unsigned char)pRe->aOp[i]], pRe->aArg[i]); - } - n = sqlite3_str_length(pStr); - z = sqlite3_str_finish(pStr); - if( n==0 ){ - sqlite3_free(z); - }else{ - sqlite3_result_text(context, z, n-1, sqlite3_free); - } - -re_bytecode_func_err: - re_free(pRe); -} - -#endif /* SQLITE_DEBUG */ - - -/* -** Invoke this routine to register the regexp() function with the -** SQLite database connection. -*/ -#ifdef _WIN32 - -#endif -int sqlite3_regexp_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; /* Unused */ - rc = sqlite3_create_function(db, "regexp", 2, - SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, - 0, re_sql_func, 0, 0); - if( rc==SQLITE_OK ){ - /* The regexpi(PATTERN,STRING) function is a case-insensitive version - ** of regexp(PATTERN,STRING). */ - rc = sqlite3_create_function(db, "regexpi", 2, - SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, - (void*)db, re_sql_func, 0, 0); -#if defined(SQLITE_DEBUG) - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "regexp_bytecode", 1, - SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, - 0, re_bytecode_func, 0, 0); - } -#endif /* SQLITE_DEBUG */ - } - return rc; -} - -/************************* End ../ext/misc/regexp.c ********************/ -#ifndef SQLITE_SHELL_FIDDLE -/************************* Begin ../ext/misc/fileio.c ******************/ -/* -** 2014-06-13 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This SQLite extension implements SQL functions readfile() and -** writefile(), and eponymous virtual type "fsdir". -** -** WRITEFILE(FILE, DATA [, MODE [, MTIME]]): -** -** If neither of the optional arguments is present, then this UDF -** function writes blob DATA to file FILE. If successful, the number -** of bytes written is returned. If an error occurs, NULL is returned. -** -** If the first option argument - MODE - is present, then it must -** be passed an integer value that corresponds to a POSIX mode -** value (file type + permissions, as returned in the stat.st_mode -** field by the stat() system call). Three types of files may -** be written/created: -** -** regular files: (mode & 0170000)==0100000 -** symbolic links: (mode & 0170000)==0120000 -** directories: (mode & 0170000)==0040000 -** -** For a directory, the DATA is ignored. For a symbolic link, it is -** interpreted as text and used as the target of the link. For a -** regular file, it is interpreted as a blob and written into the -** named file. Regardless of the type of file, its permissions are -** set to (mode & 0777) before returning. -** -** If the optional MTIME argument is present, then it is interpreted -** as an integer - the number of seconds since the unix epoch. The -** modification-time of the target file is set to this value before -** returning. -** -** If five or more arguments are passed to this function and an -** error is encountered, an exception is raised. -** -** READFILE(FILE): -** -** Read and return the contents of file FILE (type blob) from disk. -** -** FSDIR: -** -** Used as follows: -** -** SELECT * FROM fsdir($path [, $dir]); -** -** Parameter $path is an absolute or relative pathname. If the file that it -** refers to does not exist, it is an error. If the path refers to a regular -** file or symbolic link, it returns a single row. Or, if the path refers -** to a directory, it returns one row for the directory, and one row for each -** file within the hierarchy rooted at $path. -** -** Each row has the following columns: -** -** name: Path to file or directory (text value). -** mode: Value of stat.st_mode for directory entry (an integer). -** mtime: Value of stat.st_mtime for directory entry (an integer). -** data: For a regular file, a blob containing the file data. For a -** symlink, a text value containing the text of the link. For a -** directory, NULL. -** -** If a non-NULL value is specified for the optional $dir parameter and -** $path is a relative path, then $path is interpreted relative to $dir. -** And the paths returned in the "name" column of the table are also -** relative to directory $dir. -** -** Notes on building this extension for Windows: -** Unless linked statically with the SQLite library, a preprocessor -** symbol, FILEIO_WIN32_DLL, must be #define'd to create a stand-alone -** DLL form of this extension for WIN32. See its use below for details. -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include -#include - -#include -#include -#include -#if !defined(_WIN32) && !defined(WIN32) -# include -# include -# include -# include -#else -# include "windows.h" -# include -# include -/* # include "test_windirent.h" */ -# define dirent DIRENT -# ifndef chmod -# define chmod _chmod -# endif -# ifndef stat -# define stat _stat -# endif -# define mkdir(path,mode) _mkdir(path) -# define lstat(path,buf) stat(path,buf) -#endif -#include -#include - -/* When used as part of the CLI, the sqlite3_stdio.h module will have -** been included before this one. In that case use the sqlite3_stdio.h -** #defines. If not, create our own for fopen(). -*/ -#ifndef _SQLITE3_STDIO_H_ -# define sqlite3_fopen fopen -#endif - -/* -** Structure of the fsdir() table-valued function -*/ - /* 0 1 2 3 4 5 */ -#define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)" -#define FSDIR_COLUMN_NAME 0 /* Name of the file */ -#define FSDIR_COLUMN_MODE 1 /* Access mode */ -#define FSDIR_COLUMN_MTIME 2 /* Last modification time */ -#define FSDIR_COLUMN_DATA 3 /* File content */ -#define FSDIR_COLUMN_PATH 4 /* Path to top of search */ -#define FSDIR_COLUMN_DIR 5 /* Path is relative to this directory */ - - -/* -** Set the result stored by context ctx to a blob containing the -** contents of file zName. Or, leave the result unchanged (NULL) -** if the file does not exist or is unreadable. -** -** If the file exceeds the SQLite blob size limit, through an -** SQLITE_TOOBIG error. -** -** Throw an SQLITE_IOERR if there are difficulties pulling the file -** off of disk. -*/ -static void readFileContents(sqlite3_context *ctx, const char *zName){ - FILE *in; - sqlite3_int64 nIn; - void *pBuf; - sqlite3 *db; - int mxBlob; - - in = sqlite3_fopen(zName, "rb"); - if( in==0 ){ - /* File does not exist or is unreadable. Leave the result set to NULL. */ - return; - } - fseek(in, 0, SEEK_END); - nIn = ftell(in); - rewind(in); - db = sqlite3_context_db_handle(ctx); - mxBlob = sqlite3_limit(db, SQLITE_LIMIT_LENGTH, -1); - if( nIn>mxBlob ){ - sqlite3_result_error_code(ctx, SQLITE_TOOBIG); - fclose(in); - return; - } - pBuf = sqlite3_malloc64( nIn ? nIn : 1 ); - if( pBuf==0 ){ - sqlite3_result_error_nomem(ctx); - fclose(in); - return; - } - if( nIn==(sqlite3_int64)fread(pBuf, 1, (size_t)nIn, in) ){ - sqlite3_result_blob64(ctx, pBuf, nIn, sqlite3_free); - }else{ - sqlite3_result_error_code(ctx, SQLITE_IOERR); - sqlite3_free(pBuf); - } - fclose(in); -} - -/* -** Implementation of the "readfile(X)" SQL function. The entire content -** of the file named X is read and returned as a BLOB. NULL is returned -** if the file does not exist or is unreadable. -*/ -static void readfileFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const char *zName; - (void)(argc); /* Unused parameter */ - zName = (const char*)sqlite3_value_text(argv[0]); - if( zName==0 ) return; - readFileContents(context, zName); -} - -/* -** Set the error message contained in context ctx to the results of -** vprintf(zFmt, ...). -*/ -static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){ - char *zMsg = 0; - va_list ap; - va_start(ap, zFmt); - zMsg = sqlite3_vmprintf(zFmt, ap); - sqlite3_result_error(ctx, zMsg, -1); - sqlite3_free(zMsg); - va_end(ap); -} - -#if defined(_WIN32) -/* -** This function is designed to convert a Win32 FILETIME structure into the -** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC). -*/ -static sqlite3_uint64 fileTimeToUnixTime( - LPFILETIME pFileTime -){ - SYSTEMTIME epochSystemTime; - ULARGE_INTEGER epochIntervals; - FILETIME epochFileTime; - ULARGE_INTEGER fileIntervals; - - memset(&epochSystemTime, 0, sizeof(SYSTEMTIME)); - epochSystemTime.wYear = 1970; - epochSystemTime.wMonth = 1; - epochSystemTime.wDay = 1; - SystemTimeToFileTime(&epochSystemTime, &epochFileTime); - epochIntervals.LowPart = epochFileTime.dwLowDateTime; - epochIntervals.HighPart = epochFileTime.dwHighDateTime; - - fileIntervals.LowPart = pFileTime->dwLowDateTime; - fileIntervals.HighPart = pFileTime->dwHighDateTime; - - return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000; -} - - -#if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32)) -# /* To allow a standalone DLL, use this next replacement function: */ -# undef sqlite3_win32_utf8_to_unicode -# define sqlite3_win32_utf8_to_unicode utf8_to_utf16 -# -LPWSTR utf8_to_utf16(const char *z){ - int nAllot = MultiByteToWideChar(CP_UTF8, 0, z, -1, NULL, 0); - LPWSTR rv = sqlite3_malloc(nAllot * sizeof(WCHAR)); - if( rv!=0 && 0 < MultiByteToWideChar(CP_UTF8, 0, z, -1, rv, nAllot) ) - return rv; - sqlite3_free(rv); - return 0; -} -#endif - -/* -** This function attempts to normalize the time values found in the stat() -** buffer to UTC. This is necessary on Win32, where the runtime library -** appears to return these values as local times. -*/ -static void statTimesToUtc( - const char *zPath, - struct stat *pStatBuf -){ - HANDLE hFindFile; - WIN32_FIND_DATAW fd; - LPWSTR zUnicodeName; - extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*); - zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath); - if( zUnicodeName ){ - memset(&fd, 0, sizeof(WIN32_FIND_DATAW)); - hFindFile = FindFirstFileW(zUnicodeName, &fd); - if( hFindFile!=NULL ){ - pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime); - pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime); - pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime); - FindClose(hFindFile); - } - sqlite3_free(zUnicodeName); - } -} -#endif - -/* -** This function is used in place of stat(). On Windows, special handling -** is required in order for the included time to be returned as UTC. On all -** other systems, this function simply calls stat(). -*/ -static int fileStat( - const char *zPath, - struct stat *pStatBuf -){ -#if defined(_WIN32) - int rc = stat(zPath, pStatBuf); - if( rc==0 ) statTimesToUtc(zPath, pStatBuf); - return rc; -#else - return stat(zPath, pStatBuf); -#endif -} - -/* -** This function is used in place of lstat(). On Windows, special handling -** is required in order for the included time to be returned as UTC. On all -** other systems, this function simply calls lstat(). -*/ -static int fileLinkStat( - const char *zPath, - struct stat *pStatBuf -){ -#if defined(_WIN32) - int rc = lstat(zPath, pStatBuf); - if( rc==0 ) statTimesToUtc(zPath, pStatBuf); - return rc; -#else - return lstat(zPath, pStatBuf); -#endif -} - -/* -** Argument zFile is the name of a file that will be created and/or written -** by SQL function writefile(). This function ensures that the directory -** zFile will be written to exists, creating it if required. The permissions -** for any path components created by this function are set in accordance -** with the current umask. -** -** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise, -** SQLITE_OK is returned if the directory is successfully created, or -** SQLITE_ERROR otherwise. -*/ -static int makeDirectory( - const char *zFile -){ - char *zCopy = sqlite3_mprintf("%s", zFile); - int rc = SQLITE_OK; - - if( zCopy==0 ){ - rc = SQLITE_NOMEM; - }else{ - int nCopy = (int)strlen(zCopy); - int i = 1; - - while( rc==SQLITE_OK ){ - struct stat sStat; - int rc2; - - for(; zCopy[i]!='/' && i=0 ){ -#if defined(_WIN32) -#if !SQLITE_OS_WINRT - /* Windows */ - FILETIME lastAccess; - FILETIME lastWrite; - SYSTEMTIME currentTime; - LONGLONG intervals; - HANDLE hFile; - LPWSTR zUnicodeName; - extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*); - - GetSystemTime(¤tTime); - SystemTimeToFileTime(¤tTime, &lastAccess); - intervals = Int32x32To64(mtime, 10000000) + 116444736000000000; - lastWrite.dwLowDateTime = (DWORD)intervals; - lastWrite.dwHighDateTime = intervals >> 32; - zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile); - if( zUnicodeName==0 ){ - return 1; - } - hFile = CreateFileW( - zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL - ); - sqlite3_free(zUnicodeName); - if( hFile!=INVALID_HANDLE_VALUE ){ - BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite); - CloseHandle(hFile); - return !bResult; - }else{ - return 1; - } -#endif -#elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */ - /* Recent unix */ - struct timespec times[2]; - times[0].tv_nsec = times[1].tv_nsec = 0; - times[0].tv_sec = time(0); - times[1].tv_sec = mtime; - if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){ - return 1; - } -#else - /* Legacy unix. - ** - ** Do not use utimes() on a symbolic link - it sees through the link and - ** modifies the timestamps on the target. Or fails if the target does - ** not exist. */ - if( 0==S_ISLNK(mode) ){ - struct timeval times[2]; - times[0].tv_usec = times[1].tv_usec = 0; - times[0].tv_sec = time(0); - times[1].tv_sec = mtime; - if( utimes(zFile, times) ){ - return 1; - } - } -#endif - } - - return 0; -} - -/* -** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function. -** Refer to header comments at the top of this file for details. -*/ -static void writefileFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const char *zFile; - mode_t mode = 0; - int res; - sqlite3_int64 mtime = -1; - - if( argc<2 || argc>4 ){ - sqlite3_result_error(context, - "wrong number of arguments to function writefile()", -1 - ); - return; - } - - zFile = (const char*)sqlite3_value_text(argv[0]); - if( zFile==0 ) return; - if( argc>=3 ){ - mode = (mode_t)sqlite3_value_int(argv[2]); - } - if( argc==4 ){ - mtime = sqlite3_value_int64(argv[3]); - } - - res = writeFile(context, zFile, argv[1], mode, mtime); - if( res==1 && errno==ENOENT ){ - if( makeDirectory(zFile)==SQLITE_OK ){ - res = writeFile(context, zFile, argv[1], mode, mtime); - } - } - - if( argc>2 && res!=0 ){ - if( S_ISLNK(mode) ){ - ctxErrorMsg(context, "failed to create symlink: %s", zFile); - }else if( S_ISDIR(mode) ){ - ctxErrorMsg(context, "failed to create directory: %s", zFile); - }else{ - ctxErrorMsg(context, "failed to write file: %s", zFile); - } - } -} - -/* -** SQL function: lsmode(MODE) -** -** Given a numberic st_mode from stat(), convert it into a human-readable -** text string in the style of "ls -l". -*/ -static void lsModeFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - int i; - int iMode = sqlite3_value_int(argv[0]); - char z[16]; - (void)argc; - if( S_ISLNK(iMode) ){ - z[0] = 'l'; - }else if( S_ISREG(iMode) ){ - z[0] = '-'; - }else if( S_ISDIR(iMode) ){ - z[0] = 'd'; - }else{ - z[0] = '?'; - } - for(i=0; i<3; i++){ - int m = (iMode >> ((2-i)*3)); - char *a = &z[1 + i*3]; - a[0] = (m & 0x4) ? 'r' : '-'; - a[1] = (m & 0x2) ? 'w' : '-'; - a[2] = (m & 0x1) ? 'x' : '-'; - } - z[10] = '\0'; - sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT); -} - -#ifndef SQLITE_OMIT_VIRTUALTABLE - -/* -** Cursor type for recursively iterating through a directory structure. -*/ -typedef struct fsdir_cursor fsdir_cursor; -typedef struct FsdirLevel FsdirLevel; - -struct FsdirLevel { - DIR *pDir; /* From opendir() */ - char *zDir; /* Name of directory (nul-terminated) */ -}; - -struct fsdir_cursor { - sqlite3_vtab_cursor base; /* Base class - must be first */ - - int nLvl; /* Number of entries in aLvl[] array */ - int iLvl; /* Index of current entry */ - FsdirLevel *aLvl; /* Hierarchy of directories being traversed */ - - const char *zBase; - int nBase; - - struct stat sStat; /* Current lstat() results */ - char *zPath; /* Path to current entry */ - sqlite3_int64 iRowid; /* Current rowid */ -}; - -typedef struct fsdir_tab fsdir_tab; -struct fsdir_tab { - sqlite3_vtab base; /* Base class - must be first */ -}; - -/* -** Construct a new fsdir virtual table object. -*/ -static int fsdirConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - fsdir_tab *pNew = 0; - int rc; - (void)pAux; - (void)argc; - (void)argv; - (void)pzErr; - rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA); - if( rc==SQLITE_OK ){ - pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) ); - if( pNew==0 ) return SQLITE_NOMEM; - memset(pNew, 0, sizeof(*pNew)); - sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY); - } - *ppVtab = (sqlite3_vtab*)pNew; - return rc; -} - -/* -** This method is the destructor for fsdir vtab objects. -*/ -static int fsdirDisconnect(sqlite3_vtab *pVtab){ - sqlite3_free(pVtab); - return SQLITE_OK; -} - -/* -** Constructor for a new fsdir_cursor object. -*/ -static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ - fsdir_cursor *pCur; - (void)p; - pCur = sqlite3_malloc( sizeof(*pCur) ); - if( pCur==0 ) return SQLITE_NOMEM; - memset(pCur, 0, sizeof(*pCur)); - pCur->iLvl = -1; - *ppCursor = &pCur->base; - return SQLITE_OK; -} - -/* -** Reset a cursor back to the state it was in when first returned -** by fsdirOpen(). -*/ -static void fsdirResetCursor(fsdir_cursor *pCur){ - int i; - for(i=0; i<=pCur->iLvl; i++){ - FsdirLevel *pLvl = &pCur->aLvl[i]; - if( pLvl->pDir ) closedir(pLvl->pDir); - sqlite3_free(pLvl->zDir); - } - sqlite3_free(pCur->zPath); - sqlite3_free(pCur->aLvl); - pCur->aLvl = 0; - pCur->zPath = 0; - pCur->zBase = 0; - pCur->nBase = 0; - pCur->nLvl = 0; - pCur->iLvl = -1; - pCur->iRowid = 1; -} - -/* -** Destructor for an fsdir_cursor. -*/ -static int fsdirClose(sqlite3_vtab_cursor *cur){ - fsdir_cursor *pCur = (fsdir_cursor*)cur; - - fsdirResetCursor(pCur); - sqlite3_free(pCur); - return SQLITE_OK; -} - -/* -** Set the error message for the virtual table associated with cursor -** pCur to the results of vprintf(zFmt, ...). -*/ -static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){ - va_list ap; - va_start(ap, zFmt); - pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); - va_end(ap); -} - - -/* -** Advance an fsdir_cursor to its next row of output. -*/ -static int fsdirNext(sqlite3_vtab_cursor *cur){ - fsdir_cursor *pCur = (fsdir_cursor*)cur; - mode_t m = pCur->sStat.st_mode; - - pCur->iRowid++; - if( S_ISDIR(m) ){ - /* Descend into this directory */ - int iNew = pCur->iLvl + 1; - FsdirLevel *pLvl; - if( iNew>=pCur->nLvl ){ - int nNew = iNew+1; - sqlite3_int64 nByte = nNew*sizeof(FsdirLevel); - FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc64(pCur->aLvl, nByte); - if( aNew==0 ) return SQLITE_NOMEM; - memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl)); - pCur->aLvl = aNew; - pCur->nLvl = nNew; - } - pCur->iLvl = iNew; - pLvl = &pCur->aLvl[iNew]; - - pLvl->zDir = pCur->zPath; - pCur->zPath = 0; - pLvl->pDir = opendir(pLvl->zDir); - if( pLvl->pDir==0 ){ - fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath); - return SQLITE_ERROR; - } - } - - while( pCur->iLvl>=0 ){ - FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl]; - struct dirent *pEntry = readdir(pLvl->pDir); - if( pEntry ){ - if( pEntry->d_name[0]=='.' ){ - if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue; - if( pEntry->d_name[1]=='\0' ) continue; - } - sqlite3_free(pCur->zPath); - pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name); - if( pCur->zPath==0 ) return SQLITE_NOMEM; - if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ - fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); - return SQLITE_ERROR; - } - return SQLITE_OK; - } - closedir(pLvl->pDir); - sqlite3_free(pLvl->zDir); - pLvl->pDir = 0; - pLvl->zDir = 0; - pCur->iLvl--; - } - - /* EOF */ - sqlite3_free(pCur->zPath); - pCur->zPath = 0; - return SQLITE_OK; -} - -/* -** Return values of columns for the row at which the series_cursor -** is currently pointing. -*/ -static int fsdirColumn( - sqlite3_vtab_cursor *cur, /* The cursor */ - sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ - int i /* Which column to return */ -){ - fsdir_cursor *pCur = (fsdir_cursor*)cur; - switch( i ){ - case FSDIR_COLUMN_NAME: { - sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT); - break; - } - - case FSDIR_COLUMN_MODE: - sqlite3_result_int64(ctx, pCur->sStat.st_mode); - break; - - case FSDIR_COLUMN_MTIME: - sqlite3_result_int64(ctx, pCur->sStat.st_mtime); - break; - - case FSDIR_COLUMN_DATA: { - mode_t m = pCur->sStat.st_mode; - if( S_ISDIR(m) ){ - sqlite3_result_null(ctx); -#if !defined(_WIN32) && !defined(WIN32) - }else if( S_ISLNK(m) ){ - char aStatic[64]; - char *aBuf = aStatic; - sqlite3_int64 nBuf = 64; - int n; - - while( 1 ){ - n = readlink(pCur->zPath, aBuf, nBuf); - if( nzPath); - } - } - case FSDIR_COLUMN_PATH: - default: { - /* The FSDIR_COLUMN_PATH and FSDIR_COLUMN_DIR are input parameters. - ** always return their values as NULL */ - break; - } - } - return SQLITE_OK; -} - -/* -** Return the rowid for the current row. In this implementation, the -** first row returned is assigned rowid value 1, and each subsequent -** row a value 1 more than that of the previous. -*/ -static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ - fsdir_cursor *pCur = (fsdir_cursor*)cur; - *pRowid = pCur->iRowid; - return SQLITE_OK; -} - -/* -** Return TRUE if the cursor has been moved off of the last -** row of output. -*/ -static int fsdirEof(sqlite3_vtab_cursor *cur){ - fsdir_cursor *pCur = (fsdir_cursor*)cur; - return (pCur->zPath==0); -} - -/* -** xFilter callback. -** -** idxNum==1 PATH parameter only -** idxNum==2 Both PATH and DIR supplied -*/ -static int fsdirFilter( - sqlite3_vtab_cursor *cur, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - const char *zDir = 0; - fsdir_cursor *pCur = (fsdir_cursor*)cur; - (void)idxStr; - fsdirResetCursor(pCur); - - if( idxNum==0 ){ - fsdirSetErrmsg(pCur, "table function fsdir requires an argument"); - return SQLITE_ERROR; - } - - assert( argc==idxNum && (argc==1 || argc==2) ); - zDir = (const char*)sqlite3_value_text(argv[0]); - if( zDir==0 ){ - fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument"); - return SQLITE_ERROR; - } - if( argc==2 ){ - pCur->zBase = (const char*)sqlite3_value_text(argv[1]); - } - if( pCur->zBase ){ - pCur->nBase = (int)strlen(pCur->zBase)+1; - pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir); - }else{ - pCur->zPath = sqlite3_mprintf("%s", zDir); - } - - if( pCur->zPath==0 ){ - return SQLITE_NOMEM; - } - if( fileLinkStat(pCur->zPath, &pCur->sStat) ){ - fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath); - return SQLITE_ERROR; - } - - return SQLITE_OK; -} - -/* -** SQLite will invoke this method one or more times while planning a query -** that uses the generate_series virtual table. This routine needs to create -** a query plan for each invocation and compute an estimated cost for that -** plan. -** -** In this implementation idxNum is used to represent the -** query plan. idxStr is unused. -** -** The query plan is represented by values of idxNum: -** -** (1) The path value is supplied by argv[0] -** (2) Path is in argv[0] and dir is in argv[1] -*/ -static int fsdirBestIndex( - sqlite3_vtab *tab, - sqlite3_index_info *pIdxInfo -){ - int i; /* Loop over constraints */ - int idxPath = -1; /* Index in pIdxInfo->aConstraint of PATH= */ - int idxDir = -1; /* Index in pIdxInfo->aConstraint of DIR= */ - int seenPath = 0; /* True if an unusable PATH= constraint is seen */ - int seenDir = 0; /* True if an unusable DIR= constraint is seen */ - const struct sqlite3_index_constraint *pConstraint; - - (void)tab; - pConstraint = pIdxInfo->aConstraint; - for(i=0; inConstraint; i++, pConstraint++){ - if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; - switch( pConstraint->iColumn ){ - case FSDIR_COLUMN_PATH: { - if( pConstraint->usable ){ - idxPath = i; - seenPath = 0; - }else if( idxPath<0 ){ - seenPath = 1; - } - break; - } - case FSDIR_COLUMN_DIR: { - if( pConstraint->usable ){ - idxDir = i; - seenDir = 0; - }else if( idxDir<0 ){ - seenDir = 1; - } - break; - } - } - } - if( seenPath || seenDir ){ - /* If input parameters are unusable, disallow this plan */ - return SQLITE_CONSTRAINT; - } - - if( idxPath<0 ){ - pIdxInfo->idxNum = 0; - /* The pIdxInfo->estimatedCost should have been initialized to a huge - ** number. Leave it unchanged. */ - pIdxInfo->estimatedRows = 0x7fffffff; - }else{ - pIdxInfo->aConstraintUsage[idxPath].omit = 1; - pIdxInfo->aConstraintUsage[idxPath].argvIndex = 1; - if( idxDir>=0 ){ - pIdxInfo->aConstraintUsage[idxDir].omit = 1; - pIdxInfo->aConstraintUsage[idxDir].argvIndex = 2; - pIdxInfo->idxNum = 2; - pIdxInfo->estimatedCost = 10.0; - }else{ - pIdxInfo->idxNum = 1; - pIdxInfo->estimatedCost = 100.0; - } - } - - return SQLITE_OK; -} - -/* -** Register the "fsdir" virtual table. -*/ -static int fsdirRegister(sqlite3 *db){ - static sqlite3_module fsdirModule = { - 0, /* iVersion */ - 0, /* xCreate */ - fsdirConnect, /* xConnect */ - fsdirBestIndex, /* xBestIndex */ - fsdirDisconnect, /* xDisconnect */ - 0, /* xDestroy */ - fsdirOpen, /* xOpen - open a cursor */ - fsdirClose, /* xClose - close a cursor */ - fsdirFilter, /* xFilter - configure scan constraints */ - fsdirNext, /* xNext - advance a cursor */ - fsdirEof, /* xEof - check for end of scan */ - fsdirColumn, /* xColumn - read data */ - fsdirRowid, /* xRowid - read data */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindMethod */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0, /* xShadowName */ - 0 /* xIntegrity */ - }; - - int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0); - return rc; -} -#else /* SQLITE_OMIT_VIRTUALTABLE */ -# define fsdirRegister(x) SQLITE_OK -#endif - -#ifdef _WIN32 - -#endif -int sqlite3_fileio_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; /* Unused parameter */ - rc = sqlite3_create_function(db, "readfile", 1, - SQLITE_UTF8|SQLITE_DIRECTONLY, 0, - readfileFunc, 0, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "writefile", -1, - SQLITE_UTF8|SQLITE_DIRECTONLY, 0, - writefileFunc, 0, 0); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0, - lsModeFunc, 0, 0); - } - if( rc==SQLITE_OK ){ - rc = fsdirRegister(db); - } - return rc; -} - -#if defined(FILEIO_WIN32_DLL) && (defined(_WIN32) || defined(WIN32)) -/* To allow a standalone DLL, make test_windirent.c use the same - * redefined SQLite API calls as the above extension code does. - * Just pull in this .c to accomplish this. As a beneficial side - * effect, this extension becomes a single translation unit. */ -# include "test_windirent.c" -#endif - -/************************* End ../ext/misc/fileio.c ********************/ -/************************* Begin ../ext/misc/completion.c ******************/ -/* -** 2017-07-10 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file implements an eponymous virtual table that returns suggested -** completions for a partial SQL input. -** -** Suggested usage: -** -** SELECT DISTINCT candidate COLLATE nocase -** FROM completion($prefix,$wholeline) -** ORDER BY 1; -** -** The two query parameters are optional. $prefix is the text of the -** current word being typed and that is to be completed. $wholeline is -** the complete input line, used for context. -** -** The raw completion() table might return the same candidate multiple -** times, for example if the same column name is used to two or more -** tables. And the candidates are returned in an arbitrary order. Hence, -** the DISTINCT and ORDER BY are recommended. -** -** This virtual table operates at the speed of human typing, and so there -** is no attempt to make it fast. Even a slow implementation will be much -** faster than any human can type. -** -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include -#include - -#ifndef SQLITE_OMIT_VIRTUALTABLE - -/* completion_vtab is a subclass of sqlite3_vtab which will -** serve as the underlying representation of a completion virtual table -*/ -typedef struct completion_vtab completion_vtab; -struct completion_vtab { - sqlite3_vtab base; /* Base class - must be first */ - sqlite3 *db; /* Database connection for this completion vtab */ -}; - -/* completion_cursor is a subclass of sqlite3_vtab_cursor which will -** serve as the underlying representation of a cursor that scans -** over rows of the result -*/ -typedef struct completion_cursor completion_cursor; -struct completion_cursor { - sqlite3_vtab_cursor base; /* Base class - must be first */ - sqlite3 *db; /* Database connection for this cursor */ - int nPrefix, nLine; /* Number of bytes in zPrefix and zLine */ - char *zPrefix; /* The prefix for the word we want to complete */ - char *zLine; /* The whole that we want to complete */ - const char *zCurrentRow; /* Current output row */ - int szRow; /* Length of the zCurrentRow string */ - sqlite3_stmt *pStmt; /* Current statement */ - sqlite3_int64 iRowid; /* The rowid */ - int ePhase; /* Current phase */ - int j; /* inter-phase counter */ -}; - -/* Values for ePhase: -*/ -#define COMPLETION_FIRST_PHASE 1 -#define COMPLETION_KEYWORDS 1 -#define COMPLETION_PRAGMAS 2 -#define COMPLETION_FUNCTIONS 3 -#define COMPLETION_COLLATIONS 4 -#define COMPLETION_INDEXES 5 -#define COMPLETION_TRIGGERS 6 -#define COMPLETION_DATABASES 7 -#define COMPLETION_TABLES 8 /* Also VIEWs and TRIGGERs */ -#define COMPLETION_COLUMNS 9 -#define COMPLETION_MODULES 10 -#define COMPLETION_EOF 11 - -/* -** The completionConnect() method is invoked to create a new -** completion_vtab that describes the completion virtual table. -** -** Think of this routine as the constructor for completion_vtab objects. -** -** All this routine needs to do is: -** -** (1) Allocate the completion_vtab object and initialize all fields. -** -** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the -** result set of queries against completion will look like. -*/ -static int completionConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - completion_vtab *pNew; - int rc; - - (void)(pAux); /* Unused parameter */ - (void)(argc); /* Unused parameter */ - (void)(argv); /* Unused parameter */ - (void)(pzErr); /* Unused parameter */ - -/* Column numbers */ -#define COMPLETION_COLUMN_CANDIDATE 0 /* Suggested completion of the input */ -#define COMPLETION_COLUMN_PREFIX 1 /* Prefix of the word to be completed */ -#define COMPLETION_COLUMN_WHOLELINE 2 /* Entire line seen so far */ -#define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */ - - sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS); - rc = sqlite3_declare_vtab(db, - "CREATE TABLE x(" - " candidate TEXT," - " prefix TEXT HIDDEN," - " wholeline TEXT HIDDEN," - " phase INT HIDDEN" /* Used for debugging only */ - ")"); - if( rc==SQLITE_OK ){ - pNew = sqlite3_malloc( sizeof(*pNew) ); - *ppVtab = (sqlite3_vtab*)pNew; - if( pNew==0 ) return SQLITE_NOMEM; - memset(pNew, 0, sizeof(*pNew)); - pNew->db = db; - } - return rc; -} - -/* -** This method is the destructor for completion_cursor objects. -*/ -static int completionDisconnect(sqlite3_vtab *pVtab){ - sqlite3_free(pVtab); - return SQLITE_OK; -} - -/* -** Constructor for a new completion_cursor object. -*/ -static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ - completion_cursor *pCur; - pCur = sqlite3_malloc( sizeof(*pCur) ); - if( pCur==0 ) return SQLITE_NOMEM; - memset(pCur, 0, sizeof(*pCur)); - pCur->db = ((completion_vtab*)p)->db; - *ppCursor = &pCur->base; - return SQLITE_OK; -} - -/* -** Reset the completion_cursor. -*/ -static void completionCursorReset(completion_cursor *pCur){ - sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0; - sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0; - sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0; - pCur->j = 0; -} - -/* -** Destructor for a completion_cursor. -*/ -static int completionClose(sqlite3_vtab_cursor *cur){ - completionCursorReset((completion_cursor*)cur); - sqlite3_free(cur); - return SQLITE_OK; -} - -/* -** Advance a completion_cursor to its next row of output. -** -** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object -** record the current state of the scan. This routine sets ->zCurrentRow -** to the current row of output and then returns. If no more rows remain, -** then ->ePhase is set to COMPLETION_EOF which will signal the virtual -** table that has reached the end of its scan. -** -** The current implementation just lists potential identifiers and -** keywords and filters them by zPrefix. Future enhancements should -** take zLine into account to try to restrict the set of identifiers and -** keywords based on what would be legal at the current point of input. -*/ -static int completionNext(sqlite3_vtab_cursor *cur){ - completion_cursor *pCur = (completion_cursor*)cur; - int eNextPhase = 0; /* Next phase to try if current phase reaches end */ - int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */ - pCur->iRowid++; - while( pCur->ePhase!=COMPLETION_EOF ){ - switch( pCur->ePhase ){ - case COMPLETION_KEYWORDS: { - if( pCur->j >= sqlite3_keyword_count() ){ - pCur->zCurrentRow = 0; - pCur->ePhase = COMPLETION_DATABASES; - }else{ - sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow); - } - iCol = -1; - break; - } - case COMPLETION_DATABASES: { - if( pCur->pStmt==0 ){ - sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, - &pCur->pStmt, 0); - } - iCol = 1; - eNextPhase = COMPLETION_TABLES; - break; - } - case COMPLETION_TABLES: { - if( pCur->pStmt==0 ){ - sqlite3_stmt *pS2; - char *zSql = 0; - const char *zSep = ""; - sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0); - while( sqlite3_step(pS2)==SQLITE_ROW ){ - const char *zDb = (const char*)sqlite3_column_text(pS2, 1); - zSql = sqlite3_mprintf( - "%z%s" - "SELECT name FROM \"%w\".sqlite_schema", - zSql, zSep, zDb - ); - if( zSql==0 ) return SQLITE_NOMEM; - zSep = " UNION "; - } - sqlite3_finalize(pS2); - sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0); - sqlite3_free(zSql); - } - iCol = 0; - eNextPhase = COMPLETION_COLUMNS; - break; - } - case COMPLETION_COLUMNS: { - if( pCur->pStmt==0 ){ - sqlite3_stmt *pS2; - char *zSql = 0; - const char *zSep = ""; - sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0); - while( sqlite3_step(pS2)==SQLITE_ROW ){ - const char *zDb = (const char*)sqlite3_column_text(pS2, 1); - zSql = sqlite3_mprintf( - "%z%s" - "SELECT pti.name FROM \"%w\".sqlite_schema AS sm" - " JOIN pragma_table_xinfo(sm.name,%Q) AS pti" - " WHERE sm.type='table'", - zSql, zSep, zDb, zDb - ); - if( zSql==0 ) return SQLITE_NOMEM; - zSep = " UNION "; - } - sqlite3_finalize(pS2); - sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0); - sqlite3_free(zSql); - } - iCol = 0; - eNextPhase = COMPLETION_EOF; - break; - } - } - if( iCol<0 ){ - /* This case is when the phase presets zCurrentRow */ - if( pCur->zCurrentRow==0 ) continue; - }else{ - if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){ - /* Extract the next row of content */ - pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol); - pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol); - }else{ - /* When all rows are finished, advance to the next phase */ - sqlite3_finalize(pCur->pStmt); - pCur->pStmt = 0; - pCur->ePhase = eNextPhase; - continue; - } - } - if( pCur->nPrefix==0 ) break; - if( pCur->nPrefix<=pCur->szRow - && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0 - ){ - break; - } - } - - return SQLITE_OK; -} - -/* -** Return values of columns for the row at which the completion_cursor -** is currently pointing. -*/ -static int completionColumn( - sqlite3_vtab_cursor *cur, /* The cursor */ - sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ - int i /* Which column to return */ -){ - completion_cursor *pCur = (completion_cursor*)cur; - switch( i ){ - case COMPLETION_COLUMN_CANDIDATE: { - sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT); - break; - } - case COMPLETION_COLUMN_PREFIX: { - sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT); - break; - } - case COMPLETION_COLUMN_WHOLELINE: { - sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT); - break; - } - case COMPLETION_COLUMN_PHASE: { - sqlite3_result_int(ctx, pCur->ePhase); - break; - } - } - return SQLITE_OK; -} - -/* -** Return the rowid for the current row. In this implementation, the -** rowid is the same as the output value. -*/ -static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ - completion_cursor *pCur = (completion_cursor*)cur; - *pRowid = pCur->iRowid; - return SQLITE_OK; -} - -/* -** Return TRUE if the cursor has been moved off of the last -** row of output. -*/ -static int completionEof(sqlite3_vtab_cursor *cur){ - completion_cursor *pCur = (completion_cursor*)cur; - return pCur->ePhase >= COMPLETION_EOF; -} - -/* -** This method is called to "rewind" the completion_cursor object back -** to the first row of output. This method is always called at least -** once prior to any call to completionColumn() or completionRowid() or -** completionEof(). -*/ -static int completionFilter( - sqlite3_vtab_cursor *pVtabCursor, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - completion_cursor *pCur = (completion_cursor *)pVtabCursor; - int iArg = 0; - (void)(idxStr); /* Unused parameter */ - (void)(argc); /* Unused parameter */ - completionCursorReset(pCur); - if( idxNum & 1 ){ - pCur->nPrefix = sqlite3_value_bytes(argv[iArg]); - if( pCur->nPrefix>0 ){ - pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg])); - if( pCur->zPrefix==0 ) return SQLITE_NOMEM; - } - iArg = 1; - } - if( idxNum & 2 ){ - pCur->nLine = sqlite3_value_bytes(argv[iArg]); - if( pCur->nLine>0 ){ - pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg])); - if( pCur->zLine==0 ) return SQLITE_NOMEM; - } - } - if( pCur->zLine!=0 && pCur->zPrefix==0 ){ - int i = pCur->nLine; - while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){ - i--; - } - pCur->nPrefix = pCur->nLine - i; - if( pCur->nPrefix>0 ){ - pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i); - if( pCur->zPrefix==0 ) return SQLITE_NOMEM; - } - } - pCur->iRowid = 0; - pCur->ePhase = COMPLETION_FIRST_PHASE; - return completionNext(pVtabCursor); -} - -/* -** SQLite will invoke this method one or more times while planning a query -** that uses the completion virtual table. This routine needs to create -** a query plan for each invocation and compute an estimated cost for that -** plan. -** -** There are two hidden parameters that act as arguments to the table-valued -** function: "prefix" and "wholeline". Bit 0 of idxNum is set if "prefix" -** is available and bit 1 is set if "wholeline" is available. -*/ -static int completionBestIndex( - sqlite3_vtab *tab, - sqlite3_index_info *pIdxInfo -){ - int i; /* Loop over constraints */ - int idxNum = 0; /* The query plan bitmask */ - int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */ - int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */ - int nArg = 0; /* Number of arguments that completeFilter() expects */ - const struct sqlite3_index_constraint *pConstraint; - - (void)(tab); /* Unused parameter */ - pConstraint = pIdxInfo->aConstraint; - for(i=0; inConstraint; i++, pConstraint++){ - if( pConstraint->usable==0 ) continue; - if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue; - switch( pConstraint->iColumn ){ - case COMPLETION_COLUMN_PREFIX: - prefixIdx = i; - idxNum |= 1; - break; - case COMPLETION_COLUMN_WHOLELINE: - wholelineIdx = i; - idxNum |= 2; - break; - } - } - if( prefixIdx>=0 ){ - pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg; - pIdxInfo->aConstraintUsage[prefixIdx].omit = 1; - } - if( wholelineIdx>=0 ){ - pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg; - pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1; - } - pIdxInfo->idxNum = idxNum; - pIdxInfo->estimatedCost = (double)5000 - 1000*nArg; - pIdxInfo->estimatedRows = 500 - 100*nArg; - return SQLITE_OK; -} - -/* -** This following structure defines all the methods for the -** completion virtual table. -*/ -static sqlite3_module completionModule = { - 0, /* iVersion */ - 0, /* xCreate */ - completionConnect, /* xConnect */ - completionBestIndex, /* xBestIndex */ - completionDisconnect, /* xDisconnect */ - 0, /* xDestroy */ - completionOpen, /* xOpen - open a cursor */ - completionClose, /* xClose - close a cursor */ - completionFilter, /* xFilter - configure scan constraints */ - completionNext, /* xNext - advance a cursor */ - completionEof, /* xEof - check for end of scan */ - completionColumn, /* xColumn - read data */ - completionRowid, /* xRowid - read data */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindMethod */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0, /* xShadowName */ - 0 /* xIntegrity */ -}; - -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -int sqlite3CompletionVtabInit(sqlite3 *db){ - int rc = SQLITE_OK; -#ifndef SQLITE_OMIT_VIRTUALTABLE - rc = sqlite3_create_module(db, "completion", &completionModule, 0); -#endif - return rc; -} - -#ifdef _WIN32 - -#endif -int sqlite3_completion_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - SQLITE_EXTENSION_INIT2(pApi); - (void)(pzErrMsg); /* Unused parameter */ -#ifndef SQLITE_OMIT_VIRTUALTABLE - rc = sqlite3CompletionVtabInit(db); -#endif - return rc; -} - -/************************* End ../ext/misc/completion.c ********************/ -/************************* Begin ../ext/misc/appendvfs.c ******************/ -/* -** 2017-10-20 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file implements a VFS shim that allows an SQLite database to be -** appended onto the end of some other file, such as an executable. -** -** A special record must appear at the end of the file that identifies the -** file as an appended database and provides the offset to the first page -** of the exposed content. (Or, it is the length of the content prefix.) -** For best performance page 1 should be located at a disk page boundary, -** though that is not required. -** -** When opening a database using this VFS, the connection might treat -** the file as an ordinary SQLite database, or it might treat it as a -** database appended onto some other file. The decision is made by -** applying the following rules in order: -** -** (1) An empty file is an ordinary database. -** -** (2) If the file ends with the appendvfs trailer string -** "Start-Of-SQLite3-NNNNNNNN" that file is an appended database. -** -** (3) If the file begins with the standard SQLite prefix string -** "SQLite format 3", that file is an ordinary database. -** -** (4) If none of the above apply and the SQLITE_OPEN_CREATE flag is -** set, then a new database is appended to the already existing file. -** -** (5) Otherwise, SQLITE_CANTOPEN is returned. -** -** To avoid unnecessary complications with the PENDING_BYTE, the size of -** the file containing the database is limited to 1GiB. (1073741824 bytes) -** This VFS will not read or write past the 1GiB mark. This restriction -** might be lifted in future versions. For now, if you need a larger -** database, then keep it in a separate file. -** -** If the file being opened is a plain database (not an appended one), then -** this shim is a pass-through into the default underlying VFS. (rule 3) -**/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include - -/* The append mark at the end of the database is: -** -** Start-Of-SQLite3-NNNNNNNN -** 123456789 123456789 12345 -** -** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is -** the offset to page 1, and also the length of the prefix content. -*/ -#define APND_MARK_PREFIX "Start-Of-SQLite3-" -#define APND_MARK_PREFIX_SZ 17 -#define APND_MARK_FOS_SZ 8 -#define APND_MARK_SIZE (APND_MARK_PREFIX_SZ+APND_MARK_FOS_SZ) - -/* -** Maximum size of the combined prefix + database + append-mark. This -** must be less than 0x40000000 to avoid locking issues on Windows. -*/ -#define APND_MAX_SIZE (0x40000000) - -/* -** Try to align the database to an even multiple of APND_ROUNDUP bytes. -*/ -#ifndef APND_ROUNDUP -#define APND_ROUNDUP 4096 -#endif -#define APND_ALIGN_MASK ((sqlite3_int64)(APND_ROUNDUP-1)) -#define APND_START_ROUNDUP(fsz) (((fsz)+APND_ALIGN_MASK) & ~APND_ALIGN_MASK) - -/* -** Forward declaration of objects used by this utility -*/ -typedef struct sqlite3_vfs ApndVfs; -typedef struct ApndFile ApndFile; - -/* Access to a lower-level VFS that (might) implement dynamic loading, -** access to randomness, etc. -*/ -#define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData)) -#define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1)) - -/* An open appendvfs file -** -** An instance of this structure describes the appended database file. -** A separate sqlite3_file object is always appended. The appended -** sqlite3_file object (which can be accessed using ORIGFILE()) describes -** the entire file, including the prefix, the database, and the -** append-mark. -** -** The structure of an AppendVFS database is like this: -** -** +-------------+---------+----------+-------------+ -** | prefix-file | padding | database | append-mark | -** +-------------+---------+----------+-------------+ -** ^ ^ -** | | -** iPgOne iMark -** -** -** "prefix file" - file onto which the database has been appended. -** "padding" - zero or more bytes inserted so that "database" -** starts on an APND_ROUNDUP boundary -** "database" - The SQLite database file -** "append-mark" - The 25-byte "Start-Of-SQLite3-NNNNNNNN" that indicates -** the offset from the start of prefix-file to the start -** of "database". -** -** The size of the database is iMark - iPgOne. -** -** The NNNNNNNN in the "Start-Of-SQLite3-NNNNNNNN" suffix is the value -** of iPgOne stored as a big-ending 64-bit integer. -** -** iMark will be the size of the underlying file minus 25 (APND_MARKSIZE). -** Or, iMark is -1 to indicate that it has not yet been written. -*/ -struct ApndFile { - sqlite3_file base; /* Subclass. MUST BE FIRST! */ - sqlite3_int64 iPgOne; /* Offset to the start of the database */ - sqlite3_int64 iMark; /* Offset of the append mark. -1 if unwritten */ - /* Always followed by another sqlite3_file that describes the whole file */ -}; - -/* -** Methods for ApndFile -*/ -static int apndClose(sqlite3_file*); -static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); -static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst); -static int apndTruncate(sqlite3_file*, sqlite3_int64 size); -static int apndSync(sqlite3_file*, int flags); -static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize); -static int apndLock(sqlite3_file*, int); -static int apndUnlock(sqlite3_file*, int); -static int apndCheckReservedLock(sqlite3_file*, int *pResOut); -static int apndFileControl(sqlite3_file*, int op, void *pArg); -static int apndSectorSize(sqlite3_file*); -static int apndDeviceCharacteristics(sqlite3_file*); -static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**); -static int apndShmLock(sqlite3_file*, int offset, int n, int flags); -static void apndShmBarrier(sqlite3_file*); -static int apndShmUnmap(sqlite3_file*, int deleteFlag); -static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); -static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p); - -/* -** Methods for ApndVfs -*/ -static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); -static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir); -static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *); -static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut); -static void *apndDlOpen(sqlite3_vfs*, const char *zFilename); -static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg); -static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void); -static void apndDlClose(sqlite3_vfs*, void*); -static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut); -static int apndSleep(sqlite3_vfs*, int microseconds); -static int apndCurrentTime(sqlite3_vfs*, double*); -static int apndGetLastError(sqlite3_vfs*, int, char *); -static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*); -static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr); -static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z); -static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName); - -static sqlite3_vfs apnd_vfs = { - 3, /* iVersion (set when registered) */ - 0, /* szOsFile (set when registered) */ - 1024, /* mxPathname */ - 0, /* pNext */ - "apndvfs", /* zName */ - 0, /* pAppData (set when registered) */ - apndOpen, /* xOpen */ - apndDelete, /* xDelete */ - apndAccess, /* xAccess */ - apndFullPathname, /* xFullPathname */ - apndDlOpen, /* xDlOpen */ - apndDlError, /* xDlError */ - apndDlSym, /* xDlSym */ - apndDlClose, /* xDlClose */ - apndRandomness, /* xRandomness */ - apndSleep, /* xSleep */ - apndCurrentTime, /* xCurrentTime */ - apndGetLastError, /* xGetLastError */ - apndCurrentTimeInt64, /* xCurrentTimeInt64 */ - apndSetSystemCall, /* xSetSystemCall */ - apndGetSystemCall, /* xGetSystemCall */ - apndNextSystemCall /* xNextSystemCall */ -}; - -static const sqlite3_io_methods apnd_io_methods = { - 3, /* iVersion */ - apndClose, /* xClose */ - apndRead, /* xRead */ - apndWrite, /* xWrite */ - apndTruncate, /* xTruncate */ - apndSync, /* xSync */ - apndFileSize, /* xFileSize */ - apndLock, /* xLock */ - apndUnlock, /* xUnlock */ - apndCheckReservedLock, /* xCheckReservedLock */ - apndFileControl, /* xFileControl */ - apndSectorSize, /* xSectorSize */ - apndDeviceCharacteristics, /* xDeviceCharacteristics */ - apndShmMap, /* xShmMap */ - apndShmLock, /* xShmLock */ - apndShmBarrier, /* xShmBarrier */ - apndShmUnmap, /* xShmUnmap */ - apndFetch, /* xFetch */ - apndUnfetch /* xUnfetch */ -}; - -/* -** Close an apnd-file. -*/ -static int apndClose(sqlite3_file *pFile){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xClose(pFile); -} - -/* -** Read data from an apnd-file. -*/ -static int apndRead( - sqlite3_file *pFile, - void *zBuf, - int iAmt, - sqlite_int64 iOfst -){ - ApndFile *paf = (ApndFile *)pFile; - pFile = ORIGFILE(pFile); - return pFile->pMethods->xRead(pFile, zBuf, iAmt, paf->iPgOne+iOfst); -} - -/* -** Add the append-mark onto what should become the end of the file. -* If and only if this succeeds, internal ApndFile.iMark is updated. -* Parameter iWriteEnd is the appendvfs-relative offset of the new mark. -*/ -static int apndWriteMark( - ApndFile *paf, - sqlite3_file *pFile, - sqlite_int64 iWriteEnd -){ - sqlite_int64 iPgOne = paf->iPgOne; - unsigned char a[APND_MARK_SIZE]; - int i = APND_MARK_FOS_SZ; - int rc; - assert(pFile == ORIGFILE(paf)); - memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ); - while( --i >= 0 ){ - a[APND_MARK_PREFIX_SZ+i] = (unsigned char)(iPgOne & 0xff); - iPgOne >>= 8; - } - iWriteEnd += paf->iPgOne; - if( SQLITE_OK==(rc = pFile->pMethods->xWrite - (pFile, a, APND_MARK_SIZE, iWriteEnd)) ){ - paf->iMark = iWriteEnd; - } - return rc; -} - -/* -** Write data to an apnd-file. -*/ -static int apndWrite( - sqlite3_file *pFile, - const void *zBuf, - int iAmt, - sqlite_int64 iOfst -){ - ApndFile *paf = (ApndFile *)pFile; - sqlite_int64 iWriteEnd = iOfst + iAmt; - if( iWriteEnd>=APND_MAX_SIZE ) return SQLITE_FULL; - pFile = ORIGFILE(pFile); - /* If append-mark is absent or will be overwritten, write it. */ - if( paf->iMark < 0 || paf->iPgOne + iWriteEnd > paf->iMark ){ - int rc = apndWriteMark(paf, pFile, iWriteEnd); - if( SQLITE_OK!=rc ) return rc; - } - return pFile->pMethods->xWrite(pFile, zBuf, iAmt, paf->iPgOne+iOfst); -} - -/* -** Truncate an apnd-file. -*/ -static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){ - ApndFile *paf = (ApndFile *)pFile; - pFile = ORIGFILE(pFile); - /* The append mark goes out first so truncate failure does not lose it. */ - if( SQLITE_OK!=apndWriteMark(paf, pFile, size) ) return SQLITE_IOERR; - /* Truncate underlying file just past append mark */ - return pFile->pMethods->xTruncate(pFile, paf->iMark+APND_MARK_SIZE); -} - -/* -** Sync an apnd-file. -*/ -static int apndSync(sqlite3_file *pFile, int flags){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xSync(pFile, flags); -} - -/* -** Return the current file-size of an apnd-file. -** If the append mark is not yet there, the file-size is 0. -*/ -static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ - ApndFile *paf = (ApndFile *)pFile; - *pSize = ( paf->iMark >= 0 )? (paf->iMark - paf->iPgOne) : 0; - return SQLITE_OK; -} - -/* -** Lock an apnd-file. -*/ -static int apndLock(sqlite3_file *pFile, int eLock){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xLock(pFile, eLock); -} - -/* -** Unlock an apnd-file. -*/ -static int apndUnlock(sqlite3_file *pFile, int eLock){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xUnlock(pFile, eLock); -} - -/* -** Check if another file-handle holds a RESERVED lock on an apnd-file. -*/ -static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xCheckReservedLock(pFile, pResOut); -} - -/* -** File control method. For custom operations on an apnd-file. -*/ -static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){ - ApndFile *paf = (ApndFile *)pFile; - int rc; - pFile = ORIGFILE(pFile); - if( op==SQLITE_FCNTL_SIZE_HINT ) *(sqlite3_int64*)pArg += paf->iPgOne; - rc = pFile->pMethods->xFileControl(pFile, op, pArg); - if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){ - *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", paf->iPgOne,*(char**)pArg); - } - return rc; -} - -/* -** Return the sector-size in bytes for an apnd-file. -*/ -static int apndSectorSize(sqlite3_file *pFile){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xSectorSize(pFile); -} - -/* -** Return the device characteristic flags supported by an apnd-file. -*/ -static int apndDeviceCharacteristics(sqlite3_file *pFile){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xDeviceCharacteristics(pFile); -} - -/* Create a shared memory file mapping */ -static int apndShmMap( - sqlite3_file *pFile, - int iPg, - int pgsz, - int bExtend, - void volatile **pp -){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp); -} - -/* Perform locking on a shared-memory segment */ -static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xShmLock(pFile,offset,n,flags); -} - -/* Memory barrier operation on shared memory */ -static void apndShmBarrier(sqlite3_file *pFile){ - pFile = ORIGFILE(pFile); - pFile->pMethods->xShmBarrier(pFile); -} - -/* Unmap a shared memory segment */ -static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){ - pFile = ORIGFILE(pFile); - return pFile->pMethods->xShmUnmap(pFile,deleteFlag); -} - -/* Fetch a page of a memory-mapped file */ -static int apndFetch( - sqlite3_file *pFile, - sqlite3_int64 iOfst, - int iAmt, - void **pp -){ - ApndFile *p = (ApndFile *)pFile; - if( p->iMark < 0 || iOfst+iAmt > p->iMark ){ - return SQLITE_IOERR; /* Cannot read what is not yet there. */ - } - pFile = ORIGFILE(pFile); - return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp); -} - -/* Release a memory-mapped page */ -static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){ - ApndFile *p = (ApndFile *)pFile; - pFile = ORIGFILE(pFile); - return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage); -} - -/* -** Try to read the append-mark off the end of a file. Return the -** start of the appended database if the append-mark is present. -** If there is no valid append-mark, return -1; -** -** An append-mark is only valid if the NNNNNNNN start-of-database offset -** indicates that the appended database contains at least one page. The -** start-of-database value must be a multiple of 512. -*/ -static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){ - int rc, i; - sqlite3_int64 iMark; - int msbs = 8 * (APND_MARK_FOS_SZ-1); - unsigned char a[APND_MARK_SIZE]; - - if( APND_MARK_SIZE!=(sz & 0x1ff) ) return -1; - rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE); - if( rc ) return -1; - if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1; - iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ] & 0x7f)) << msbs; - for(i=1; i<8; i++){ - msbs -= 8; - iMark |= (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]< (sz - APND_MARK_SIZE - 512) ) return -1; - if( iMark & 0x1ff ) return -1; - return iMark; -} - -static const char apvfsSqliteHdr[] = "SQLite format 3"; -/* -** Check to see if the file is an appendvfs SQLite database file. -** Return true iff it is such. Parameter sz is the file's size. -*/ -static int apndIsAppendvfsDatabase(sqlite3_int64 sz, sqlite3_file *pFile){ - int rc; - char zHdr[16]; - sqlite3_int64 iMark = apndReadMark(sz, pFile); - if( iMark>=0 ){ - /* If file has the correct end-marker, the expected odd size, and the - ** SQLite DB type marker where the end-marker puts it, then it - ** is an appendvfs database. - */ - rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), iMark); - if( SQLITE_OK==rc - && memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))==0 - && (sz & 0x1ff) == APND_MARK_SIZE - && sz>=512+APND_MARK_SIZE - ){ - return 1; /* It's an appendvfs database */ - } - } - return 0; -} - -/* -** Check to see if the file is an ordinary SQLite database file. -** Return true iff so. Parameter sz is the file's size. -*/ -static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){ - char zHdr[16]; - if( apndIsAppendvfsDatabase(sz, pFile) /* rule 2 */ - || (sz & 0x1ff) != 0 - || SQLITE_OK!=pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0) - || memcmp(zHdr, apvfsSqliteHdr, sizeof(zHdr))!=0 - ){ - return 0; - }else{ - return 1; - } -} - -/* -** Open an apnd file handle. -*/ -static int apndOpen( - sqlite3_vfs *pApndVfs, - const char *zName, - sqlite3_file *pFile, - int flags, - int *pOutFlags -){ - ApndFile *pApndFile = (ApndFile*)pFile; - sqlite3_file *pBaseFile = ORIGFILE(pFile); - sqlite3_vfs *pBaseVfs = ORIGVFS(pApndVfs); - int rc; - sqlite3_int64 sz = 0; - if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){ - /* The appendvfs is not to be used for transient or temporary databases. - ** Just use the base VFS open to initialize the given file object and - ** open the underlying file. (Appendvfs is then unused for this file.) - */ - return pBaseVfs->xOpen(pBaseVfs, zName, pFile, flags, pOutFlags); - } - memset(pApndFile, 0, sizeof(ApndFile)); - pFile->pMethods = &apnd_io_methods; - pApndFile->iMark = -1; /* Append mark not yet written */ - - rc = pBaseVfs->xOpen(pBaseVfs, zName, pBaseFile, flags, pOutFlags); - if( rc==SQLITE_OK ){ - rc = pBaseFile->pMethods->xFileSize(pBaseFile, &sz); - if( rc ){ - pBaseFile->pMethods->xClose(pBaseFile); - } - } - if( rc ){ - pFile->pMethods = 0; - return rc; - } - if( apndIsOrdinaryDatabaseFile(sz, pBaseFile) ){ - /* The file being opened appears to be just an ordinary DB. Copy - ** the base dispatch-table so this instance mimics the base VFS. - */ - memmove(pApndFile, pBaseFile, pBaseVfs->szOsFile); - return SQLITE_OK; - } - pApndFile->iPgOne = apndReadMark(sz, pFile); - if( pApndFile->iPgOne>=0 ){ - pApndFile->iMark = sz - APND_MARK_SIZE; /* Append mark found */ - return SQLITE_OK; - } - if( (flags & SQLITE_OPEN_CREATE)==0 ){ - pBaseFile->pMethods->xClose(pBaseFile); - rc = SQLITE_CANTOPEN; - pFile->pMethods = 0; - }else{ - /* Round newly added appendvfs location to #define'd page boundary. - ** Note that nothing has yet been written to the underlying file. - ** The append mark will be written along with first content write. - ** Until then, paf->iMark value indicates it is not yet written. - */ - pApndFile->iPgOne = APND_START_ROUNDUP(sz); - } - return rc; -} - -/* -** Delete an apnd file. -** For an appendvfs, this could mean delete the appendvfs portion, -** leaving the appendee as it was before it gained an appendvfs. -** For now, this code deletes the underlying file too. -*/ -static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ - return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync); -} - -/* -** All other VFS methods are pass-thrus. -*/ -static int apndAccess( - sqlite3_vfs *pVfs, - const char *zPath, - int flags, - int *pResOut -){ - return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut); -} -static int apndFullPathname( - sqlite3_vfs *pVfs, - const char *zPath, - int nOut, - char *zOut -){ - return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut); -} -static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){ - return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath); -} -static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ - ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg); -} -static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){ - return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym); -} -static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){ - ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle); -} -static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ - return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut); -} -static int apndSleep(sqlite3_vfs *pVfs, int nMicro){ - return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro); -} -static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ - return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut); -} -static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){ - return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b); -} -static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){ - return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p); -} -static int apndSetSystemCall( - sqlite3_vfs *pVfs, - const char *zName, - sqlite3_syscall_ptr pCall -){ - return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall); -} -static sqlite3_syscall_ptr apndGetSystemCall( - sqlite3_vfs *pVfs, - const char *zName -){ - return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName); -} -static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){ - return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName); -} - - -#ifdef _WIN32 - -#endif -/* -** This routine is called when the extension is loaded. -** Register the new VFS. -*/ -int sqlite3_appendvfs_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - sqlite3_vfs *pOrig; - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; - (void)db; - pOrig = sqlite3_vfs_find(0); - if( pOrig==0 ) return SQLITE_ERROR; - apnd_vfs.iVersion = pOrig->iVersion; - apnd_vfs.pAppData = pOrig; - apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile); - rc = sqlite3_vfs_register(&apnd_vfs, 0); -#ifdef APPENDVFS_TEST - if( rc==SQLITE_OK ){ - rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister); - } -#endif - if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY; - return rc; -} - -/************************* End ../ext/misc/appendvfs.c ********************/ -#endif -#ifdef SQLITE_HAVE_ZLIB -/************************* Begin ../ext/misc/zipfile.c ******************/ -/* -** 2017-12-26 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file implements a virtual table for reading and writing ZIP archive -** files. -** -** Usage example: -** -** SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename); -** -** Current limitations: -** -** * No support for encryption -** * No support for ZIP archives spanning multiple files -** * No support for zip64 extensions -** * Only the "inflate/deflate" (zlib) compression method is supported -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include -#include -#ifndef SQLITE_NO_STDINT -# include -#endif - -#include - -/* When used as part of the CLI, the sqlite3_stdio.h module will have -** been included before this one. In that case use the sqlite3_stdio.h -** #defines. If not, create our own for fopen(). -*/ -#ifndef _SQLITE3_STDIO_H_ -# define sqlite3_fopen fopen -#endif - -#ifndef SQLITE_OMIT_VIRTUALTABLE - -#ifndef SQLITE_AMALGAMATION - -#ifndef UINT32_TYPE -# ifdef HAVE_UINT32_T -# define UINT32_TYPE uint32_t -# else -# define UINT32_TYPE unsigned int -# endif -#endif -#ifndef UINT16_TYPE -# ifdef HAVE_UINT16_T -# define UINT16_TYPE uint16_t -# else -# define UINT16_TYPE unsigned short int -# endif -#endif -/* typedef sqlite3_int64 i64; */ -/* typedef unsigned char u8; */ -/* typedef UINT32_TYPE u32; // 4-byte unsigned integer // */ -/* typedef UINT16_TYPE u16; // 2-byte unsigned integer // */ -#define MIN(a,b) ((a)<(b) ? (a) : (b)) - -#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST) -# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1 -#endif -#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS) -# define ALWAYS(X) (1) -# define NEVER(X) (0) -#elif !defined(NDEBUG) -# define ALWAYS(X) ((X)?1:(assert(0),0)) -# define NEVER(X) ((X)?(assert(0),1):0) -#else -# define ALWAYS(X) (X) -# define NEVER(X) (X) -#endif - -#endif /* SQLITE_AMALGAMATION */ - -/* -** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK. -** -** In some ways it would be better to obtain these values from system -** header files. But, the dependency is undesirable and (a) these -** have been stable for decades, (b) the values are part of POSIX and -** are also made explicit in [man stat], and (c) are part of the -** file format for zip archives. -*/ -#ifndef S_IFDIR -# define S_IFDIR 0040000 -#endif -#ifndef S_IFREG -# define S_IFREG 0100000 -#endif -#ifndef S_IFLNK -# define S_IFLNK 0120000 -#endif - -static const char ZIPFILE_SCHEMA[] = - "CREATE TABLE y(" - "name PRIMARY KEY," /* 0: Name of file in zip archive */ - "mode," /* 1: POSIX mode for file */ - "mtime," /* 2: Last modification time (secs since 1970)*/ - "sz," /* 3: Size of object */ - "rawdata," /* 4: Raw data */ - "data," /* 5: Uncompressed data */ - "method," /* 6: Compression method (integer) */ - "z HIDDEN" /* 7: Name of zip file */ - ") WITHOUT ROWID;"; - -#define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */ -#define ZIPFILE_BUFFER_SIZE (64*1024) - - -/* -** Magic numbers used to read and write zip files. -** -** ZIPFILE_NEWENTRY_MADEBY: -** Use this value for the "version-made-by" field in new zip file -** entries. The upper byte indicates "unix", and the lower byte -** indicates that the zip file matches pkzip specification 3.0. -** This is what info-zip seems to do. -** -** ZIPFILE_NEWENTRY_REQUIRED: -** Value for "version-required-to-extract" field of new entries. -** Version 2.0 is required to support folders and deflate compression. -** -** ZIPFILE_NEWENTRY_FLAGS: -** Value for "general-purpose-bit-flags" field of new entries. Bit -** 11 means "utf-8 filename and comment". -** -** ZIPFILE_SIGNATURE_CDS: -** First 4 bytes of a valid CDS record. -** -** ZIPFILE_SIGNATURE_LFH: -** First 4 bytes of a valid LFH record. -** -** ZIPFILE_SIGNATURE_EOCD -** First 4 bytes of a valid EOCD record. -*/ -#define ZIPFILE_EXTRA_TIMESTAMP 0x5455 -#define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30) -#define ZIPFILE_NEWENTRY_REQUIRED 20 -#define ZIPFILE_NEWENTRY_FLAGS 0x800 -#define ZIPFILE_SIGNATURE_CDS 0x02014b50 -#define ZIPFILE_SIGNATURE_LFH 0x04034b50 -#define ZIPFILE_SIGNATURE_EOCD 0x06054b50 - -/* -** The sizes of the fixed-size part of each of the three main data -** structures in a zip archive. -*/ -#define ZIPFILE_LFH_FIXED_SZ 30 -#define ZIPFILE_EOCD_FIXED_SZ 22 -#define ZIPFILE_CDS_FIXED_SZ 46 - -/* -*** 4.3.16 End of central directory record: -*** -*** end of central dir signature 4 bytes (0x06054b50) -*** number of this disk 2 bytes -*** number of the disk with the -*** start of the central directory 2 bytes -*** total number of entries in the -*** central directory on this disk 2 bytes -*** total number of entries in -*** the central directory 2 bytes -*** size of the central directory 4 bytes -*** offset of start of central -*** directory with respect to -*** the starting disk number 4 bytes -*** .ZIP file comment length 2 bytes -*** .ZIP file comment (variable size) -*/ -typedef struct ZipfileEOCD ZipfileEOCD; -struct ZipfileEOCD { - u16 iDisk; - u16 iFirstDisk; - u16 nEntry; - u16 nEntryTotal; - u32 nSize; - u32 iOffset; -}; - -/* -*** 4.3.12 Central directory structure: -*** -*** ... -*** -*** central file header signature 4 bytes (0x02014b50) -*** version made by 2 bytes -*** version needed to extract 2 bytes -*** general purpose bit flag 2 bytes -*** compression method 2 bytes -*** last mod file time 2 bytes -*** last mod file date 2 bytes -*** crc-32 4 bytes -*** compressed size 4 bytes -*** uncompressed size 4 bytes -*** file name length 2 bytes -*** extra field length 2 bytes -*** file comment length 2 bytes -*** disk number start 2 bytes -*** internal file attributes 2 bytes -*** external file attributes 4 bytes -*** relative offset of local header 4 bytes -*/ -typedef struct ZipfileCDS ZipfileCDS; -struct ZipfileCDS { - u16 iVersionMadeBy; - u16 iVersionExtract; - u16 flags; - u16 iCompression; - u16 mTime; - u16 mDate; - u32 crc32; - u32 szCompressed; - u32 szUncompressed; - u16 nFile; - u16 nExtra; - u16 nComment; - u16 iDiskStart; - u16 iInternalAttr; - u32 iExternalAttr; - u32 iOffset; - char *zFile; /* Filename (sqlite3_malloc()) */ -}; - -/* -*** 4.3.7 Local file header: -*** -*** local file header signature 4 bytes (0x04034b50) -*** version needed to extract 2 bytes -*** general purpose bit flag 2 bytes -*** compression method 2 bytes -*** last mod file time 2 bytes -*** last mod file date 2 bytes -*** crc-32 4 bytes -*** compressed size 4 bytes -*** uncompressed size 4 bytes -*** file name length 2 bytes -*** extra field length 2 bytes -*** -*/ -typedef struct ZipfileLFH ZipfileLFH; -struct ZipfileLFH { - u16 iVersionExtract; - u16 flags; - u16 iCompression; - u16 mTime; - u16 mDate; - u32 crc32; - u32 szCompressed; - u32 szUncompressed; - u16 nFile; - u16 nExtra; -}; - -typedef struct ZipfileEntry ZipfileEntry; -struct ZipfileEntry { - ZipfileCDS cds; /* Parsed CDS record */ - u32 mUnixTime; /* Modification time, in UNIX format */ - u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */ - i64 iDataOff; /* Offset to data in file (if aData==0) */ - u8 *aData; /* cds.szCompressed bytes of compressed data */ - ZipfileEntry *pNext; /* Next element in in-memory CDS */ -}; - -/* -** Cursor type for zipfile tables. -*/ -typedef struct ZipfileCsr ZipfileCsr; -struct ZipfileCsr { - sqlite3_vtab_cursor base; /* Base class - must be first */ - i64 iId; /* Cursor ID */ - u8 bEof; /* True when at EOF */ - u8 bNoop; /* If next xNext() call is no-op */ - - /* Used outside of write transactions */ - FILE *pFile; /* Zip file */ - i64 iNextOff; /* Offset of next record in central directory */ - ZipfileEOCD eocd; /* Parse of central directory record */ - - ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */ - ZipfileEntry *pCurrent; /* Current entry */ - ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */ -}; - -typedef struct ZipfileTab ZipfileTab; -struct ZipfileTab { - sqlite3_vtab base; /* Base class - must be first */ - char *zFile; /* Zip file this table accesses (may be NULL) */ - sqlite3 *db; /* Host database connection */ - u8 *aBuffer; /* Temporary buffer used for various tasks */ - - ZipfileCsr *pCsrList; /* List of cursors */ - i64 iNextCsrid; - - /* The following are used by write transactions only */ - ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */ - ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */ - FILE *pWriteFd; /* File handle open on zip archive */ - i64 szCurrent; /* Current size of zip archive */ - i64 szOrig; /* Size of archive at start of transaction */ -}; - -/* -** Set the error message contained in context ctx to the results of -** vprintf(zFmt, ...). -*/ -static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){ - char *zMsg = 0; - va_list ap; - va_start(ap, zFmt); - zMsg = sqlite3_vmprintf(zFmt, ap); - sqlite3_result_error(ctx, zMsg, -1); - sqlite3_free(zMsg); - va_end(ap); -} - -/* -** If string zIn is quoted, dequote it in place. Otherwise, if the string -** is not quoted, do nothing. -*/ -static void zipfileDequote(char *zIn){ - char q = zIn[0]; - if( q=='"' || q=='\'' || q=='`' || q=='[' ){ - int iIn = 1; - int iOut = 0; - if( q=='[' ) q = ']'; - while( ALWAYS(zIn[iIn]) ){ - char c = zIn[iIn++]; - if( c==q && zIn[iIn++]!=q ) break; - zIn[iOut++] = c; - } - zIn[iOut] = '\0'; - } -} - -/* -** Construct a new ZipfileTab virtual table object. -** -** argv[0] -> module name ("zipfile") -** argv[1] -> database name -** argv[2] -> table name -** argv[...] -> "column name" and other module argument fields. -*/ -static int zipfileConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE; - int nFile = 0; - const char *zFile = 0; - ZipfileTab *pNew = 0; - int rc; - (void)pAux; - - /* If the table name is not "zipfile", require that the argument be - ** specified. This stops zipfile tables from being created as: - ** - ** CREATE VIRTUAL TABLE zzz USING zipfile(); - ** - ** It does not prevent: - ** - ** CREATE VIRTUAL TABLE zipfile USING zipfile(); - */ - assert( 0==sqlite3_stricmp(argv[0], "zipfile") ); - if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){ - *pzErr = sqlite3_mprintf("zipfile constructor requires one argument"); - return SQLITE_ERROR; - } - - if( argc>3 ){ - zFile = argv[3]; - nFile = (int)strlen(zFile)+1; - } - - rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA); - if( rc==SQLITE_OK ){ - pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile); - if( pNew==0 ) return SQLITE_NOMEM; - memset(pNew, 0, nByte+nFile); - pNew->db = db; - pNew->aBuffer = (u8*)&pNew[1]; - if( zFile ){ - pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE]; - memcpy(pNew->zFile, zFile, nFile); - zipfileDequote(pNew->zFile); - } - } - sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY); - *ppVtab = (sqlite3_vtab*)pNew; - return rc; -} - -/* -** Free the ZipfileEntry structure indicated by the only argument. -*/ -static void zipfileEntryFree(ZipfileEntry *p){ - if( p ){ - sqlite3_free(p->cds.zFile); - sqlite3_free(p); - } -} - -/* -** Release resources that should be freed at the end of a write -** transaction. -*/ -static void zipfileCleanupTransaction(ZipfileTab *pTab){ - ZipfileEntry *pEntry; - ZipfileEntry *pNext; - - if( pTab->pWriteFd ){ - fclose(pTab->pWriteFd); - pTab->pWriteFd = 0; - } - for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){ - pNext = pEntry->pNext; - zipfileEntryFree(pEntry); - } - pTab->pFirstEntry = 0; - pTab->pLastEntry = 0; - pTab->szCurrent = 0; - pTab->szOrig = 0; -} - -/* -** This method is the destructor for zipfile vtab objects. -*/ -static int zipfileDisconnect(sqlite3_vtab *pVtab){ - zipfileCleanupTransaction((ZipfileTab*)pVtab); - sqlite3_free(pVtab); - return SQLITE_OK; -} - -/* -** Constructor for a new ZipfileCsr object. -*/ -static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){ - ZipfileTab *pTab = (ZipfileTab*)p; - ZipfileCsr *pCsr; - pCsr = sqlite3_malloc(sizeof(*pCsr)); - *ppCsr = (sqlite3_vtab_cursor*)pCsr; - if( pCsr==0 ){ - return SQLITE_NOMEM; - } - memset(pCsr, 0, sizeof(*pCsr)); - pCsr->iId = ++pTab->iNextCsrid; - pCsr->pCsrNext = pTab->pCsrList; - pTab->pCsrList = pCsr; - return SQLITE_OK; -} - -/* -** Reset a cursor back to the state it was in when first returned -** by zipfileOpen(). -*/ -static void zipfileResetCursor(ZipfileCsr *pCsr){ - ZipfileEntry *p; - ZipfileEntry *pNext; - - pCsr->bEof = 0; - if( pCsr->pFile ){ - fclose(pCsr->pFile); - pCsr->pFile = 0; - zipfileEntryFree(pCsr->pCurrent); - pCsr->pCurrent = 0; - } - - for(p=pCsr->pFreeEntry; p; p=pNext){ - pNext = p->pNext; - zipfileEntryFree(p); - } -} - -/* -** Destructor for an ZipfileCsr. -*/ -static int zipfileClose(sqlite3_vtab_cursor *cur){ - ZipfileCsr *pCsr = (ZipfileCsr*)cur; - ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab); - ZipfileCsr **pp; - zipfileResetCursor(pCsr); - - /* Remove this cursor from the ZipfileTab.pCsrList list. */ - for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext)); - *pp = pCsr->pCsrNext; - - sqlite3_free(pCsr); - return SQLITE_OK; -} - -/* -** Set the error message for the virtual table associated with cursor -** pCsr to the results of vprintf(zFmt, ...). -*/ -static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){ - va_list ap; - va_start(ap, zFmt); - sqlite3_free(pTab->base.zErrMsg); - pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap); - va_end(ap); -} -static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){ - va_list ap; - va_start(ap, zFmt); - sqlite3_free(pCsr->base.pVtab->zErrMsg); - pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); - va_end(ap); -} - -/* -** Read nRead bytes of data from offset iOff of file pFile into buffer -** aRead[]. Return SQLITE_OK if successful, or an SQLite error code -** otherwise. -** -** If an error does occur, output variable (*pzErrmsg) may be set to point -** to an English language error message. It is the responsibility of the -** caller to eventually free this buffer using -** sqlite3_free(). -*/ -static int zipfileReadData( - FILE *pFile, /* Read from this file */ - u8 *aRead, /* Read into this buffer */ - int nRead, /* Number of bytes to read */ - i64 iOff, /* Offset to read from */ - char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */ -){ - size_t n; - fseek(pFile, (long)iOff, SEEK_SET); - n = fread(aRead, 1, nRead, pFile); - if( (int)n!=nRead ){ - *pzErrmsg = sqlite3_mprintf("error in fread()"); - return SQLITE_ERROR; - } - return SQLITE_OK; -} - -static int zipfileAppendData( - ZipfileTab *pTab, - const u8 *aWrite, - int nWrite -){ - if( nWrite>0 ){ - size_t n = nWrite; - fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET); - n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd); - if( (int)n!=nWrite ){ - pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()"); - return SQLITE_ERROR; - } - pTab->szCurrent += nWrite; - } - return SQLITE_OK; -} - -/* -** Read and return a 16-bit little-endian unsigned integer from buffer aBuf. -*/ -static u16 zipfileGetU16(const u8 *aBuf){ - return (aBuf[1] << 8) + aBuf[0]; -} - -/* -** Read and return a 32-bit little-endian unsigned integer from buffer aBuf. -*/ -static u32 zipfileGetU32(const u8 *aBuf){ - if( aBuf==0 ) return 0; - return ((u32)(aBuf[3]) << 24) - + ((u32)(aBuf[2]) << 16) - + ((u32)(aBuf[1]) << 8) - + ((u32)(aBuf[0]) << 0); -} - -/* -** Write a 16-bit little endiate integer into buffer aBuf. -*/ -static void zipfilePutU16(u8 *aBuf, u16 val){ - aBuf[0] = val & 0xFF; - aBuf[1] = (val>>8) & 0xFF; -} - -/* -** Write a 32-bit little endiate integer into buffer aBuf. -*/ -static void zipfilePutU32(u8 *aBuf, u32 val){ - aBuf[0] = val & 0xFF; - aBuf[1] = (val>>8) & 0xFF; - aBuf[2] = (val>>16) & 0xFF; - aBuf[3] = (val>>24) & 0xFF; -} - -#define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) ) -#define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) ) - -#define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; } -#define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; } - -/* -** Magic numbers used to read CDS records. -*/ -#define ZIPFILE_CDS_NFILE_OFF 28 -#define ZIPFILE_CDS_SZCOMPRESSED_OFF 20 - -/* -** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR -** if the record is not well-formed, or SQLITE_OK otherwise. -*/ -static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){ - u8 *aRead = aBuf; - u32 sig = zipfileRead32(aRead); - int rc = SQLITE_OK; - if( sig!=ZIPFILE_SIGNATURE_CDS ){ - rc = SQLITE_ERROR; - }else{ - pCDS->iVersionMadeBy = zipfileRead16(aRead); - pCDS->iVersionExtract = zipfileRead16(aRead); - pCDS->flags = zipfileRead16(aRead); - pCDS->iCompression = zipfileRead16(aRead); - pCDS->mTime = zipfileRead16(aRead); - pCDS->mDate = zipfileRead16(aRead); - pCDS->crc32 = zipfileRead32(aRead); - pCDS->szCompressed = zipfileRead32(aRead); - pCDS->szUncompressed = zipfileRead32(aRead); - assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); - pCDS->nFile = zipfileRead16(aRead); - pCDS->nExtra = zipfileRead16(aRead); - pCDS->nComment = zipfileRead16(aRead); - pCDS->iDiskStart = zipfileRead16(aRead); - pCDS->iInternalAttr = zipfileRead16(aRead); - pCDS->iExternalAttr = zipfileRead32(aRead); - pCDS->iOffset = zipfileRead32(aRead); - assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] ); - } - - return rc; -} - -/* -** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR -** if the record is not well-formed, or SQLITE_OK otherwise. -*/ -static int zipfileReadLFH( - u8 *aBuffer, - ZipfileLFH *pLFH -){ - u8 *aRead = aBuffer; - int rc = SQLITE_OK; - - u32 sig = zipfileRead32(aRead); - if( sig!=ZIPFILE_SIGNATURE_LFH ){ - rc = SQLITE_ERROR; - }else{ - pLFH->iVersionExtract = zipfileRead16(aRead); - pLFH->flags = zipfileRead16(aRead); - pLFH->iCompression = zipfileRead16(aRead); - pLFH->mTime = zipfileRead16(aRead); - pLFH->mDate = zipfileRead16(aRead); - pLFH->crc32 = zipfileRead32(aRead); - pLFH->szCompressed = zipfileRead32(aRead); - pLFH->szUncompressed = zipfileRead32(aRead); - pLFH->nFile = zipfileRead16(aRead); - pLFH->nExtra = zipfileRead16(aRead); - } - return rc; -} - - -/* -** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields. -** Scan through this buffer to find an "extra-timestamp" field. If one -** exists, extract the 32-bit modification-timestamp from it and store -** the value in output parameter *pmTime. -** -** Zero is returned if no extra-timestamp record could be found (and so -** *pmTime is left unchanged), or non-zero otherwise. -** -** The general format of an extra field is: -** -** Header ID 2 bytes -** Data Size 2 bytes -** Data N bytes -*/ -static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){ - int ret = 0; - u8 *p = aExtra; - u8 *pEnd = &aExtra[nExtra]; - - while( p modtime is present */ - *pmTime = zipfileGetU32(&p[1]); - ret = 1; - } - break; - } - } - - p += nByte; - } - return ret; -} - -/* -** Convert the standard MS-DOS timestamp stored in the mTime and mDate -** fields of the CDS structure passed as the only argument to a 32-bit -** UNIX seconds-since-the-epoch timestamp. Return the result. -** -** "Standard" MS-DOS time format: -** -** File modification time: -** Bits 00-04: seconds divided by 2 -** Bits 05-10: minute -** Bits 11-15: hour -** File modification date: -** Bits 00-04: day -** Bits 05-08: month (1-12) -** Bits 09-15: years from 1980 -** -** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx -*/ -static u32 zipfileMtime(ZipfileCDS *pCDS){ - int Y,M,D,X1,X2,A,B,sec,min,hr; - i64 JDsec; - Y = (1980 + ((pCDS->mDate >> 9) & 0x7F)); - M = ((pCDS->mDate >> 5) & 0x0F); - D = (pCDS->mDate & 0x1F); - sec = (pCDS->mTime & 0x1F)*2; - min = (pCDS->mTime >> 5) & 0x3F; - hr = (pCDS->mTime >> 11) & 0x1F; - if( M<=2 ){ - Y--; - M += 12; - } - X1 = 36525*(Y+4716)/100; - X2 = 306001*(M+1)/10000; - A = Y/100; - B = 2 - A + (A/4); - JDsec = (i64)((X1 + X2 + D + B - 1524.5)*86400) + hr*3600 + min*60 + sec; - return (u32)(JDsec - (i64)24405875*(i64)8640); -} - -/* -** The opposite of zipfileMtime(). This function populates the mTime and -** mDate fields of the CDS structure passed as the first argument according -** to the UNIX timestamp value passed as the second. -*/ -static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){ - /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */ - i64 JD = (i64)2440588 + mUnixTime / (24*60*60); - - int A, B, C, D, E; - int yr, mon, day; - int hr, min, sec; - - A = (int)((JD - 1867216.25)/36524.25); - A = (int)(JD + 1 + A - (A/4)); - B = A + 1524; - C = (int)((B - 122.1)/365.25); - D = (36525*(C&32767))/100; - E = (int)((B-D)/30.6001); - - day = B - D - (int)(30.6001*E); - mon = (E<14 ? E-1 : E-13); - yr = mon>2 ? C-4716 : C-4715; - - hr = (mUnixTime % (24*60*60)) / (60*60); - min = (mUnixTime % (60*60)) / 60; - sec = (mUnixTime % 60); - - if( yr>=1980 ){ - pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9)); - pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11)); - }else{ - pCds->mDate = pCds->mTime = 0; - } - - assert( mUnixTime<315507600 - || mUnixTime==zipfileMtime(pCds) - || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) - /* || (mUnixTime % 2) */ - ); -} - -/* -** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in -** size) containing an entire zip archive image. Or, if aBlob is NULL, -** then pFile is a file-handle open on a zip file. In either case, this -** function creates a ZipfileEntry object based on the zip archive entry -** for which the CDS record is at offset iOff. -** -** If successful, SQLITE_OK is returned and (*ppEntry) set to point to -** the new object. Otherwise, an SQLite error code is returned and the -** final value of (*ppEntry) undefined. -*/ -static int zipfileGetEntry( - ZipfileTab *pTab, /* Store any error message here */ - const u8 *aBlob, /* Pointer to in-memory file image */ - int nBlob, /* Size of aBlob[] in bytes */ - FILE *pFile, /* If aBlob==0, read from this file */ - i64 iOff, /* Offset of CDS record */ - ZipfileEntry **ppEntry /* OUT: Pointer to new object */ -){ - u8 *aRead; - char **pzErr = &pTab->base.zErrMsg; - int rc = SQLITE_OK; - (void)nBlob; - - if( aBlob==0 ){ - aRead = pTab->aBuffer; - rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr); - }else{ - aRead = (u8*)&aBlob[iOff]; - } - - if( rc==SQLITE_OK ){ - sqlite3_int64 nAlloc; - ZipfileEntry *pNew; - - int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]); - int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]); - nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]); - - nAlloc = sizeof(ZipfileEntry) + nExtra; - if( aBlob ){ - nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]); - } - - pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc); - if( pNew==0 ){ - rc = SQLITE_NOMEM; - }else{ - memset(pNew, 0, sizeof(ZipfileEntry)); - rc = zipfileReadCDS(aRead, &pNew->cds); - if( rc!=SQLITE_OK ){ - *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff); - }else if( aBlob==0 ){ - rc = zipfileReadData( - pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr - ); - }else{ - aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ]; - } - } - - if( rc==SQLITE_OK ){ - u32 *pt = &pNew->mUnixTime; - pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); - pNew->aExtra = (u8*)&pNew[1]; - memcpy(pNew->aExtra, &aRead[nFile], nExtra); - if( pNew->cds.zFile==0 ){ - rc = SQLITE_NOMEM; - }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){ - pNew->mUnixTime = zipfileMtime(&pNew->cds); - } - } - - if( rc==SQLITE_OK ){ - static const int szFix = ZIPFILE_LFH_FIXED_SZ; - ZipfileLFH lfh; - if( pFile ){ - rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr); - }else{ - aRead = (u8*)&aBlob[pNew->cds.iOffset]; - } - - if( rc==SQLITE_OK ) rc = zipfileReadLFH(aRead, &lfh); - if( rc==SQLITE_OK ){ - pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ; - pNew->iDataOff += lfh.nFile + lfh.nExtra; - if( aBlob && pNew->cds.szCompressed ){ - pNew->aData = &pNew->aExtra[nExtra]; - memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed); - } - }else{ - *pzErr = sqlite3_mprintf("failed to read LFH at offset %d", - (int)pNew->cds.iOffset - ); - } - } - - if( rc!=SQLITE_OK ){ - zipfileEntryFree(pNew); - }else{ - *ppEntry = pNew; - } - } - - return rc; -} - -/* -** Advance an ZipfileCsr to its next row of output. -*/ -static int zipfileNext(sqlite3_vtab_cursor *cur){ - ZipfileCsr *pCsr = (ZipfileCsr*)cur; - int rc = SQLITE_OK; - - if( pCsr->pFile ){ - i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize; - zipfileEntryFree(pCsr->pCurrent); - pCsr->pCurrent = 0; - if( pCsr->iNextOff>=iEof ){ - pCsr->bEof = 1; - }else{ - ZipfileEntry *p = 0; - ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab); - rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p); - if( rc==SQLITE_OK ){ - pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ; - pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment; - } - pCsr->pCurrent = p; - } - }else{ - if( !pCsr->bNoop ){ - pCsr->pCurrent = pCsr->pCurrent->pNext; - } - if( pCsr->pCurrent==0 ){ - pCsr->bEof = 1; - } - } - - pCsr->bNoop = 0; - return rc; -} - -static void zipfileFree(void *p) { - sqlite3_free(p); -} - -/* -** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the -** size is nOut bytes. This function uncompresses the data and sets the -** return value in context pCtx to the result (a blob). -** -** If an error occurs, an error code is left in pCtx instead. -*/ -static void zipfileInflate( - sqlite3_context *pCtx, /* Store result here */ - const u8 *aIn, /* Compressed data */ - int nIn, /* Size of buffer aIn[] in bytes */ - int nOut /* Expected output size */ -){ - u8 *aRes = sqlite3_malloc(nOut); - if( aRes==0 ){ - sqlite3_result_error_nomem(pCtx); - }else{ - int err; - z_stream str; - memset(&str, 0, sizeof(str)); - - str.next_in = (Byte*)aIn; - str.avail_in = nIn; - str.next_out = (Byte*)aRes; - str.avail_out = nOut; - - err = inflateInit2(&str, -15); - if( err!=Z_OK ){ - zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err); - }else{ - err = inflate(&str, Z_NO_FLUSH); - if( err!=Z_STREAM_END ){ - zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err); - }else{ - sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree); - aRes = 0; - } - } - sqlite3_free(aRes); - inflateEnd(&str); - } -} - -/* -** Buffer aIn (size nIn bytes) contains uncompressed data. This function -** compresses it and sets (*ppOut) to point to a buffer containing the -** compressed data. The caller is responsible for eventually calling -** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) -** is set to the size of buffer (*ppOut) in bytes. -** -** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error -** code is returned and an error message left in virtual-table handle -** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this -** case. -*/ -static int zipfileDeflate( - const u8 *aIn, int nIn, /* Input */ - u8 **ppOut, int *pnOut, /* Output */ - char **pzErr /* OUT: Error message */ -){ - int rc = SQLITE_OK; - sqlite3_int64 nAlloc; - z_stream str; - u8 *aOut; - - memset(&str, 0, sizeof(str)); - str.next_in = (Bytef*)aIn; - str.avail_in = nIn; - deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); - - nAlloc = deflateBound(&str, nIn); - aOut = (u8*)sqlite3_malloc64(nAlloc); - if( aOut==0 ){ - rc = SQLITE_NOMEM; - }else{ - int res; - str.next_out = aOut; - str.avail_out = nAlloc; - res = deflate(&str, Z_FINISH); - if( res==Z_STREAM_END ){ - *ppOut = aOut; - *pnOut = (int)str.total_out; - }else{ - sqlite3_free(aOut); - *pzErr = sqlite3_mprintf("zipfile: deflate() error"); - rc = SQLITE_ERROR; - } - deflateEnd(&str); - } - - return rc; -} - - -/* -** Return values of columns for the row at which the series_cursor -** is currently pointing. -*/ -static int zipfileColumn( - sqlite3_vtab_cursor *cur, /* The cursor */ - sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ - int i /* Which column to return */ -){ - ZipfileCsr *pCsr = (ZipfileCsr*)cur; - ZipfileCDS *pCDS = &pCsr->pCurrent->cds; - int rc = SQLITE_OK; - switch( i ){ - case 0: /* name */ - sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT); - break; - case 1: /* mode */ - /* TODO: Whether or not the following is correct surely depends on - ** the platform on which the archive was created. */ - sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16); - break; - case 2: { /* mtime */ - sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime); - break; - } - case 3: { /* sz */ - if( sqlite3_vtab_nochange(ctx)==0 ){ - sqlite3_result_int64(ctx, pCDS->szUncompressed); - } - break; - } - case 4: /* rawdata */ - if( sqlite3_vtab_nochange(ctx) ) break; - case 5: { /* data */ - if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){ - int sz = pCDS->szCompressed; - int szFinal = pCDS->szUncompressed; - if( szFinal>0 ){ - u8 *aBuf; - u8 *aFree = 0; - if( pCsr->pCurrent->aData ){ - aBuf = pCsr->pCurrent->aData; - }else{ - aBuf = aFree = sqlite3_malloc64(sz); - if( aBuf==0 ){ - rc = SQLITE_NOMEM; - }else{ - FILE *pFile = pCsr->pFile; - if( pFile==0 ){ - pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd; - } - rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff, - &pCsr->base.pVtab->zErrMsg - ); - } - } - if( rc==SQLITE_OK ){ - if( i==5 && pCDS->iCompression ){ - zipfileInflate(ctx, aBuf, sz, szFinal); - }else{ - sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT); - } - } - sqlite3_free(aFree); - }else{ - /* Figure out if this is a directory or a zero-sized file. Consider - ** it to be a directory either if the mode suggests so, or if - ** the final character in the name is '/'. */ - u32 mode = pCDS->iExternalAttr >> 16; - if( !(mode & S_IFDIR) - && pCDS->nFile>=1 - && pCDS->zFile[pCDS->nFile-1]!='/' - ){ - sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC); - } - } - } - break; - } - case 6: /* method */ - sqlite3_result_int(ctx, pCDS->iCompression); - break; - default: /* z */ - assert( i==7 ); - sqlite3_result_int64(ctx, pCsr->iId); - break; - } - - return rc; -} - -/* -** Return TRUE if the cursor is at EOF. -*/ -static int zipfileEof(sqlite3_vtab_cursor *cur){ - ZipfileCsr *pCsr = (ZipfileCsr*)cur; - return pCsr->bEof; -} - -/* -** If aBlob is not NULL, then it points to a buffer nBlob bytes in size -** containing an entire zip archive image. Or, if aBlob is NULL, then pFile -** is guaranteed to be a file-handle open on a zip file. -** -** This function attempts to locate the EOCD record within the zip archive -** and populate *pEOCD with the results of decoding it. SQLITE_OK is -** returned if successful. Otherwise, an SQLite error code is returned and -** an English language error message may be left in virtual-table pTab. -*/ -static int zipfileReadEOCD( - ZipfileTab *pTab, /* Return errors here */ - const u8 *aBlob, /* Pointer to in-memory file image */ - int nBlob, /* Size of aBlob[] in bytes */ - FILE *pFile, /* Read from this file if aBlob==0 */ - ZipfileEOCD *pEOCD /* Object to populate */ -){ - u8 *aRead = pTab->aBuffer; /* Temporary buffer */ - int nRead; /* Bytes to read from file */ - int rc = SQLITE_OK; - - memset(pEOCD, 0, sizeof(ZipfileEOCD)); - if( aBlob==0 ){ - i64 iOff; /* Offset to read from */ - i64 szFile; /* Total size of file in bytes */ - fseek(pFile, 0, SEEK_END); - szFile = (i64)ftell(pFile); - if( szFile==0 ){ - return SQLITE_OK; - } - nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE)); - iOff = szFile - nRead; - rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg); - }else{ - nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE)); - aRead = (u8*)&aBlob[nBlob-nRead]; - } - - if( rc==SQLITE_OK ){ - int i; - - /* Scan backwards looking for the signature bytes */ - for(i=nRead-20; i>=0; i--){ - if( aRead[i]==0x50 && aRead[i+1]==0x4b - && aRead[i+2]==0x05 && aRead[i+3]==0x06 - ){ - break; - } - } - if( i<0 ){ - pTab->base.zErrMsg = sqlite3_mprintf( - "cannot find end of central directory record" - ); - return SQLITE_ERROR; - } - - aRead += i+4; - pEOCD->iDisk = zipfileRead16(aRead); - pEOCD->iFirstDisk = zipfileRead16(aRead); - pEOCD->nEntry = zipfileRead16(aRead); - pEOCD->nEntryTotal = zipfileRead16(aRead); - pEOCD->nSize = zipfileRead32(aRead); - pEOCD->iOffset = zipfileRead32(aRead); - } - - return rc; -} - -/* -** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry -** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added -** to the end of the list. Otherwise, it is added to the list immediately -** before pBefore (which is guaranteed to be a part of said list). -*/ -static void zipfileAddEntry( - ZipfileTab *pTab, - ZipfileEntry *pBefore, - ZipfileEntry *pNew -){ - assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) ); - assert( pNew->pNext==0 ); - if( pBefore==0 ){ - if( pTab->pFirstEntry==0 ){ - pTab->pFirstEntry = pTab->pLastEntry = pNew; - }else{ - assert( pTab->pLastEntry->pNext==0 ); - pTab->pLastEntry->pNext = pNew; - pTab->pLastEntry = pNew; - } - }else{ - ZipfileEntry **pp; - for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext)); - pNew->pNext = pBefore; - *pp = pNew; - } -} - -static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){ - ZipfileEOCD eocd; - int rc; - int i; - i64 iOff; - - rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd); - iOff = eocd.iOffset; - for(i=0; rc==SQLITE_OK && ipWriteFd, iOff, &pNew); - - if( rc==SQLITE_OK ){ - zipfileAddEntry(pTab, 0, pNew); - iOff += ZIPFILE_CDS_FIXED_SZ; - iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment; - } - } - return rc; -} - -/* -** xFilter callback. -*/ -static int zipfileFilter( - sqlite3_vtab_cursor *cur, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - ZipfileTab *pTab = (ZipfileTab*)cur->pVtab; - ZipfileCsr *pCsr = (ZipfileCsr*)cur; - const char *zFile = 0; /* Zip file to scan */ - int rc = SQLITE_OK; /* Return Code */ - int bInMemory = 0; /* True for an in-memory zipfile */ - - (void)idxStr; - (void)argc; - - zipfileResetCursor(pCsr); - - if( pTab->zFile ){ - zFile = pTab->zFile; - }else if( idxNum==0 ){ - zipfileCursorErr(pCsr, "zipfile() function requires an argument"); - return SQLITE_ERROR; - }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){ - static const u8 aEmptyBlob = 0; - const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]); - int nBlob = sqlite3_value_bytes(argv[0]); - assert( pTab->pFirstEntry==0 ); - if( aBlob==0 ){ - aBlob = &aEmptyBlob; - nBlob = 0; - } - rc = zipfileLoadDirectory(pTab, aBlob, nBlob); - pCsr->pFreeEntry = pTab->pFirstEntry; - pTab->pFirstEntry = pTab->pLastEntry = 0; - if( rc!=SQLITE_OK ) return rc; - bInMemory = 1; - }else{ - zFile = (const char*)sqlite3_value_text(argv[0]); - } - - if( 0==pTab->pWriteFd && 0==bInMemory ){ - pCsr->pFile = zFile ? sqlite3_fopen(zFile, "rb") : 0; - if( pCsr->pFile==0 ){ - zipfileCursorErr(pCsr, "cannot open file: %s", zFile); - rc = SQLITE_ERROR; - }else{ - rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd); - if( rc==SQLITE_OK ){ - if( pCsr->eocd.nEntry==0 ){ - pCsr->bEof = 1; - }else{ - pCsr->iNextOff = pCsr->eocd.iOffset; - rc = zipfileNext(cur); - } - } - } - }else{ - pCsr->bNoop = 1; - pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry; - rc = zipfileNext(cur); - } - - return rc; -} - -/* -** xBestIndex callback. -*/ -static int zipfileBestIndex( - sqlite3_vtab *tab, - sqlite3_index_info *pIdxInfo -){ - int i; - int idx = -1; - int unusable = 0; - (void)tab; - - for(i=0; inConstraint; i++){ - const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; - if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue; - if( pCons->usable==0 ){ - unusable = 1; - }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ - idx = i; - } - } - pIdxInfo->estimatedCost = 1000.0; - if( idx>=0 ){ - pIdxInfo->aConstraintUsage[idx].argvIndex = 1; - pIdxInfo->aConstraintUsage[idx].omit = 1; - pIdxInfo->idxNum = 1; - }else if( unusable ){ - return SQLITE_CONSTRAINT; - } - return SQLITE_OK; -} - -static ZipfileEntry *zipfileNewEntry(const char *zPath){ - ZipfileEntry *pNew; - pNew = sqlite3_malloc(sizeof(ZipfileEntry)); - if( pNew ){ - memset(pNew, 0, sizeof(ZipfileEntry)); - pNew->cds.zFile = sqlite3_mprintf("%s", zPath); - if( pNew->cds.zFile==0 ){ - sqlite3_free(pNew); - pNew = 0; - } - } - return pNew; -} - -static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){ - ZipfileCDS *pCds = &pEntry->cds; - u8 *a = aBuf; - - pCds->nExtra = 9; - - /* Write the LFH itself */ - zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH); - zipfileWrite16(a, pCds->iVersionExtract); - zipfileWrite16(a, pCds->flags); - zipfileWrite16(a, pCds->iCompression); - zipfileWrite16(a, pCds->mTime); - zipfileWrite16(a, pCds->mDate); - zipfileWrite32(a, pCds->crc32); - zipfileWrite32(a, pCds->szCompressed); - zipfileWrite32(a, pCds->szUncompressed); - zipfileWrite16(a, (u16)pCds->nFile); - zipfileWrite16(a, pCds->nExtra); - assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] ); - - /* Add the file name */ - memcpy(a, pCds->zFile, (int)pCds->nFile); - a += (int)pCds->nFile; - - /* The "extra" data */ - zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); - zipfileWrite16(a, 5); - *a++ = 0x01; - zipfileWrite32(a, pEntry->mUnixTime); - - return a-aBuf; -} - -static int zipfileAppendEntry( - ZipfileTab *pTab, - ZipfileEntry *pEntry, - const u8 *pData, - int nData -){ - u8 *aBuf = pTab->aBuffer; - int nBuf; - int rc; - - nBuf = zipfileSerializeLFH(pEntry, aBuf); - rc = zipfileAppendData(pTab, aBuf, nBuf); - if( rc==SQLITE_OK ){ - pEntry->iDataOff = pTab->szCurrent; - rc = zipfileAppendData(pTab, pData, nData); - } - - return rc; -} - -static int zipfileGetMode( - sqlite3_value *pVal, - int bIsDir, /* If true, default to directory */ - u32 *pMode, /* OUT: Mode value */ - char **pzErr /* OUT: Error message */ -){ - const char *z = (const char*)sqlite3_value_text(pVal); - u32 mode = 0; - if( z==0 ){ - mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644)); - }else if( z[0]>='0' && z[0]<='9' ){ - mode = (unsigned int)sqlite3_value_int(pVal); - }else{ - const char zTemplate[11] = "-rwxrwxrwx"; - int i; - if( strlen(z)!=10 ) goto parse_error; - switch( z[0] ){ - case '-': mode |= S_IFREG; break; - case 'd': mode |= S_IFDIR; break; - case 'l': mode |= S_IFLNK; break; - default: goto parse_error; - } - for(i=1; i<10; i++){ - if( z[i]==zTemplate[i] ) mode |= 1 << (9-i); - else if( z[i]!='-' ) goto parse_error; - } - } - if( ((mode & S_IFDIR)==0)==bIsDir ){ - /* The "mode" attribute is a directory, but data has been specified. - ** Or vice-versa - no data but "mode" is a file or symlink. */ - *pzErr = sqlite3_mprintf("zipfile: mode does not match data"); - return SQLITE_CONSTRAINT; - } - *pMode = mode; - return SQLITE_OK; - - parse_error: - *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z); - return SQLITE_ERROR; -} - -/* -** Both (const char*) arguments point to nul-terminated strings. Argument -** nB is the value of strlen(zB). This function returns 0 if the strings are -** identical, ignoring any trailing '/' character in either path. */ -static int zipfileComparePath(const char *zA, const char *zB, int nB){ - int nA = (int)strlen(zA); - if( nA>0 && zA[nA-1]=='/' ) nA--; - if( nB>0 && zB[nB-1]=='/' ) nB--; - if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0; - return 1; -} - -static int zipfileBegin(sqlite3_vtab *pVtab){ - ZipfileTab *pTab = (ZipfileTab*)pVtab; - int rc = SQLITE_OK; - - assert( pTab->pWriteFd==0 ); - if( pTab->zFile==0 || pTab->zFile[0]==0 ){ - pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename"); - return SQLITE_ERROR; - } - - /* Open a write fd on the file. Also load the entire central directory - ** structure into memory. During the transaction any new file data is - ** appended to the archive file, but the central directory is accumulated - ** in main-memory until the transaction is committed. */ - pTab->pWriteFd = sqlite3_fopen(pTab->zFile, "ab+"); - if( pTab->pWriteFd==0 ){ - pTab->base.zErrMsg = sqlite3_mprintf( - "zipfile: failed to open file %s for writing", pTab->zFile - ); - rc = SQLITE_ERROR; - }else{ - fseek(pTab->pWriteFd, 0, SEEK_END); - pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd); - rc = zipfileLoadDirectory(pTab, 0, 0); - } - - if( rc!=SQLITE_OK ){ - zipfileCleanupTransaction(pTab); - } - - return rc; -} - -/* -** Return the current time as a 32-bit timestamp in UNIX epoch format (like -** time(2)). -*/ -static u32 zipfileTime(void){ - sqlite3_vfs *pVfs = sqlite3_vfs_find(0); - u32 ret; - if( pVfs==0 ) return 0; - if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ - i64 ms; - pVfs->xCurrentTimeInt64(pVfs, &ms); - ret = (u32)((ms/1000) - ((i64)24405875 * 8640)); - }else{ - double day; - pVfs->xCurrentTime(pVfs, &day); - ret = (u32)((day - 2440587.5) * 86400); - } - return ret; -} - -/* -** Return a 32-bit timestamp in UNIX epoch format. -** -** If the value passed as the only argument is either NULL or an SQL NULL, -** return the current time. Otherwise, return the value stored in (*pVal) -** cast to a 32-bit unsigned integer. -*/ -static u32 zipfileGetTime(sqlite3_value *pVal){ - if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){ - return zipfileTime(); - } - return (u32)sqlite3_value_int64(pVal); -} - -/* -** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry -** linked list. Remove it from the list and free the object. -*/ -static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){ - if( pOld ){ - if( pTab->pFirstEntry==pOld ){ - pTab->pFirstEntry = pOld->pNext; - if( pTab->pLastEntry==pOld ) pTab->pLastEntry = 0; - }else{ - ZipfileEntry *p; - for(p=pTab->pFirstEntry; p; p=p->pNext){ - if( p->pNext==pOld ){ - p->pNext = pOld->pNext; - if( pTab->pLastEntry==pOld ) pTab->pLastEntry = p; - break; - } - } - } - zipfileEntryFree(pOld); - } -} - -/* -** xUpdate method. -*/ -static int zipfileUpdate( - sqlite3_vtab *pVtab, - int nVal, - sqlite3_value **apVal, - sqlite_int64 *pRowid -){ - ZipfileTab *pTab = (ZipfileTab*)pVtab; - int rc = SQLITE_OK; /* Return Code */ - ZipfileEntry *pNew = 0; /* New in-memory CDS entry */ - - u32 mode = 0; /* Mode for new entry */ - u32 mTime = 0; /* Modification time for new entry */ - i64 sz = 0; /* Uncompressed size */ - const char *zPath = 0; /* Path for new entry */ - int nPath = 0; /* strlen(zPath) */ - const u8 *pData = 0; /* Pointer to buffer containing content */ - int nData = 0; /* Size of pData buffer in bytes */ - int iMethod = 0; /* Compression method for new entry */ - u8 *pFree = 0; /* Free this */ - char *zFree = 0; /* Also free this */ - ZipfileEntry *pOld = 0; - ZipfileEntry *pOld2 = 0; - int bUpdate = 0; /* True for an update that modifies "name" */ - int bIsDir = 0; - u32 iCrc32 = 0; - - (void)pRowid; - - if( pTab->pWriteFd==0 ){ - rc = zipfileBegin(pVtab); - if( rc!=SQLITE_OK ) return rc; - } - - /* If this is a DELETE or UPDATE, find the archive entry to delete. */ - if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ - const char *zDelete = (const char*)sqlite3_value_text(apVal[0]); - int nDelete = (int)strlen(zDelete); - if( nVal>1 ){ - const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]); - if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){ - bUpdate = 1; - } - } - for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){ - if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){ - break; - } - assert( pOld->pNext ); - } - } - - if( nVal>1 ){ - /* Check that "sz" and "rawdata" are both NULL: */ - if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){ - zipfileTableErr(pTab, "sz must be NULL"); - rc = SQLITE_CONSTRAINT; - } - if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){ - zipfileTableErr(pTab, "rawdata must be NULL"); - rc = SQLITE_CONSTRAINT; - } - - if( rc==SQLITE_OK ){ - if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){ - /* data=NULL. A directory */ - bIsDir = 1; - }else{ - /* Value specified for "data", and possibly "method". This must be - ** a regular file or a symlink. */ - const u8 *aIn = sqlite3_value_blob(apVal[7]); - int nIn = sqlite3_value_bytes(apVal[7]); - int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL; - - iMethod = sqlite3_value_int(apVal[8]); - sz = nIn; - pData = aIn; - nData = nIn; - if( iMethod!=0 && iMethod!=8 ){ - zipfileTableErr(pTab, "unknown compression method: %d", iMethod); - rc = SQLITE_CONSTRAINT; - }else{ - if( bAuto || iMethod ){ - int nCmp; - rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg); - if( rc==SQLITE_OK ){ - if( iMethod || nCmpbase.zErrMsg); - } - - if( rc==SQLITE_OK ){ - zPath = (const char*)sqlite3_value_text(apVal[2]); - if( zPath==0 ) zPath = ""; - nPath = (int)strlen(zPath); - mTime = zipfileGetTime(apVal[4]); - } - - if( rc==SQLITE_OK && bIsDir ){ - /* For a directory, check that the last character in the path is a - ** '/'. This appears to be required for compatibility with info-zip - ** (the unzip command on unix). It does not create directories - ** otherwise. */ - if( nPath<=0 || zPath[nPath-1]!='/' ){ - zFree = sqlite3_mprintf("%s/", zPath); - zPath = (const char*)zFree; - if( zFree==0 ){ - rc = SQLITE_NOMEM; - nPath = 0; - }else{ - nPath = (int)strlen(zPath); - } - } - } - - /* Check that we're not inserting a duplicate entry -OR- updating an - ** entry with a path, thereby making it into a duplicate. */ - if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){ - ZipfileEntry *p; - for(p=pTab->pFirstEntry; p; p=p->pNext){ - if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){ - switch( sqlite3_vtab_on_conflict(pTab->db) ){ - case SQLITE_IGNORE: { - goto zipfile_update_done; - } - case SQLITE_REPLACE: { - pOld2 = p; - break; - } - default: { - zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath); - rc = SQLITE_CONSTRAINT; - break; - } - } - break; - } - } - } - - if( rc==SQLITE_OK ){ - /* Create the new CDS record. */ - pNew = zipfileNewEntry(zPath); - if( pNew==0 ){ - rc = SQLITE_NOMEM; - }else{ - pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; - pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; - pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS; - pNew->cds.iCompression = (u16)iMethod; - zipfileMtimeToDos(&pNew->cds, mTime); - pNew->cds.crc32 = iCrc32; - pNew->cds.szCompressed = nData; - pNew->cds.szUncompressed = (u32)sz; - pNew->cds.iExternalAttr = (mode<<16); - pNew->cds.iOffset = (u32)pTab->szCurrent; - pNew->cds.nFile = (u16)nPath; - pNew->mUnixTime = (u32)mTime; - rc = zipfileAppendEntry(pTab, pNew, pData, nData); - zipfileAddEntry(pTab, pOld, pNew); - } - } - } - - if( rc==SQLITE_OK && (pOld || pOld2) ){ - ZipfileCsr *pCsr; - for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ - if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){ - pCsr->pCurrent = pCsr->pCurrent->pNext; - pCsr->bNoop = 1; - } - } - - zipfileRemoveEntryFromList(pTab, pOld); - zipfileRemoveEntryFromList(pTab, pOld2); - } - -zipfile_update_done: - sqlite3_free(pFree); - sqlite3_free(zFree); - return rc; -} - -static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){ - u8 *a = aBuf; - zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD); - zipfileWrite16(a, p->iDisk); - zipfileWrite16(a, p->iFirstDisk); - zipfileWrite16(a, p->nEntry); - zipfileWrite16(a, p->nEntryTotal); - zipfileWrite32(a, p->nSize); - zipfileWrite32(a, p->iOffset); - zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/ - - return a-aBuf; -} - -static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){ - int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer); - assert( nBuf==ZIPFILE_EOCD_FIXED_SZ ); - return zipfileAppendData(pTab, pTab->aBuffer, nBuf); -} - -/* -** Serialize the CDS structure into buffer aBuf[]. Return the number -** of bytes written. -*/ -static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){ - u8 *a = aBuf; - ZipfileCDS *pCDS = &pEntry->cds; - - if( pEntry->aExtra==0 ){ - pCDS->nExtra = 9; - } - - zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS); - zipfileWrite16(a, pCDS->iVersionMadeBy); - zipfileWrite16(a, pCDS->iVersionExtract); - zipfileWrite16(a, pCDS->flags); - zipfileWrite16(a, pCDS->iCompression); - zipfileWrite16(a, pCDS->mTime); - zipfileWrite16(a, pCDS->mDate); - zipfileWrite32(a, pCDS->crc32); - zipfileWrite32(a, pCDS->szCompressed); - zipfileWrite32(a, pCDS->szUncompressed); - assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); - zipfileWrite16(a, pCDS->nFile); - zipfileWrite16(a, pCDS->nExtra); - zipfileWrite16(a, pCDS->nComment); - zipfileWrite16(a, pCDS->iDiskStart); - zipfileWrite16(a, pCDS->iInternalAttr); - zipfileWrite32(a, pCDS->iExternalAttr); - zipfileWrite32(a, pCDS->iOffset); - - memcpy(a, pCDS->zFile, pCDS->nFile); - a += pCDS->nFile; - - if( pEntry->aExtra ){ - int n = (int)pCDS->nExtra + (int)pCDS->nComment; - memcpy(a, pEntry->aExtra, n); - a += n; - }else{ - assert( pCDS->nExtra==9 ); - zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); - zipfileWrite16(a, 5); - *a++ = 0x01; - zipfileWrite32(a, pEntry->mUnixTime); - } - - return a-aBuf; -} - -static int zipfileCommit(sqlite3_vtab *pVtab){ - ZipfileTab *pTab = (ZipfileTab*)pVtab; - int rc = SQLITE_OK; - if( pTab->pWriteFd ){ - i64 iOffset = pTab->szCurrent; - ZipfileEntry *p; - ZipfileEOCD eocd; - int nEntry = 0; - - /* Write out all entries */ - for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){ - int n = zipfileSerializeCDS(p, pTab->aBuffer); - rc = zipfileAppendData(pTab, pTab->aBuffer, n); - nEntry++; - } - - /* Write out the EOCD record */ - eocd.iDisk = 0; - eocd.iFirstDisk = 0; - eocd.nEntry = (u16)nEntry; - eocd.nEntryTotal = (u16)nEntry; - eocd.nSize = (u32)(pTab->szCurrent - iOffset); - eocd.iOffset = (u32)iOffset; - rc = zipfileAppendEOCD(pTab, &eocd); - - zipfileCleanupTransaction(pTab); - } - return rc; -} - -static int zipfileRollback(sqlite3_vtab *pVtab){ - return zipfileCommit(pVtab); -} - -static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){ - ZipfileCsr *pCsr; - for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ - if( iId==pCsr->iId ) break; - } - return pCsr; -} - -static void zipfileFunctionCds( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - ZipfileCsr *pCsr; - ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context); - assert( argc>0 ); - - pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0])); - if( pCsr ){ - ZipfileCDS *p = &pCsr->pCurrent->cds; - char *zRes = sqlite3_mprintf("{" - "\"version-made-by\" : %u, " - "\"version-to-extract\" : %u, " - "\"flags\" : %u, " - "\"compression\" : %u, " - "\"time\" : %u, " - "\"date\" : %u, " - "\"crc32\" : %u, " - "\"compressed-size\" : %u, " - "\"uncompressed-size\" : %u, " - "\"file-name-length\" : %u, " - "\"extra-field-length\" : %u, " - "\"file-comment-length\" : %u, " - "\"disk-number-start\" : %u, " - "\"internal-attr\" : %u, " - "\"external-attr\" : %u, " - "\"offset\" : %u }", - (u32)p->iVersionMadeBy, (u32)p->iVersionExtract, - (u32)p->flags, (u32)p->iCompression, - (u32)p->mTime, (u32)p->mDate, - (u32)p->crc32, (u32)p->szCompressed, - (u32)p->szUncompressed, (u32)p->nFile, - (u32)p->nExtra, (u32)p->nComment, - (u32)p->iDiskStart, (u32)p->iInternalAttr, - (u32)p->iExternalAttr, (u32)p->iOffset - ); - - if( zRes==0 ){ - sqlite3_result_error_nomem(context); - }else{ - sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT); - sqlite3_free(zRes); - } - } -} - -/* -** xFindFunction method. -*/ -static int zipfileFindFunction( - sqlite3_vtab *pVtab, /* Virtual table handle */ - int nArg, /* Number of SQL function arguments */ - const char *zName, /* Name of SQL function */ - void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ - void **ppArg /* OUT: User data for *pxFunc */ -){ - (void)nArg; - if( sqlite3_stricmp("zipfile_cds", zName)==0 ){ - *pxFunc = zipfileFunctionCds; - *ppArg = (void*)pVtab; - return 1; - } - return 0; -} - -typedef struct ZipfileBuffer ZipfileBuffer; -struct ZipfileBuffer { - u8 *a; /* Pointer to buffer */ - int n; /* Size of buffer in bytes */ - int nAlloc; /* Byte allocated at a[] */ -}; - -typedef struct ZipfileCtx ZipfileCtx; -struct ZipfileCtx { - int nEntry; - ZipfileBuffer body; - ZipfileBuffer cds; -}; - -static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){ - if( pBuf->n+nByte>pBuf->nAlloc ){ - u8 *aNew; - sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512; - int nReq = pBuf->n + nByte; - - while( nNewa, nNew); - if( aNew==0 ) return SQLITE_NOMEM; - pBuf->a = aNew; - pBuf->nAlloc = (int)nNew; - } - return SQLITE_OK; -} - -/* -** xStep() callback for the zipfile() aggregate. This can be called in -** any of the following ways: -** -** SELECT zipfile(name,data) ... -** SELECT zipfile(name,mode,mtime,data) ... -** SELECT zipfile(name,mode,mtime,data,method) ... -*/ -static void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){ - ZipfileCtx *p; /* Aggregate function context */ - ZipfileEntry e; /* New entry to add to zip archive */ - - sqlite3_value *pName = 0; - sqlite3_value *pMode = 0; - sqlite3_value *pMtime = 0; - sqlite3_value *pData = 0; - sqlite3_value *pMethod = 0; - - int bIsDir = 0; - u32 mode; - int rc = SQLITE_OK; - char *zErr = 0; - - int iMethod = -1; /* Compression method to use (0 or 8) */ - - const u8 *aData = 0; /* Possibly compressed data for new entry */ - int nData = 0; /* Size of aData[] in bytes */ - int szUncompressed = 0; /* Size of data before compression */ - u8 *aFree = 0; /* Free this before returning */ - u32 iCrc32 = 0; /* crc32 of uncompressed data */ - - char *zName = 0; /* Path (name) of new entry */ - int nName = 0; /* Size of zName in bytes */ - char *zFree = 0; /* Free this before returning */ - int nByte; - - memset(&e, 0, sizeof(e)); - p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); - if( p==0 ) return; - - /* Martial the arguments into stack variables */ - if( nVal!=2 && nVal!=4 && nVal!=5 ){ - zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()"); - rc = SQLITE_ERROR; - goto zipfile_step_out; - } - pName = apVal[0]; - if( nVal==2 ){ - pData = apVal[1]; - }else{ - pMode = apVal[1]; - pMtime = apVal[2]; - pData = apVal[3]; - if( nVal==5 ){ - pMethod = apVal[4]; - } - } - - /* Check that the 'name' parameter looks ok. */ - zName = (char*)sqlite3_value_text(pName); - nName = sqlite3_value_bytes(pName); - if( zName==0 ){ - zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL"); - rc = SQLITE_ERROR; - goto zipfile_step_out; - } - - /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use - ** deflate compression) or NULL (choose automatically). */ - if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){ - iMethod = (int)sqlite3_value_int64(pMethod); - if( iMethod!=0 && iMethod!=8 ){ - zErr = sqlite3_mprintf("illegal method value: %d", iMethod); - rc = SQLITE_ERROR; - goto zipfile_step_out; - } - } - - /* Now inspect the data. If this is NULL, then the new entry must be a - ** directory. Otherwise, figure out whether or not the data should - ** be deflated or simply stored in the zip archive. */ - if( sqlite3_value_type(pData)==SQLITE_NULL ){ - bIsDir = 1; - iMethod = 0; - }else{ - aData = sqlite3_value_blob(pData); - szUncompressed = nData = sqlite3_value_bytes(pData); - iCrc32 = crc32(0, aData, nData); - if( iMethod<0 || iMethod==8 ){ - int nOut = 0; - rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr); - if( rc!=SQLITE_OK ){ - goto zipfile_step_out; - } - if( iMethod==8 || nOut0 && zName[nName-1]=='/' ){ - zErr = sqlite3_mprintf("non-directory name must not end with /"); - rc = SQLITE_ERROR; - goto zipfile_step_out; - } - }else{ - if( nName==0 || zName[nName-1]!='/' ){ - zName = zFree = sqlite3_mprintf("%s/", zName); - if( zName==0 ){ - rc = SQLITE_NOMEM; - goto zipfile_step_out; - } - nName = (int)strlen(zName); - }else{ - while( nName>1 && zName[nName-2]=='/' ) nName--; - } - } - - /* Assemble the ZipfileEntry object for the new zip archive entry */ - e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; - e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; - e.cds.flags = ZIPFILE_NEWENTRY_FLAGS; - e.cds.iCompression = (u16)iMethod; - zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime); - e.cds.crc32 = iCrc32; - e.cds.szCompressed = nData; - e.cds.szUncompressed = szUncompressed; - e.cds.iExternalAttr = (mode<<16); - e.cds.iOffset = p->body.n; - e.cds.nFile = (u16)nName; - e.cds.zFile = zName; - - /* Append the LFH to the body of the new archive */ - nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9; - if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out; - p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]); - - /* Append the data to the body of the new archive */ - if( nData>0 ){ - if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out; - memcpy(&p->body.a[p->body.n], aData, nData); - p->body.n += nData; - } - - /* Append the CDS record to the directory of the new archive */ - nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9; - if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out; - p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]); - - /* Increment the count of entries in the archive */ - p->nEntry++; - - zipfile_step_out: - sqlite3_free(aFree); - sqlite3_free(zFree); - if( rc ){ - if( zErr ){ - sqlite3_result_error(pCtx, zErr, -1); - }else{ - sqlite3_result_error_code(pCtx, rc); - } - } - sqlite3_free(zErr); -} - -/* -** xFinalize() callback for zipfile aggregate function. -*/ -static void zipfileFinal(sqlite3_context *pCtx){ - ZipfileCtx *p; - ZipfileEOCD eocd; - sqlite3_int64 nZip; - u8 *aZip; - - p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); - if( p==0 ) return; - if( p->nEntry>0 ){ - memset(&eocd, 0, sizeof(eocd)); - eocd.nEntry = (u16)p->nEntry; - eocd.nEntryTotal = (u16)p->nEntry; - eocd.nSize = p->cds.n; - eocd.iOffset = p->body.n; - - nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ; - aZip = (u8*)sqlite3_malloc64(nZip); - if( aZip==0 ){ - sqlite3_result_error_nomem(pCtx); - }else{ - memcpy(aZip, p->body.a, p->body.n); - memcpy(&aZip[p->body.n], p->cds.a, p->cds.n); - zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]); - sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree); - } - } - - sqlite3_free(p->body.a); - sqlite3_free(p->cds.a); -} - - -/* -** Register the "zipfile" virtual table. -*/ -static int zipfileRegister(sqlite3 *db){ - static sqlite3_module zipfileModule = { - 1, /* iVersion */ - zipfileConnect, /* xCreate */ - zipfileConnect, /* xConnect */ - zipfileBestIndex, /* xBestIndex */ - zipfileDisconnect, /* xDisconnect */ - zipfileDisconnect, /* xDestroy */ - zipfileOpen, /* xOpen - open a cursor */ - zipfileClose, /* xClose - close a cursor */ - zipfileFilter, /* xFilter - configure scan constraints */ - zipfileNext, /* xNext - advance a cursor */ - zipfileEof, /* xEof - check for end of scan */ - zipfileColumn, /* xColumn - read data */ - 0, /* xRowid - read data */ - zipfileUpdate, /* xUpdate */ - zipfileBegin, /* xBegin */ - 0, /* xSync */ - zipfileCommit, /* xCommit */ - zipfileRollback, /* xRollback */ - zipfileFindFunction, /* xFindMethod */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollback */ - 0, /* xShadowName */ - 0 /* xIntegrity */ - }; - - int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0); - if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, - zipfileStep, zipfileFinal - ); - } - assert( sizeof(i64)==8 ); - assert( sizeof(u32)==4 ); - assert( sizeof(u16)==2 ); - assert( sizeof(u8)==1 ); - return rc; -} -#else /* SQLITE_OMIT_VIRTUALTABLE */ -# define zipfileRegister(x) SQLITE_OK -#endif - -#ifdef _WIN32 - -#endif -int sqlite3_zipfile_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; /* Unused parameter */ - return zipfileRegister(db); -} - -/************************* End ../ext/misc/zipfile.c ********************/ -/************************* Begin ../ext/misc/sqlar.c ******************/ -/* -** 2017-12-17 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** Utility functions sqlar_compress() and sqlar_uncompress(). Useful -** for working with sqlar archives and used by the shell tool's built-in -** sqlar support. -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include - -/* -** Implementation of the "sqlar_compress(X)" SQL function. -** -** If the type of X is SQLITE_BLOB, and compressing that blob using -** zlib utility function compress() yields a smaller blob, return the -** compressed blob. Otherwise, return a copy of X. -** -** SQLar uses the "zlib format" for compressed content. The zlib format -** contains a two-byte identification header and a four-byte checksum at -** the end. This is different from ZIP which uses the raw deflate format. -** -** Future enhancements to SQLar might add support for new compression formats. -** If so, those new formats will be identified by alternative headers in the -** compressed data. -*/ -static void sqlarCompressFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - assert( argc==1 ); - if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){ - const Bytef *pData = sqlite3_value_blob(argv[0]); - uLong nData = sqlite3_value_bytes(argv[0]); - uLongf nOut = compressBound(nData); - Bytef *pOut; - - pOut = (Bytef*)sqlite3_malloc(nOut); - if( pOut==0 ){ - sqlite3_result_error_nomem(context); - return; - }else{ - if( Z_OK!=compress(pOut, &nOut, pData, nData) ){ - sqlite3_result_error(context, "error in compress()", -1); - }else if( nOut -#include -#include - -#if !defined(SQLITE_AMALGAMATION) -#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST) -# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1 -#endif -#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS) -# define ALWAYS(X) (1) -# define NEVER(X) (0) -#elif !defined(NDEBUG) -# define ALWAYS(X) ((X)?1:(assert(0),0)) -# define NEVER(X) ((X)?(assert(0),1):0) -#else -# define ALWAYS(X) (X) -# define NEVER(X) (X) -#endif -#endif /* !defined(SQLITE_AMALGAMATION) */ - - -#ifndef SQLITE_OMIT_VIRTUALTABLE - -/* typedef sqlite3_int64 i64; */ -/* typedef sqlite3_uint64 u64; */ - -typedef struct IdxColumn IdxColumn; -typedef struct IdxConstraint IdxConstraint; -typedef struct IdxScan IdxScan; -typedef struct IdxStatement IdxStatement; -typedef struct IdxTable IdxTable; -typedef struct IdxWrite IdxWrite; - -#define STRLEN (int)strlen - -/* -** A temp table name that we assume no user database will actually use. -** If this assumption proves incorrect triggers on the table with the -** conflicting name will be ignored. -*/ -#define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776" - -/* -** A single constraint. Equivalent to either "col = ?" or "col < ?" (or -** any other type of single-ended range constraint on a column). -** -** pLink: -** Used to temporarily link IdxConstraint objects into lists while -** creating candidate indexes. -*/ -struct IdxConstraint { - char *zColl; /* Collation sequence */ - int bRange; /* True for range, false for eq */ - int iCol; /* Constrained table column */ - int bFlag; /* Used by idxFindCompatible() */ - int bDesc; /* True if ORDER BY DESC */ - IdxConstraint *pNext; /* Next constraint in pEq or pRange list */ - IdxConstraint *pLink; /* See above */ -}; - -/* -** A single scan of a single table. -*/ -struct IdxScan { - IdxTable *pTab; /* Associated table object */ - int iDb; /* Database containing table zTable */ - i64 covering; /* Mask of columns required for cov. index */ - IdxConstraint *pOrder; /* ORDER BY columns */ - IdxConstraint *pEq; /* List of == constraints */ - IdxConstraint *pRange; /* List of < constraints */ - IdxScan *pNextScan; /* Next IdxScan object for same analysis */ -}; - -/* -** Information regarding a single database table. Extracted from -** "PRAGMA table_info" by function idxGetTableInfo(). -*/ -struct IdxColumn { - char *zName; - char *zColl; - int iPk; -}; -struct IdxTable { - int nCol; - char *zName; /* Table name */ - IdxColumn *aCol; - IdxTable *pNext; /* Next table in linked list of all tables */ -}; - -/* -** An object of the following type is created for each unique table/write-op -** seen. The objects are stored in a singly-linked list beginning at -** sqlite3expert.pWrite. -*/ -struct IdxWrite { - IdxTable *pTab; - int eOp; /* SQLITE_UPDATE, DELETE or INSERT */ - IdxWrite *pNext; -}; - -/* -** Each statement being analyzed is represented by an instance of this -** structure. -*/ -struct IdxStatement { - int iId; /* Statement number */ - char *zSql; /* SQL statement */ - char *zIdx; /* Indexes */ - char *zEQP; /* Plan */ - IdxStatement *pNext; -}; - - -/* -** A hash table for storing strings. With space for a payload string -** with each entry. Methods are: -** -** idxHashInit() -** idxHashClear() -** idxHashAdd() -** idxHashSearch() -*/ -#define IDX_HASH_SIZE 1023 -typedef struct IdxHashEntry IdxHashEntry; -typedef struct IdxHash IdxHash; -struct IdxHashEntry { - char *zKey; /* nul-terminated key */ - char *zVal; /* nul-terminated value string */ - char *zVal2; /* nul-terminated value string 2 */ - IdxHashEntry *pHashNext; /* Next entry in same hash bucket */ - IdxHashEntry *pNext; /* Next entry in hash */ -}; -struct IdxHash { - IdxHashEntry *pFirst; - IdxHashEntry *aHash[IDX_HASH_SIZE]; -}; - -/* -** sqlite3expert object. -*/ -struct sqlite3expert { - int iSample; /* Percentage of tables to sample for stat1 */ - sqlite3 *db; /* User database */ - sqlite3 *dbm; /* In-memory db for this analysis */ - sqlite3 *dbv; /* Vtab schema for this analysis */ - IdxTable *pTable; /* List of all IdxTable objects */ - IdxScan *pScan; /* List of scan objects */ - IdxWrite *pWrite; /* List of write objects */ - IdxStatement *pStatement; /* List of IdxStatement objects */ - int bRun; /* True once analysis has run */ - char **pzErrmsg; - int rc; /* Error code from whereinfo hook */ - IdxHash hIdx; /* Hash containing all candidate indexes */ - char *zCandidates; /* For EXPERT_REPORT_CANDIDATES */ -}; - - -/* -** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc(). -** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL. -*/ -static void *idxMalloc(int *pRc, int nByte){ - void *pRet; - assert( *pRc==SQLITE_OK ); - assert( nByte>0 ); - pRet = sqlite3_malloc(nByte); - if( pRet ){ - memset(pRet, 0, nByte); - }else{ - *pRc = SQLITE_NOMEM; - } - return pRet; -} - -/* -** Initialize an IdxHash hash table. -*/ -static void idxHashInit(IdxHash *pHash){ - memset(pHash, 0, sizeof(IdxHash)); -} - -/* -** Reset an IdxHash hash table. -*/ -static void idxHashClear(IdxHash *pHash){ - int i; - for(i=0; iaHash[i]; pEntry; pEntry=pNext){ - pNext = pEntry->pHashNext; - sqlite3_free(pEntry->zVal2); - sqlite3_free(pEntry); - } - } - memset(pHash, 0, sizeof(IdxHash)); -} - -/* -** Return the index of the hash bucket that the string specified by the -** arguments to this function belongs. -*/ -static int idxHashString(const char *z, int n){ - unsigned int ret = 0; - int i; - for(i=0; i=0 ); - for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ - if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ - return 1; - } - } - pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1); - if( pEntry ){ - pEntry->zKey = (char*)&pEntry[1]; - memcpy(pEntry->zKey, zKey, nKey); - if( zVal ){ - pEntry->zVal = &pEntry->zKey[nKey+1]; - memcpy(pEntry->zVal, zVal, nVal); - } - pEntry->pHashNext = pHash->aHash[iHash]; - pHash->aHash[iHash] = pEntry; - - pEntry->pNext = pHash->pFirst; - pHash->pFirst = pEntry; - } - return 0; -} - -/* -** If zKey/nKey is present in the hash table, return a pointer to the -** hash-entry object. -*/ -static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){ - int iHash; - IdxHashEntry *pEntry; - if( nKey<0 ) nKey = STRLEN(zKey); - iHash = idxHashString(zKey, nKey); - assert( iHash>=0 ); - for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){ - if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){ - return pEntry; - } - } - return 0; -} - -/* -** If the hash table contains an entry with a key equal to the string -** passed as the final two arguments to this function, return a pointer -** to the payload string. Otherwise, if zKey/nKey is not present in the -** hash table, return NULL. -*/ -static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){ - IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey); - if( pEntry ) return pEntry->zVal; - return 0; -} - -/* -** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl -** variable to point to a copy of nul-terminated string zColl. -*/ -static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){ - IdxConstraint *pNew; - int nColl = STRLEN(zColl); - - assert( *pRc==SQLITE_OK ); - pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1); - if( pNew ){ - pNew->zColl = (char*)&pNew[1]; - memcpy(pNew->zColl, zColl, nColl+1); - } - return pNew; -} - -/* -** An error associated with database handle db has just occurred. Pass -** the error message to callback function xOut. -*/ -static void idxDatabaseError( - sqlite3 *db, /* Database handle */ - char **pzErrmsg /* Write error here */ -){ - *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db)); -} - -/* -** Prepare an SQL statement. -*/ -static int idxPrepareStmt( - sqlite3 *db, /* Database handle to compile against */ - sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */ - char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */ - const char *zSql /* SQL statement to compile */ -){ - int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); - if( rc!=SQLITE_OK ){ - *ppStmt = 0; - idxDatabaseError(db, pzErrmsg); - } - return rc; -} - -/* -** Prepare an SQL statement using the results of a printf() formatting. -*/ -static int idxPrintfPrepareStmt( - sqlite3 *db, /* Database handle to compile against */ - sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */ - char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */ - const char *zFmt, /* printf() format of SQL statement */ - ... /* Trailing printf() arguments */ -){ - va_list ap; - int rc; - char *zSql; - va_start(ap, zFmt); - zSql = sqlite3_vmprintf(zFmt, ap); - if( zSql==0 ){ - rc = SQLITE_NOMEM; - }else{ - rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql); - sqlite3_free(zSql); - } - va_end(ap); - return rc; -} - - -/************************************************************************* -** Beginning of virtual table implementation. -*/ -typedef struct ExpertVtab ExpertVtab; -struct ExpertVtab { - sqlite3_vtab base; - IdxTable *pTab; - sqlite3expert *pExpert; -}; - -typedef struct ExpertCsr ExpertCsr; -struct ExpertCsr { - sqlite3_vtab_cursor base; - sqlite3_stmt *pData; -}; - -static char *expertDequote(const char *zIn){ - int n = STRLEN(zIn); - char *zRet = sqlite3_malloc(n); - - assert( zIn[0]=='\'' ); - assert( zIn[n-1]=='\'' ); - - if( zRet ){ - int iOut = 0; - int iIn = 0; - for(iIn=1; iIn<(n-1); iIn++){ - if( zIn[iIn]=='\'' ){ - assert( zIn[iIn+1]=='\'' ); - iIn++; - } - zRet[iOut++] = zIn[iIn]; - } - zRet[iOut] = '\0'; - } - - return zRet; -} - -/* -** This function is the implementation of both the xConnect and xCreate -** methods of the r-tree virtual table. -** -** argv[0] -> module name -** argv[1] -> database name -** argv[2] -> table name -** argv[...] -> column names... -*/ -static int expertConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - sqlite3expert *pExpert = (sqlite3expert*)pAux; - ExpertVtab *p = 0; - int rc; - - if( argc!=4 ){ - *pzErr = sqlite3_mprintf("internal error!"); - rc = SQLITE_ERROR; - }else{ - char *zCreateTable = expertDequote(argv[3]); - if( zCreateTable ){ - rc = sqlite3_declare_vtab(db, zCreateTable); - if( rc==SQLITE_OK ){ - p = idxMalloc(&rc, sizeof(ExpertVtab)); - } - if( rc==SQLITE_OK ){ - p->pExpert = pExpert; - p->pTab = pExpert->pTable; - assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 ); - } - sqlite3_free(zCreateTable); - }else{ - rc = SQLITE_NOMEM; - } - } - - *ppVtab = (sqlite3_vtab*)p; - return rc; -} - -static int expertDisconnect(sqlite3_vtab *pVtab){ - ExpertVtab *p = (ExpertVtab*)pVtab; - sqlite3_free(p); - return SQLITE_OK; -} - -static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){ - ExpertVtab *p = (ExpertVtab*)pVtab; - int rc = SQLITE_OK; - int n = 0; - IdxScan *pScan; - const int opmask = - SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT | - SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE | - SQLITE_INDEX_CONSTRAINT_LE; - - pScan = idxMalloc(&rc, sizeof(IdxScan)); - if( pScan ){ - int i; - - /* Link the new scan object into the list */ - pScan->pTab = p->pTab; - pScan->pNextScan = p->pExpert->pScan; - p->pExpert->pScan = pScan; - - /* Add the constraints to the IdxScan object */ - for(i=0; inConstraint; i++){ - struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; - if( pCons->usable - && pCons->iColumn>=0 - && p->pTab->aCol[pCons->iColumn].iPk==0 - && (pCons->op & opmask) - ){ - IdxConstraint *pNew; - const char *zColl = sqlite3_vtab_collation(pIdxInfo, i); - pNew = idxNewConstraint(&rc, zColl); - if( pNew ){ - pNew->iCol = pCons->iColumn; - if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ - pNew->pNext = pScan->pEq; - pScan->pEq = pNew; - }else{ - pNew->bRange = 1; - pNew->pNext = pScan->pRange; - pScan->pRange = pNew; - } - } - n++; - pIdxInfo->aConstraintUsage[i].argvIndex = n; - } - } - - /* Add the ORDER BY to the IdxScan object */ - for(i=pIdxInfo->nOrderBy-1; i>=0; i--){ - int iCol = pIdxInfo->aOrderBy[i].iColumn; - if( iCol>=0 ){ - IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl); - if( pNew ){ - pNew->iCol = iCol; - pNew->bDesc = pIdxInfo->aOrderBy[i].desc; - pNew->pNext = pScan->pOrder; - pNew->pLink = pScan->pOrder; - pScan->pOrder = pNew; - n++; - } - } - } - } - - pIdxInfo->estimatedCost = 1000000.0 / (n+1); - return rc; -} - -static int expertUpdate( - sqlite3_vtab *pVtab, - int nData, - sqlite3_value **azData, - sqlite_int64 *pRowid -){ - (void)pVtab; - (void)nData; - (void)azData; - (void)pRowid; - return SQLITE_OK; -} - -/* -** Virtual table module xOpen method. -*/ -static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ - int rc = SQLITE_OK; - ExpertCsr *pCsr; - (void)pVTab; - pCsr = idxMalloc(&rc, sizeof(ExpertCsr)); - *ppCursor = (sqlite3_vtab_cursor*)pCsr; - return rc; -} - -/* -** Virtual table module xClose method. -*/ -static int expertClose(sqlite3_vtab_cursor *cur){ - ExpertCsr *pCsr = (ExpertCsr*)cur; - sqlite3_finalize(pCsr->pData); - sqlite3_free(pCsr); - return SQLITE_OK; -} - -/* -** Virtual table module xEof method. -** -** Return non-zero if the cursor does not currently point to a valid -** record (i.e if the scan has finished), or zero otherwise. -*/ -static int expertEof(sqlite3_vtab_cursor *cur){ - ExpertCsr *pCsr = (ExpertCsr*)cur; - return pCsr->pData==0; -} - -/* -** Virtual table module xNext method. -*/ -static int expertNext(sqlite3_vtab_cursor *cur){ - ExpertCsr *pCsr = (ExpertCsr*)cur; - int rc = SQLITE_OK; - - assert( pCsr->pData ); - rc = sqlite3_step(pCsr->pData); - if( rc!=SQLITE_ROW ){ - rc = sqlite3_finalize(pCsr->pData); - pCsr->pData = 0; - }else{ - rc = SQLITE_OK; - } - - return rc; -} - -/* -** Virtual table module xRowid method. -*/ -static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ - (void)cur; - *pRowid = 0; - return SQLITE_OK; -} - -/* -** Virtual table module xColumn method. -*/ -static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ - ExpertCsr *pCsr = (ExpertCsr*)cur; - sqlite3_value *pVal; - pVal = sqlite3_column_value(pCsr->pData, i); - if( pVal ){ - sqlite3_result_value(ctx, pVal); - } - return SQLITE_OK; -} - -/* -** Virtual table module xFilter method. -*/ -static int expertFilter( - sqlite3_vtab_cursor *cur, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - ExpertCsr *pCsr = (ExpertCsr*)cur; - ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab); - sqlite3expert *pExpert = pVtab->pExpert; - int rc; - - (void)idxNum; - (void)idxStr; - (void)argc; - (void)argv; - rc = sqlite3_finalize(pCsr->pData); - pCsr->pData = 0; - if( rc==SQLITE_OK ){ - rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg, - "SELECT * FROM main.%Q WHERE sqlite_expert_sample()", pVtab->pTab->zName - ); - } - - if( rc==SQLITE_OK ){ - rc = expertNext(cur); - } - return rc; -} - -static int idxRegisterVtab(sqlite3expert *p){ - static sqlite3_module expertModule = { - 2, /* iVersion */ - expertConnect, /* xCreate - create a table */ - expertConnect, /* xConnect - connect to an existing table */ - expertBestIndex, /* xBestIndex - Determine search strategy */ - expertDisconnect, /* xDisconnect - Disconnect from a table */ - expertDisconnect, /* xDestroy - Drop a table */ - expertOpen, /* xOpen - open a cursor */ - expertClose, /* xClose - close a cursor */ - expertFilter, /* xFilter - configure scan constraints */ - expertNext, /* xNext - advance a cursor */ - expertEof, /* xEof */ - expertColumn, /* xColumn - read data */ - expertRowid, /* xRowid - read data */ - expertUpdate, /* xUpdate - write data */ - 0, /* xBegin - begin transaction */ - 0, /* xSync - sync transaction */ - 0, /* xCommit - commit transaction */ - 0, /* xRollback - rollback transaction */ - 0, /* xFindFunction - function overloading */ - 0, /* xRename - rename the table */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0, /* xShadowName */ - 0, /* xIntegrity */ - }; - - return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p); -} -/* -** End of virtual table implementation. -*************************************************************************/ -/* -** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function -** is called, set it to the return value of sqlite3_finalize() before -** returning. Otherwise, discard the sqlite3_finalize() return value. -*/ -static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){ - int rc = sqlite3_finalize(pStmt); - if( *pRc==SQLITE_OK ) *pRc = rc; -} - -/* -** Attempt to allocate an IdxTable structure corresponding to table zTab -** in the main database of connection db. If successful, set (*ppOut) to -** point to the new object and return SQLITE_OK. Otherwise, return an -** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be -** set to point to an error string. -** -** It is the responsibility of the caller to eventually free either the -** IdxTable object or error message using sqlite3_free(). -*/ -static int idxGetTableInfo( - sqlite3 *db, /* Database connection to read details from */ - const char *zTab, /* Table name */ - IdxTable **ppOut, /* OUT: New object (if successful) */ - char **pzErrmsg /* OUT: Error message (if not) */ -){ - sqlite3_stmt *p1 = 0; - int nCol = 0; - int nTab; - int nByte; - IdxTable *pNew = 0; - int rc, rc2; - char *pCsr = 0; - int nPk = 0; - - *ppOut = 0; - if( zTab==0 ) return SQLITE_ERROR; - nTab = STRLEN(zTab); - nByte = sizeof(IdxTable) + nTab + 1; - rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){ - const char *zCol = (const char*)sqlite3_column_text(p1, 1); - const char *zColSeq = 0; - if( zCol==0 ){ - rc = SQLITE_ERROR; - break; - } - nByte += 1 + STRLEN(zCol); - rc = sqlite3_table_column_metadata( - db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0 - ); - if( zColSeq==0 ) zColSeq = "binary"; - nByte += 1 + STRLEN(zColSeq); - nCol++; - nPk += (sqlite3_column_int(p1, 5)>0); - } - rc2 = sqlite3_reset(p1); - if( rc==SQLITE_OK ) rc = rc2; - - nByte += sizeof(IdxColumn) * nCol; - if( rc==SQLITE_OK ){ - pNew = idxMalloc(&rc, nByte); - } - if( rc==SQLITE_OK ){ - pNew->aCol = (IdxColumn*)&pNew[1]; - pNew->nCol = nCol; - pCsr = (char*)&pNew->aCol[nCol]; - } - - nCol = 0; - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){ - const char *zCol = (const char*)sqlite3_column_text(p1, 1); - const char *zColSeq = 0; - int nCopy; - if( zCol==0 ) continue; - nCopy = STRLEN(zCol) + 1; - pNew->aCol[nCol].zName = pCsr; - pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1); - memcpy(pCsr, zCol, nCopy); - pCsr += nCopy; - - rc = sqlite3_table_column_metadata( - db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0 - ); - if( rc==SQLITE_OK ){ - if( zColSeq==0 ) zColSeq = "binary"; - nCopy = STRLEN(zColSeq) + 1; - pNew->aCol[nCol].zColl = pCsr; - memcpy(pCsr, zColSeq, nCopy); - pCsr += nCopy; - } - - nCol++; - } - idxFinalize(&rc, p1); - - if( rc!=SQLITE_OK ){ - sqlite3_free(pNew); - pNew = 0; - }else if( ALWAYS(pNew!=0) ){ - pNew->zName = pCsr; - if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1); - } - - *ppOut = pNew; - return rc; -} - -/* -** This function is a no-op if *pRc is set to anything other than -** SQLITE_OK when it is called. -** -** If *pRc is initially set to SQLITE_OK, then the text specified by -** the printf() style arguments is appended to zIn and the result returned -** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on -** zIn before returning. -*/ -static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){ - va_list ap; - char *zAppend = 0; - char *zRet = 0; - int nIn = zIn ? STRLEN(zIn) : 0; - int nAppend = 0; - va_start(ap, zFmt); - if( *pRc==SQLITE_OK ){ - zAppend = sqlite3_vmprintf(zFmt, ap); - if( zAppend ){ - nAppend = STRLEN(zAppend); - zRet = (char*)sqlite3_malloc(nIn + nAppend + 1); - } - if( zAppend && zRet ){ - if( nIn ) memcpy(zRet, zIn, nIn); - memcpy(&zRet[nIn], zAppend, nAppend+1); - }else{ - sqlite3_free(zRet); - zRet = 0; - *pRc = SQLITE_NOMEM; - } - sqlite3_free(zAppend); - sqlite3_free(zIn); - } - va_end(ap); - return zRet; -} - -/* -** Return true if zId must be quoted in order to use it as an SQL -** identifier, or false otherwise. -*/ -static int idxIdentifierRequiresQuotes(const char *zId){ - int i; - int nId = STRLEN(zId); - - if( sqlite3_keyword_check(zId, nId) ) return 1; - - for(i=0; zId[i]; i++){ - if( !(zId[i]=='_') - && !(zId[i]>='0' && zId[i]<='9') - && !(zId[i]>='a' && zId[i]<='z') - && !(zId[i]>='A' && zId[i]<='Z') - ){ - return 1; - } - } - return 0; -} - -/* -** This function appends an index column definition suitable for constraint -** pCons to the string passed as zIn and returns the result. -*/ -static char *idxAppendColDefn( - int *pRc, /* IN/OUT: Error code */ - char *zIn, /* Column defn accumulated so far */ - IdxTable *pTab, /* Table index will be created on */ - IdxConstraint *pCons -){ - char *zRet = zIn; - IdxColumn *p = &pTab->aCol[pCons->iCol]; - if( zRet ) zRet = idxAppendText(pRc, zRet, ", "); - - if( idxIdentifierRequiresQuotes(p->zName) ){ - zRet = idxAppendText(pRc, zRet, "%Q", p->zName); - }else{ - zRet = idxAppendText(pRc, zRet, "%s", p->zName); - } - - if( sqlite3_stricmp(p->zColl, pCons->zColl) ){ - if( idxIdentifierRequiresQuotes(pCons->zColl) ){ - zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl); - }else{ - zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl); - } - } - - if( pCons->bDesc ){ - zRet = idxAppendText(pRc, zRet, " DESC"); - } - return zRet; -} - -/* -** Search database dbm for an index compatible with the one idxCreateFromCons() -** would create from arguments pScan, pEq and pTail. If no error occurs and -** such an index is found, return non-zero. Or, if no such index is found, -** return zero. -** -** If an error occurs, set *pRc to an SQLite error code and return zero. -*/ -static int idxFindCompatible( - int *pRc, /* OUT: Error code */ - sqlite3* dbm, /* Database to search */ - IdxScan *pScan, /* Scan for table to search for index on */ - IdxConstraint *pEq, /* List of == constraints */ - IdxConstraint *pTail /* List of range constraints */ -){ - const char *zTbl = pScan->pTab->zName; - sqlite3_stmt *pIdxList = 0; - IdxConstraint *pIter; - int nEq = 0; /* Number of elements in pEq */ - int rc; - - /* Count the elements in list pEq */ - for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++; - - rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl); - while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){ - int bMatch = 1; - IdxConstraint *pT = pTail; - sqlite3_stmt *pInfo = 0; - const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1); - if( zIdx==0 ) continue; - - /* Zero the IdxConstraint.bFlag values in the pEq list */ - for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0; - - rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx); - while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){ - int iIdx = sqlite3_column_int(pInfo, 0); - int iCol = sqlite3_column_int(pInfo, 1); - const char *zColl = (const char*)sqlite3_column_text(pInfo, 4); - - if( iIdxpLink){ - if( pIter->bFlag ) continue; - if( pIter->iCol!=iCol ) continue; - if( sqlite3_stricmp(pIter->zColl, zColl) ) continue; - pIter->bFlag = 1; - break; - } - if( pIter==0 ){ - bMatch = 0; - break; - } - }else{ - if( pT ){ - if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){ - bMatch = 0; - break; - } - pT = pT->pLink; - } - } - } - idxFinalize(&rc, pInfo); - - if( rc==SQLITE_OK && bMatch ){ - sqlite3_finalize(pIdxList); - return 1; - } - } - idxFinalize(&rc, pIdxList); - - *pRc = rc; - return 0; -} - -/* Callback for sqlite3_exec() with query with leading count(*) column. - * The first argument is expected to be an int*, referent to be incremented - * if that leading column is not exactly '0'. - */ -static int countNonzeros(void* pCount, int nc, - char* azResults[], char* azColumns[]){ - (void)azColumns; /* Suppress unused parameter warning */ - if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){ - *((int *)pCount) += 1; - } - return 0; -} - -static int idxCreateFromCons( - sqlite3expert *p, - IdxScan *pScan, - IdxConstraint *pEq, - IdxConstraint *pTail -){ - sqlite3 *dbm = p->dbm; - int rc = SQLITE_OK; - if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){ - IdxTable *pTab = pScan->pTab; - char *zCols = 0; - char *zIdx = 0; - IdxConstraint *pCons; - unsigned int h = 0; - const char *zFmt; - - for(pCons=pEq; pCons; pCons=pCons->pLink){ - zCols = idxAppendColDefn(&rc, zCols, pTab, pCons); - } - for(pCons=pTail; pCons; pCons=pCons->pLink){ - zCols = idxAppendColDefn(&rc, zCols, pTab, pCons); - } - - if( rc==SQLITE_OK ){ - /* Hash the list of columns to come up with a name for the index */ - const char *zTable = pScan->pTab->zName; - int quoteTable = idxIdentifierRequiresQuotes(zTable); - char *zName = 0; /* Index name */ - int collisions = 0; - do{ - int i; - char *zFind; - for(i=0; zCols[i]; i++){ - h += ((h<<3) + zCols[i]); - } - sqlite3_free(zName); - zName = sqlite3_mprintf("%s_idx_%08x", zTable, h); - if( zName==0 ) break; - /* Is is unique among table, view and index names? */ - zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q" - " AND type in ('index','table','view')"; - zFind = sqlite3_mprintf(zFmt, zName); - i = 0; - rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0); - assert(rc==SQLITE_OK); - sqlite3_free(zFind); - if( i==0 ){ - collisions = 0; - break; - } - ++collisions; - }while( collisions<50 && zName!=0 ); - if( collisions ){ - /* This return means "Gave up trying to find a unique index name." */ - rc = SQLITE_BUSY_TIMEOUT; - }else if( zName==0 ){ - rc = SQLITE_NOMEM; - }else{ - if( quoteTable ){ - zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)"; - }else{ - zFmt = "CREATE INDEX %s ON %s(%s)"; - } - zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols); - if( !zIdx ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg); - if( rc!=SQLITE_OK ){ - rc = SQLITE_BUSY_TIMEOUT; - }else{ - idxHashAdd(&rc, &p->hIdx, zName, zIdx); - } - } - sqlite3_free(zName); - sqlite3_free(zIdx); - } - } - - sqlite3_free(zCols); - } - return rc; -} - -/* -** Return true if list pList (linked by IdxConstraint.pLink) contains -** a constraint compatible with *p. Otherwise return false. -*/ -static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){ - IdxConstraint *pCmp; - for(pCmp=pList; pCmp; pCmp=pCmp->pLink){ - if( p->iCol==pCmp->iCol ) return 1; - } - return 0; -} - -static int idxCreateFromWhere( - sqlite3expert *p, - IdxScan *pScan, /* Create indexes for this scan */ - IdxConstraint *pTail /* range/ORDER BY constraints for inclusion */ -){ - IdxConstraint *p1 = 0; - IdxConstraint *pCon; - int rc; - - /* Gather up all the == constraints. */ - for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){ - if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){ - pCon->pLink = p1; - p1 = pCon; - } - } - - /* Create an index using the == constraints collected above. And the - ** range constraint/ORDER BY terms passed in by the caller, if any. */ - rc = idxCreateFromCons(p, pScan, p1, pTail); - - /* If no range/ORDER BY passed by the caller, create a version of the - ** index for each range constraint. */ - if( pTail==0 ){ - for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){ - assert( pCon->pLink==0 ); - if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){ - rc = idxCreateFromCons(p, pScan, p1, pCon); - } - } - } - - return rc; -} - -/* -** Create candidate indexes in database [dbm] based on the data in -** linked-list pScan. -*/ -static int idxCreateCandidates(sqlite3expert *p){ - int rc = SQLITE_OK; - IdxScan *pIter; - - for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){ - rc = idxCreateFromWhere(p, pIter, 0); - if( rc==SQLITE_OK && pIter->pOrder ){ - rc = idxCreateFromWhere(p, pIter, pIter->pOrder); - } - } - - return rc; -} - -/* -** Free all elements of the linked list starting at pConstraint. -*/ -static void idxConstraintFree(IdxConstraint *pConstraint){ - IdxConstraint *pNext; - IdxConstraint *p; - - for(p=pConstraint; p; p=pNext){ - pNext = p->pNext; - sqlite3_free(p); - } -} - -/* -** Free all elements of the linked list starting from pScan up until pLast -** (pLast is not freed). -*/ -static void idxScanFree(IdxScan *pScan, IdxScan *pLast){ - IdxScan *p; - IdxScan *pNext; - for(p=pScan; p!=pLast; p=pNext){ - pNext = p->pNextScan; - idxConstraintFree(p->pOrder); - idxConstraintFree(p->pEq); - idxConstraintFree(p->pRange); - sqlite3_free(p); - } -} - -/* -** Free all elements of the linked list starting from pStatement up -** until pLast (pLast is not freed). -*/ -static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){ - IdxStatement *p; - IdxStatement *pNext; - for(p=pStatement; p!=pLast; p=pNext){ - pNext = p->pNext; - sqlite3_free(p->zEQP); - sqlite3_free(p->zIdx); - sqlite3_free(p); - } -} - -/* -** Free the linked list of IdxTable objects starting at pTab. -*/ -static void idxTableFree(IdxTable *pTab){ - IdxTable *pIter; - IdxTable *pNext; - for(pIter=pTab; pIter; pIter=pNext){ - pNext = pIter->pNext; - sqlite3_free(pIter); - } -} - -/* -** Free the linked list of IdxWrite objects starting at pTab. -*/ -static void idxWriteFree(IdxWrite *pTab){ - IdxWrite *pIter; - IdxWrite *pNext; - for(pIter=pTab; pIter; pIter=pNext){ - pNext = pIter->pNext; - sqlite3_free(pIter); - } -} - - - -/* -** This function is called after candidate indexes have been created. It -** runs all the queries to see which indexes they prefer, and populates -** IdxStatement.zIdx and IdxStatement.zEQP with the results. -*/ -static int idxFindIndexes( - sqlite3expert *p, - char **pzErr /* OUT: Error message (sqlite3_malloc) */ -){ - IdxStatement *pStmt; - sqlite3 *dbm = p->dbm; - int rc = SQLITE_OK; - - IdxHash hIdx; - idxHashInit(&hIdx); - - for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){ - IdxHashEntry *pEntry; - sqlite3_stmt *pExplain = 0; - idxHashClear(&hIdx); - rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr, - "EXPLAIN QUERY PLAN %s", pStmt->zSql - ); - while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){ - /* int iId = sqlite3_column_int(pExplain, 0); */ - /* int iParent = sqlite3_column_int(pExplain, 1); */ - /* int iNotUsed = sqlite3_column_int(pExplain, 2); */ - const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3); - int nDetail; - int i; - - if( !zDetail ) continue; - nDetail = STRLEN(zDetail); - - for(i=0; ihIdx, zIdx, nIdx); - if( zSql ){ - idxHashAdd(&rc, &hIdx, zSql, 0); - if( rc ) goto find_indexes_out; - } - break; - } - } - - if( zDetail[0]!='-' ){ - pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail); - } - } - - for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ - pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey); - } - - idxFinalize(&rc, pExplain); - } - - find_indexes_out: - idxHashClear(&hIdx); - return rc; -} - -static int idxAuthCallback( - void *pCtx, - int eOp, - const char *z3, - const char *z4, - const char *zDb, - const char *zTrigger -){ - int rc = SQLITE_OK; - (void)z4; - (void)zTrigger; - if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){ - if( sqlite3_stricmp(zDb, "main")==0 ){ - sqlite3expert *p = (sqlite3expert*)pCtx; - IdxTable *pTab; - for(pTab=p->pTable; pTab; pTab=pTab->pNext){ - if( 0==sqlite3_stricmp(z3, pTab->zName) ) break; - } - if( pTab ){ - IdxWrite *pWrite; - for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){ - if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break; - } - if( pWrite==0 ){ - pWrite = idxMalloc(&rc, sizeof(IdxWrite)); - if( rc==SQLITE_OK ){ - pWrite->pTab = pTab; - pWrite->eOp = eOp; - pWrite->pNext = p->pWrite; - p->pWrite = pWrite; - } - } - } - } - } - return rc; -} - -static int idxProcessOneTrigger( - sqlite3expert *p, - IdxWrite *pWrite, - char **pzErr -){ - static const char *zInt = UNIQUE_TABLE_NAME; - static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME; - IdxTable *pTab = pWrite->pTab; - const char *zTab = pTab->zName; - const char *zSql = - "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema " - "WHERE tbl_name = %Q AND type IN ('table', 'trigger') " - "ORDER BY type;"; - sqlite3_stmt *pSelect = 0; - int rc = SQLITE_OK; - char *zWrite = 0; - - /* Create the table and its triggers in the temp schema */ - rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){ - const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0); - if( zCreate==0 ) continue; - rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr); - } - idxFinalize(&rc, pSelect); - - /* Rename the table in the temp schema to zInt */ - if( rc==SQLITE_OK ){ - char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt); - if( z==0 ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr); - sqlite3_free(z); - } - } - - switch( pWrite->eOp ){ - case SQLITE_INSERT: { - int i; - zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt); - for(i=0; inCol; i++){ - zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", "); - } - zWrite = idxAppendText(&rc, zWrite, ")"); - break; - } - case SQLITE_UPDATE: { - int i; - zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt); - for(i=0; inCol; i++){ - zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ", - pTab->aCol[i].zName - ); - } - break; - } - default: { - assert( pWrite->eOp==SQLITE_DELETE ); - if( rc==SQLITE_OK ){ - zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt); - if( zWrite==0 ) rc = SQLITE_NOMEM; - } - } - } - - if( rc==SQLITE_OK ){ - sqlite3_stmt *pX = 0; - rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0); - idxFinalize(&rc, pX); - if( rc!=SQLITE_OK ){ - idxDatabaseError(p->dbv, pzErr); - } - } - sqlite3_free(zWrite); - - if( rc==SQLITE_OK ){ - rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr); - } - - return rc; -} - -static int idxProcessTriggers(sqlite3expert *p, char **pzErr){ - int rc = SQLITE_OK; - IdxWrite *pEnd = 0; - IdxWrite *pFirst = p->pWrite; - - while( rc==SQLITE_OK && pFirst!=pEnd ){ - IdxWrite *pIter; - for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){ - rc = idxProcessOneTrigger(p, pIter, pzErr); - } - pEnd = pFirst; - pFirst = p->pWrite; - } - - return rc; -} - -/* -** This function tests if the schema of the main database of database handle -** db contains an object named zTab. Assuming no error occurs, output parameter -** (*pbContains) is set to true if zTab exists, or false if it does not. -** -** Or, if an error occurs, an SQLite error code is returned. The final value -** of (*pbContains) is undefined in this case. -*/ -static int expertDbContainsObject( - sqlite3 *db, - const char *zTab, - int *pbContains /* OUT: True if object exists */ -){ - const char *zSql = "SELECT 1 FROM sqlite_schema WHERE name = ?"; - sqlite3_stmt *pSql = 0; - int rc = SQLITE_OK; - int ret = 0; - - rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); - if( rc==SQLITE_OK ){ - sqlite3_bind_text(pSql, 1, zTab, -1, SQLITE_STATIC); - if( SQLITE_ROW==sqlite3_step(pSql) ){ - ret = 1; - } - rc = sqlite3_finalize(pSql); - } - - *pbContains = ret; - return rc; -} - -/* -** Execute SQL command zSql using database handle db. If no error occurs, -** set (*pzErr) to NULL and return SQLITE_OK. -** -** If an error does occur, return an SQLite error code and set (*pzErr) to -** point to a buffer containing an English language error message. Except, -** if the error message begins with "no such module:", then ignore the -** error and return as if the SQL statement had succeeded. -** -** This is used to copy as much of the database schema as possible while -** ignoring any errors related to missing virtual table modules. -*/ -static int expertSchemaSql(sqlite3 *db, const char *zSql, char **pzErr){ - int rc = SQLITE_OK; - char *zErr = 0; - - rc = sqlite3_exec(db, zSql, 0, 0, &zErr); - if( rc!=SQLITE_OK && zErr ){ - int nErr = STRLEN(zErr); - if( nErr>=15 && memcmp(zErr, "no such module:", 15)==0 ){ - sqlite3_free(zErr); - rc = SQLITE_OK; - zErr = 0; - } - } - - *pzErr = zErr; - return rc; -} - -static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){ - int rc = idxRegisterVtab(p); - sqlite3_stmt *pSchema = 0; - - /* For each table in the main db schema: - ** - ** 1) Add an entry to the p->pTable list, and - ** 2) Create the equivalent virtual table in dbv. - */ - rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg, - "SELECT type, name, sql, 1, " - " substr(sql,1,14)=='create virtual' COLLATE nocase " - "FROM sqlite_schema " - "WHERE type IN ('table','view') AND " - " substr(name,1,7)!='sqlite_' COLLATE nocase " - " UNION ALL " - "SELECT type, name, sql, 2, 0 FROM sqlite_schema " - "WHERE type = 'trigger'" - " AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') " - "ORDER BY 4, 5 DESC, 1" - ); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){ - const char *zType = (const char*)sqlite3_column_text(pSchema, 0); - const char *zName = (const char*)sqlite3_column_text(pSchema, 1); - const char *zSql = (const char*)sqlite3_column_text(pSchema, 2); - int bVirtual = sqlite3_column_int(pSchema, 4); - int bExists = 0; - - if( zType==0 || zName==0 ) continue; - rc = expertDbContainsObject(p->dbv, zName, &bExists); - if( rc || bExists ) continue; - - if( zType[0]=='v' || zType[1]=='r' || bVirtual ){ - /* A view. Or a trigger on a view. */ - if( zSql ) rc = expertSchemaSql(p->dbv, zSql, pzErrmsg); - }else{ - IdxTable *pTab; - rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg); - if( rc==SQLITE_OK ){ - int i; - char *zInner = 0; - char *zOuter = 0; - pTab->pNext = p->pTable; - p->pTable = pTab; - - /* The statement the vtab will pass to sqlite3_declare_vtab() */ - zInner = idxAppendText(&rc, 0, "CREATE TABLE x("); - for(i=0; inCol; i++){ - zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s", - (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl - ); - } - zInner = idxAppendText(&rc, zInner, ")"); - - /* The CVT statement to create the vtab */ - zOuter = idxAppendText(&rc, 0, - "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner - ); - if( rc==SQLITE_OK ){ - rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg); - } - sqlite3_free(zInner); - sqlite3_free(zOuter); - } - } - } - idxFinalize(&rc, pSchema); - return rc; -} - -struct IdxSampleCtx { - int iTarget; - double target; /* Target nRet/nRow value */ - double nRow; /* Number of rows seen */ - double nRet; /* Number of rows returned */ -}; - -static void idxSampleFunc( - sqlite3_context *pCtx, - int argc, - sqlite3_value **argv -){ - struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx); - int bRet; - - (void)argv; - assert( argc==0 ); - if( p->nRow==0.0 ){ - bRet = 1; - }else{ - bRet = (p->nRet / p->nRow) <= p->target; - if( bRet==0 ){ - unsigned short rnd; - sqlite3_randomness(2, (void*)&rnd); - bRet = ((int)rnd % 100) <= p->iTarget; - } - } - - sqlite3_result_int(pCtx, bRet); - p->nRow += 1.0; - p->nRet += (double)bRet; -} - -struct IdxRemCtx { - int nSlot; - struct IdxRemSlot { - int eType; /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */ - i64 iVal; /* SQLITE_INTEGER value */ - double rVal; /* SQLITE_FLOAT value */ - int nByte; /* Bytes of space allocated at z */ - int n; /* Size of buffer z */ - char *z; /* SQLITE_TEXT/BLOB value */ - } aSlot[1]; -}; - -/* -** Implementation of scalar function sqlite_expert_rem(). -*/ -static void idxRemFunc( - sqlite3_context *pCtx, - int argc, - sqlite3_value **argv -){ - struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx); - struct IdxRemSlot *pSlot; - int iSlot; - assert( argc==2 ); - - iSlot = sqlite3_value_int(argv[0]); - assert( iSlotnSlot ); - pSlot = &p->aSlot[iSlot]; - - switch( pSlot->eType ){ - case SQLITE_NULL: - /* no-op */ - break; - - case SQLITE_INTEGER: - sqlite3_result_int64(pCtx, pSlot->iVal); - break; - - case SQLITE_FLOAT: - sqlite3_result_double(pCtx, pSlot->rVal); - break; - - case SQLITE_BLOB: - sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); - break; - - case SQLITE_TEXT: - sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT); - break; - } - - pSlot->eType = sqlite3_value_type(argv[1]); - switch( pSlot->eType ){ - case SQLITE_NULL: - /* no-op */ - break; - - case SQLITE_INTEGER: - pSlot->iVal = sqlite3_value_int64(argv[1]); - break; - - case SQLITE_FLOAT: - pSlot->rVal = sqlite3_value_double(argv[1]); - break; - - case SQLITE_BLOB: - case SQLITE_TEXT: { - int nByte = sqlite3_value_bytes(argv[1]); - const void *pData = 0; - if( nByte>pSlot->nByte ){ - char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2); - if( zNew==0 ){ - sqlite3_result_error_nomem(pCtx); - return; - } - pSlot->nByte = nByte*2; - pSlot->z = zNew; - } - pSlot->n = nByte; - if( pSlot->eType==SQLITE_BLOB ){ - pData = sqlite3_value_blob(argv[1]); - if( pData ) memcpy(pSlot->z, pData, nByte); - }else{ - pData = sqlite3_value_text(argv[1]); - memcpy(pSlot->z, pData, nByte); - } - break; - } - } -} - -static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){ - int rc = SQLITE_OK; - const char *zMax = - "SELECT max(i.seqno) FROM " - " sqlite_schema AS s, " - " pragma_index_list(s.name) AS l, " - " pragma_index_info(l.name) AS i " - "WHERE s.type = 'table'"; - sqlite3_stmt *pMax = 0; - - *pnMax = 0; - rc = idxPrepareStmt(db, &pMax, pzErr, zMax); - if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){ - *pnMax = sqlite3_column_int(pMax, 0) + 1; - } - idxFinalize(&rc, pMax); - - return rc; -} - -static int idxPopulateOneStat1( - sqlite3expert *p, - sqlite3_stmt *pIndexXInfo, - sqlite3_stmt *pWriteStat, - const char *zTab, - const char *zIdx, - char **pzErr -){ - char *zCols = 0; - char *zOrder = 0; - char *zQuery = 0; - int nCol = 0; - int i; - sqlite3_stmt *pQuery = 0; - int *aStat = 0; - int rc = SQLITE_OK; - - assert( p->iSample>0 ); - - /* Formulate the query text */ - sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC); - while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){ - const char *zComma = zCols==0 ? "" : ", "; - const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0); - const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1); - if( zName==0 ){ - /* This index contains an expression. Ignore it. */ - sqlite3_free(zCols); - sqlite3_free(zOrder); - return sqlite3_reset(pIndexXInfo); - } - zCols = idxAppendText(&rc, zCols, - "%sx.%Q IS sqlite_expert_rem(%d, x.%Q) COLLATE %s", - zComma, zName, nCol, zName, zColl - ); - zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol); - } - sqlite3_reset(pIndexXInfo); - if( rc==SQLITE_OK ){ - if( p->iSample==100 ){ - zQuery = sqlite3_mprintf( - "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder - ); - }else{ - zQuery = sqlite3_mprintf( - "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder - ); - } - } - sqlite3_free(zCols); - sqlite3_free(zOrder); - - /* Formulate the query text */ - if( rc==SQLITE_OK ){ - sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); - rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery); - } - sqlite3_free(zQuery); - - if( rc==SQLITE_OK ){ - aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1)); - } - if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){ - IdxHashEntry *pEntry; - char *zStat = 0; - for(i=0; i<=nCol; i++) aStat[i] = 1; - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){ - aStat[0]++; - for(i=0; ihIdx, zIdx, STRLEN(zIdx)); - if( pEntry ){ - assert( pEntry->zVal2==0 ); - pEntry->zVal2 = zStat; - }else{ - sqlite3_free(zStat); - } - } - sqlite3_free(aStat); - idxFinalize(&rc, pQuery); - - return rc; -} - -static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){ - int rc; - char *zSql; - - rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); - if( rc!=SQLITE_OK ) return rc; - - zSql = sqlite3_mprintf( - "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab - ); - if( zSql==0 ) return SQLITE_NOMEM; - rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0); - sqlite3_free(zSql); - - return rc; -} - -/* -** This function is called as part of sqlite3_expert_analyze(). Candidate -** indexes have already been created in database sqlite3expert.dbm, this -** function populates sqlite_stat1 table in the same database. -** -** The stat1 data is generated by querying the -*/ -static int idxPopulateStat1(sqlite3expert *p, char **pzErr){ - int rc = SQLITE_OK; - int nMax =0; - struct IdxRemCtx *pCtx = 0; - struct IdxSampleCtx samplectx; - int i; - i64 iPrev = -100000; - sqlite3_stmt *pAllIndex = 0; - sqlite3_stmt *pIndexXInfo = 0; - sqlite3_stmt *pWrite = 0; - - const char *zAllIndex = - "SELECT s.rowid, s.name, l.name FROM " - " sqlite_schema AS s, " - " pragma_index_list(s.name) AS l " - "WHERE s.type = 'table'"; - const char *zIndexXInfo = - "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key"; - const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)"; - - /* If iSample==0, no sqlite_stat1 data is required. */ - if( p->iSample==0 ) return SQLITE_OK; - - rc = idxLargestIndex(p->dbm, &nMax, pzErr); - if( nMax<=0 || rc!=SQLITE_OK ) return rc; - - rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0); - - if( rc==SQLITE_OK ){ - int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax); - pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte); - } - - if( rc==SQLITE_OK ){ - sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv); - rc = sqlite3_create_function(dbrem, "sqlite_expert_rem", - 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0 - ); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(p->db, "sqlite_expert_sample", - 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0 - ); - } - - if( rc==SQLITE_OK ){ - pCtx->nSlot = nMax+1; - rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex); - } - if( rc==SQLITE_OK ){ - rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo); - } - if( rc==SQLITE_OK ){ - rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite); - } - - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){ - i64 iRowid = sqlite3_column_int64(pAllIndex, 0); - const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1); - const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2); - if( zTab==0 || zIdx==0 ) continue; - if( p->iSample<100 && iPrev!=iRowid ){ - samplectx.target = (double)p->iSample / 100.0; - samplectx.iTarget = p->iSample; - samplectx.nRow = 0.0; - samplectx.nRet = 0.0; - rc = idxBuildSampleTable(p, zTab); - if( rc!=SQLITE_OK ) break; - } - rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr); - iPrev = iRowid; - } - if( rc==SQLITE_OK && p->iSample<100 ){ - rc = sqlite3_exec(p->dbv, - "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0 - ); - } - - idxFinalize(&rc, pAllIndex); - idxFinalize(&rc, pIndexXInfo); - idxFinalize(&rc, pWrite); - - if( pCtx ){ - for(i=0; inSlot; i++){ - sqlite3_free(pCtx->aSlot[i].z); - } - sqlite3_free(pCtx); - } - - if( rc==SQLITE_OK ){ - rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0); - } - - sqlite3_create_function(p->db, "sqlite_expert_rem", 2, SQLITE_UTF8, 0,0,0,0); - sqlite3_create_function(p->db, "sqlite_expert_sample", 0,SQLITE_UTF8,0,0,0,0); - - sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0); - return rc; -} - -/* -** Define and possibly pretend to use a useless collation sequence. -** This pretense allows expert to accept SQL using custom collations. -*/ -int dummyCompare(void *up1, int up2, const void *up3, int up4, const void *up5){ - (void)up1; - (void)up2; - (void)up3; - (void)up4; - (void)up5; - assert(0); /* VDBE should never be run. */ - return 0; -} -/* And a callback to register above upon actual need */ -void useDummyCS(void *up1, sqlite3 *db, int etr, const char *zName){ - (void)up1; - sqlite3_create_collation_v2(db, zName, etr, 0, dummyCompare, 0); -} - -#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \ - && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) -/* -** dummy functions for no-op implementation of UDFs during expert's work -*/ -void dummyUDF(sqlite3_context *up1, int up2, sqlite3_value **up3){ - (void)up1; - (void)up2; - (void)up3; - assert(0); /* VDBE should never be run. */ -} -void dummyUDFvalue(sqlite3_context *up1){ - (void)up1; - assert(0); /* VDBE should never be run. */ -} - -/* -** Register UDFs from user database with another. -*/ -int registerUDFs(sqlite3 *dbSrc, sqlite3 *dbDst){ - sqlite3_stmt *pStmt; - int rc = sqlite3_prepare_v2(dbSrc, - "SELECT name,type,enc,narg,flags " - "FROM pragma_function_list() " - "WHERE builtin==0", -1, &pStmt, 0); - if( rc==SQLITE_OK ){ - while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){ - int nargs = sqlite3_column_int(pStmt,3); - int flags = sqlite3_column_int(pStmt,4); - const char *name = (char*)sqlite3_column_text(pStmt,0); - const char *type = (char*)sqlite3_column_text(pStmt,1); - const char *enc = (char*)sqlite3_column_text(pStmt,2); - if( name==0 || type==0 || enc==0 ){ - /* no-op. Only happens on OOM */ - }else{ - int ienc = SQLITE_UTF8; - int rcf = SQLITE_ERROR; - if( strcmp(enc,"utf16le")==0 ) ienc = SQLITE_UTF16LE; - else if( strcmp(enc,"utf16be")==0 ) ienc = SQLITE_UTF16BE; - ienc |= (flags & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY)); - if( strcmp(type,"w")==0 ){ - rcf = sqlite3_create_window_function(dbDst,name,nargs,ienc,0, - dummyUDF,dummyUDFvalue,0,0,0); - }else if( strcmp(type,"a")==0 ){ - rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0, - 0,dummyUDF,dummyUDFvalue); - }else if( strcmp(type,"s")==0 ){ - rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0, - dummyUDF,0,0); - } - if( rcf!=SQLITE_OK ){ - rc = rcf; - break; - } - } - } - sqlite3_finalize(pStmt); - if( rc==SQLITE_DONE ) rc = SQLITE_OK; - } - return rc; -} -#endif - -/* -** Allocate a new sqlite3expert object. -*/ -sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){ - int rc = SQLITE_OK; - sqlite3expert *pNew; - - pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert)); - - /* Open two in-memory databases to work with. The "vtab database" (dbv) - ** will contain a virtual table corresponding to each real table in - ** the user database schema, and a copy of each view. It is used to - ** collect information regarding the WHERE, ORDER BY and other clauses - ** of the user's query. - */ - if( rc==SQLITE_OK ){ - pNew->db = db; - pNew->iSample = 100; - rc = sqlite3_open(":memory:", &pNew->dbv); - } - if( rc==SQLITE_OK ){ - rc = sqlite3_open(":memory:", &pNew->dbm); - if( rc==SQLITE_OK ){ - sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0); - } - } - - /* Allow custom collations to be dealt with through prepare. */ - if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS); - if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS); - -#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \ - && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS) - /* Register UDFs from database [db] with [dbm] and [dbv]. */ - if( rc==SQLITE_OK ){ - rc = registerUDFs(pNew->db, pNew->dbm); - } - if( rc==SQLITE_OK ){ - rc = registerUDFs(pNew->db, pNew->dbv); - } -#endif - - /* Copy the entire schema of database [db] into [dbm]. */ - if( rc==SQLITE_OK ){ - sqlite3_stmt *pSql = 0; - rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, - "SELECT sql, name, substr(sql,1,14)=='create virtual' COLLATE nocase" - " FROM sqlite_schema WHERE substr(name,1,7)!='sqlite_' COLLATE nocase" - " ORDER BY 3 DESC, rowid" - ); - while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ - const char *zSql = (const char*)sqlite3_column_text(pSql, 0); - const char *zName = (const char*)sqlite3_column_text(pSql, 1); - int bExists = 0; - rc = expertDbContainsObject(pNew->dbm, zName, &bExists); - if( rc==SQLITE_OK && zSql && bExists==0 ){ - rc = expertSchemaSql(pNew->dbm, zSql, pzErrmsg); - } - } - idxFinalize(&rc, pSql); - } - - /* Create the vtab schema */ - if( rc==SQLITE_OK ){ - rc = idxCreateVtabSchema(pNew, pzErrmsg); - } - - /* Register the auth callback with dbv */ - if( rc==SQLITE_OK ){ - sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew); - } - - /* If an error has occurred, free the new object and reutrn NULL. Otherwise, - ** return the new sqlite3expert handle. */ - if( rc!=SQLITE_OK ){ - sqlite3_expert_destroy(pNew); - pNew = 0; - } - return pNew; -} - -/* -** Configure an sqlite3expert object. -*/ -int sqlite3_expert_config(sqlite3expert *p, int op, ...){ - int rc = SQLITE_OK; - va_list ap; - va_start(ap, op); - switch( op ){ - case EXPERT_CONFIG_SAMPLE: { - int iVal = va_arg(ap, int); - if( iVal<0 ) iVal = 0; - if( iVal>100 ) iVal = 100; - p->iSample = iVal; - break; - } - default: - rc = SQLITE_NOTFOUND; - break; - } - - va_end(ap); - return rc; -} - -/* -** Add an SQL statement to the analysis. -*/ -int sqlite3_expert_sql( - sqlite3expert *p, /* From sqlite3_expert_new() */ - const char *zSql, /* SQL statement to add */ - char **pzErr /* OUT: Error message (if any) */ -){ - IdxScan *pScanOrig = p->pScan; - IdxStatement *pStmtOrig = p->pStatement; - int rc = SQLITE_OK; - const char *zStmt = zSql; - - if( p->bRun ) return SQLITE_MISUSE; - - while( rc==SQLITE_OK && zStmt && zStmt[0] ){ - sqlite3_stmt *pStmt = 0; - /* Ensure that the provided statement compiles against user's DB. */ - rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt); - if( rc!=SQLITE_OK ) break; - sqlite3_finalize(pStmt); - rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt); - if( rc==SQLITE_OK ){ - if( pStmt ){ - IdxStatement *pNew; - const char *z = sqlite3_sql(pStmt); - int n = STRLEN(z); - pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1); - if( rc==SQLITE_OK ){ - pNew->zSql = (char*)&pNew[1]; - memcpy(pNew->zSql, z, n+1); - pNew->pNext = p->pStatement; - if( p->pStatement ) pNew->iId = p->pStatement->iId+1; - p->pStatement = pNew; - } - sqlite3_finalize(pStmt); - } - }else{ - idxDatabaseError(p->dbv, pzErr); - } - } - - if( rc!=SQLITE_OK ){ - idxScanFree(p->pScan, pScanOrig); - idxStatementFree(p->pStatement, pStmtOrig); - p->pScan = pScanOrig; - p->pStatement = pStmtOrig; - } - - return rc; -} - -int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){ - int rc; - IdxHashEntry *pEntry; - - /* Do trigger processing to collect any extra IdxScan structures */ - rc = idxProcessTriggers(p, pzErr); - - /* Create candidate indexes within the in-memory database file */ - if( rc==SQLITE_OK ){ - rc = idxCreateCandidates(p); - }else if ( rc==SQLITE_BUSY_TIMEOUT ){ - if( pzErr ) - *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose."); - return rc; - } - - /* Generate the stat1 data */ - if( rc==SQLITE_OK ){ - rc = idxPopulateStat1(p, pzErr); - } - - /* Formulate the EXPERT_REPORT_CANDIDATES text */ - for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){ - p->zCandidates = idxAppendText(&rc, p->zCandidates, - "%s;%s%s\n", pEntry->zVal, - pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2 - ); - } - - /* Figure out which of the candidate indexes are preferred by the query - ** planner and report the results to the user. */ - if( rc==SQLITE_OK ){ - rc = idxFindIndexes(p, pzErr); - } - - if( rc==SQLITE_OK ){ - p->bRun = 1; - } - return rc; -} - -/* -** Return the total number of statements that have been added to this -** sqlite3expert using sqlite3_expert_sql(). -*/ -int sqlite3_expert_count(sqlite3expert *p){ - int nRet = 0; - if( p->pStatement ) nRet = p->pStatement->iId+1; - return nRet; -} - -/* -** Return a component of the report. -*/ -const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){ - const char *zRet = 0; - IdxStatement *pStmt; - - if( p->bRun==0 ) return 0; - for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext); - switch( eReport ){ - case EXPERT_REPORT_SQL: - if( pStmt ) zRet = pStmt->zSql; - break; - case EXPERT_REPORT_INDEXES: - if( pStmt ) zRet = pStmt->zIdx; - break; - case EXPERT_REPORT_PLAN: - if( pStmt ) zRet = pStmt->zEQP; - break; - case EXPERT_REPORT_CANDIDATES: - zRet = p->zCandidates; - break; - } - return zRet; -} - -/* -** Free an sqlite3expert object. -*/ -void sqlite3_expert_destroy(sqlite3expert *p){ - if( p ){ - sqlite3_close(p->dbm); - sqlite3_close(p->dbv); - idxScanFree(p->pScan, 0); - idxStatementFree(p->pStatement, 0); - idxTableFree(p->pTable); - idxWriteFree(p->pWrite); - idxHashClear(&p->hIdx); - sqlite3_free(p->zCandidates); - sqlite3_free(p); - } -} - -#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ - -/************************* End ../ext/expert/sqlite3expert.c ********************/ -/************************* Begin ../ext/intck/sqlite3intck.h ******************/ -/* -** 2024-02-08 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -*/ - -/* -** Incremental Integrity-Check Extension -** ------------------------------------- -** -** This module contains code to check whether or not an SQLite database -** is well-formed or corrupt. This is the same task as performed by SQLite's -** built-in "PRAGMA integrity_check" command. This module differs from -** "PRAGMA integrity_check" in that: -** -** + It is less thorough - this module does not detect certain types -** of corruption that are detected by the PRAGMA command. However, -** it does detect all kinds of corruption that are likely to cause -** errors in SQLite applications. -** -** + It is slower. Sometimes up to three times slower. -** -** + It allows integrity-check operations to be split into multiple -** transactions, so that the database does not need to be read-locked -** for the duration of the integrity-check. -** -** One way to use the API to run integrity-check on the "main" database -** of handle db is: -** -** int rc = SQLITE_OK; -** sqlite3_intck *p = 0; -** -** sqlite3_intck_open(db, "main", &p); -** while( SQLITE_OK==sqlite3_intck_step(p) ){ -** const char *zMsg = sqlite3_intck_message(p); -** if( zMsg ) printf("corruption: %s\n", zMsg); -** } -** rc = sqlite3_intck_error(p, &zErr); -** if( rc!=SQLITE_OK ){ -** printf("error occured (rc=%d), (errmsg=%s)\n", rc, zErr); -** } -** sqlite3_intck_close(p); -** -** Usually, the sqlite3_intck object opens a read transaction within the -** first call to sqlite3_intck_step() and holds it open until the -** integrity-check is complete. However, if sqlite3_intck_unlock() is -** called, the read transaction is ended and a new read transaction opened -** by the subsequent call to sqlite3_intck_step(). -*/ - -#ifndef _SQLITE_INTCK_H -#define _SQLITE_INTCK_H - -/* #include "sqlite3.h" */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* -** An ongoing incremental integrity-check operation is represented by an -** opaque pointer of the following type. -*/ -typedef struct sqlite3_intck sqlite3_intck; - -/* -** Open a new incremental integrity-check object. If successful, populate -** output variable (*ppOut) with the new object handle and return SQLITE_OK. -** Or, if an error occurs, set (*ppOut) to NULL and return an SQLite error -** code (e.g. SQLITE_NOMEM). -** -** The integrity-check will be conducted on database zDb (which must be "main", -** "temp", or the name of an attached database) of database handle db. Once -** this function has been called successfully, the caller should not use -** database handle db until the integrity-check object has been destroyed -** using sqlite3_intck_close(). -*/ -int sqlite3_intck_open( - sqlite3 *db, /* Database handle */ - const char *zDb, /* Database name ("main", "temp" etc.) */ - sqlite3_intck **ppOut /* OUT: New sqlite3_intck handle */ -); - -/* -** Close and release all resources associated with a handle opened by an -** earlier call to sqlite3_intck_open(). The results of using an -** integrity-check handle after it has been passed to this function are -** undefined. -*/ -void sqlite3_intck_close(sqlite3_intck *pCk); - -/* -** Do the next step of the integrity-check operation specified by the handle -** passed as the only argument. This function returns SQLITE_DONE if the -** integrity-check operation is finished, or an SQLite error code if -** an error occurs, or SQLITE_OK if no error occurs but the integrity-check -** is not finished. It is not considered an error if database corruption -** is encountered. -** -** Following a successful call to sqlite3_intck_step() (one that returns -** SQLITE_OK), sqlite3_intck_message() returns a non-NULL value if -** corruption was detected in the db. -** -** If an error occurs and a value other than SQLITE_OK or SQLITE_DONE is -** returned, then the integrity-check handle is placed in an error state. -** In this state all subsequent calls to sqlite3_intck_step() or -** sqlite3_intck_unlock() will immediately return the same error. The -** sqlite3_intck_error() method may be used to obtain an English language -** error message in this case. -*/ -int sqlite3_intck_step(sqlite3_intck *pCk); - -/* -** If the previous call to sqlite3_intck_step() encountered corruption -** within the database, then this function returns a pointer to a buffer -** containing a nul-terminated string describing the corruption in -** English. If the previous call to sqlite3_intck_step() did not encounter -** corruption, or if there was no previous call, this function returns -** NULL. -*/ -const char *sqlite3_intck_message(sqlite3_intck *pCk); - -/* -** Close any read-transaction opened by an earlier call to -** sqlite3_intck_step(). Any subsequent call to sqlite3_intck_step() will -** open a new transaction. Return SQLITE_OK if successful, or an SQLite error -** code otherwise. -** -** If an error occurs, then the integrity-check handle is placed in an error -** state. In this state all subsequent calls to sqlite3_intck_step() or -** sqlite3_intck_unlock() will immediately return the same error. The -** sqlite3_intck_error() method may be used to obtain an English language -** error message in this case. -*/ -int sqlite3_intck_unlock(sqlite3_intck *pCk); - -/* -** If an error has occurred in an earlier call to sqlite3_intck_step() -** or sqlite3_intck_unlock(), then this method returns the associated -** SQLite error code. Additionally, if pzErr is not NULL, then (*pzErr) -** may be set to point to a nul-terminated string containing an English -** language error message. Or, if no error message is available, to -** NULL. -** -** If no error has occurred within sqlite3_intck_step() or -** sqlite_intck_unlock() calls on the handle passed as the first argument, -** then SQLITE_OK is returned and (*pzErr) set to NULL. -*/ -int sqlite3_intck_error(sqlite3_intck *pCk, const char **pzErr); - -/* -** This API is used for testing only. It returns the full-text of an SQL -** statement used to test object zObj, which may be a table or index. -** The returned buffer is valid until the next call to either this function -** or sqlite3_intck_close() on the same sqlite3_intck handle. -*/ -const char *sqlite3_intck_test_sql(sqlite3_intck *pCk, const char *zObj); - - -#ifdef __cplusplus -} /* end of the 'extern "C"' block */ -#endif - -#endif /* ifndef _SQLITE_INTCK_H */ - -/************************* End ../ext/intck/sqlite3intck.h ********************/ -/************************* Begin ../ext/intck/sqlite3intck.c ******************/ -/* -** 2024-02-08 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -*/ - -/* #include "sqlite3intck.h" */ -#include -#include - -#include -#include - -/* -** nKeyVal: -** The number of values that make up the 'key' for the current pCheck -** statement. -** -** rc: -** Error code returned by most recent sqlite3_intck_step() or -** sqlite3_intck_unlock() call. This is set to SQLITE_DONE when -** the integrity-check operation is finished. -** -** zErr: -** If the object has entered the error state, this is the error message. -** Is freed using sqlite3_free() when the object is deleted. -** -** zTestSql: -** The value returned by the most recent call to sqlite3_intck_testsql(). -** Each call to testsql() frees the previous zTestSql value (using -** sqlite3_free()) and replaces it with the new value it will return. -*/ -struct sqlite3_intck { - sqlite3 *db; - const char *zDb; /* Copy of zDb parameter to _open() */ - char *zObj; /* Current object. Or NULL. */ - - sqlite3_stmt *pCheck; /* Current check statement */ - char *zKey; - int nKeyVal; - - char *zMessage; - int bCorruptSchema; - - int rc; /* Error code */ - char *zErr; /* Error message */ - char *zTestSql; /* Returned by sqlite3_intck_test_sql() */ -}; - - -/* -** Some error has occurred while using database p->db. Save the error message -** and error code currently held by the database handle in p->rc and p->zErr. -*/ -static void intckSaveErrmsg(sqlite3_intck *p){ - p->rc = sqlite3_errcode(p->db); - sqlite3_free(p->zErr); - p->zErr = sqlite3_mprintf("%s", sqlite3_errmsg(p->db)); -} - -/* -** If the handle passed as the first argument is already in the error state, -** then this function is a no-op (returns NULL immediately). Otherwise, if an -** error occurs within this function, it leaves an error in said handle. -** -** Otherwise, this function attempts to prepare SQL statement zSql and -** return the resulting statement handle to the user. -*/ -static sqlite3_stmt *intckPrepare(sqlite3_intck *p, const char *zSql){ - sqlite3_stmt *pRet = 0; - if( p->rc==SQLITE_OK ){ - p->rc = sqlite3_prepare_v2(p->db, zSql, -1, &pRet, 0); - if( p->rc!=SQLITE_OK ){ - intckSaveErrmsg(p); - assert( pRet==0 ); - } - } - return pRet; -} - -/* -** If the handle passed as the first argument is already in the error state, -** then this function is a no-op (returns NULL immediately). Otherwise, if an -** error occurs within this function, it leaves an error in said handle. -** -** Otherwise, this function treats argument zFmt as a printf() style format -** string. It formats it according to the trailing arguments and then -** attempts to prepare the results and return the resulting prepared -** statement. -*/ -static sqlite3_stmt *intckPrepareFmt(sqlite3_intck *p, const char *zFmt, ...){ - sqlite3_stmt *pRet = 0; - va_list ap; - char *zSql = 0; - va_start(ap, zFmt); - zSql = sqlite3_vmprintf(zFmt, ap); - if( p->rc==SQLITE_OK && zSql==0 ){ - p->rc = SQLITE_NOMEM; - } - pRet = intckPrepare(p, zSql); - sqlite3_free(zSql); - va_end(ap); - return pRet; -} - -/* -** Finalize SQL statement pStmt. If an error occurs and the handle passed -** as the first argument does not already contain an error, store the -** error in the handle. -*/ -static void intckFinalize(sqlite3_intck *p, sqlite3_stmt *pStmt){ - int rc = sqlite3_finalize(pStmt); - if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){ - intckSaveErrmsg(p); - } -} - -/* -** If there is already an error in handle p, return it. Otherwise, call -** sqlite3_step() on the statement handle and return that value. -*/ -static int intckStep(sqlite3_intck *p, sqlite3_stmt *pStmt){ - if( p->rc ) return p->rc; - return sqlite3_step(pStmt); -} - -/* -** Execute SQL statement zSql. There is no way to obtain any results -** returned by the statement. This function uses the sqlite3_intck error -** code convention. -*/ -static void intckExec(sqlite3_intck *p, const char *zSql){ - sqlite3_stmt *pStmt = 0; - pStmt = intckPrepare(p, zSql); - intckStep(p, pStmt); - intckFinalize(p, pStmt); -} - -/* -** A wrapper around sqlite3_mprintf() that uses the sqlite3_intck error -** code convention. -*/ -static char *intckMprintf(sqlite3_intck *p, const char *zFmt, ...){ - va_list ap; - char *zRet = 0; - va_start(ap, zFmt); - zRet = sqlite3_vmprintf(zFmt, ap); - if( p->rc==SQLITE_OK ){ - if( zRet==0 ){ - p->rc = SQLITE_NOMEM; - } - }else{ - sqlite3_free(zRet); - zRet = 0; - } - return zRet; -} - -/* -** This is used by sqlite3_intck_unlock() to save the vector key value -** required to restart the current pCheck query as a nul-terminated string -** in p->zKey. -*/ -static void intckSaveKey(sqlite3_intck *p){ - int ii; - char *zSql = 0; - sqlite3_stmt *pStmt = 0; - sqlite3_stmt *pXinfo = 0; - const char *zDir = 0; - - assert( p->pCheck ); - assert( p->zKey==0 ); - - pXinfo = intckPrepareFmt(p, - "SELECT group_concat(desc, '') FROM %Q.sqlite_schema s, " - "pragma_index_xinfo(%Q, %Q) " - "WHERE s.type='index' AND s.name=%Q", - p->zDb, p->zObj, p->zDb, p->zObj - ); - if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXinfo) ){ - zDir = (const char*)sqlite3_column_text(pXinfo, 0); - } - - if( zDir==0 ){ - /* Object is a table, not an index. This is the easy case,as there are - ** no DESC columns or NULL values in a primary key. */ - const char *zSep = "SELECT '(' || "; - for(ii=0; iinKeyVal; ii++){ - zSql = intckMprintf(p, "%z%squote(?)", zSql, zSep); - zSep = " || ', ' || "; - } - zSql = intckMprintf(p, "%z || ')'", zSql); - }else{ - - /* Object is an index. */ - assert( p->nKeyVal>1 ); - for(ii=p->nKeyVal; ii>0; ii--){ - int bLastIsDesc = zDir[ii-1]=='1'; - int bLastIsNull = sqlite3_column_type(p->pCheck, ii)==SQLITE_NULL; - const char *zLast = sqlite3_column_name(p->pCheck, ii); - char *zLhs = 0; - char *zRhs = 0; - char *zWhere = 0; - - if( bLastIsNull ){ - if( bLastIsDesc ) continue; - zWhere = intckMprintf(p, "'%s IS NOT NULL'", zLast); - }else{ - const char *zOp = bLastIsDesc ? "<" : ">"; - zWhere = intckMprintf(p, "'%s %s ' || quote(?%d)", zLast, zOp, ii); - } - - if( ii>1 ){ - const char *zLhsSep = ""; - const char *zRhsSep = ""; - int jj; - for(jj=0; jjpCheck,jj+1); - zLhs = intckMprintf(p, "%z%s%s", zLhs, zLhsSep, zAlias); - zRhs = intckMprintf(p, "%z%squote(?%d)", zRhs, zRhsSep, jj+1); - zLhsSep = ","; - zRhsSep = " || ',' || "; - } - - zWhere = intckMprintf(p, - "'(%z) IS (' || %z || ') AND ' || %z", - zLhs, zRhs, zWhere); - } - zWhere = intckMprintf(p, "'WHERE ' || %z", zWhere); - - zSql = intckMprintf(p, "%z%s(quote( %z ) )", - zSql, - (zSql==0 ? "VALUES" : ",\n "), - zWhere - ); - } - zSql = intckMprintf(p, - "WITH wc(q) AS (\n%z\n)" - "SELECT 'VALUES' || group_concat('(' || q || ')', ',\n ') FROM wc" - , zSql - ); - } - - pStmt = intckPrepare(p, zSql); - if( p->rc==SQLITE_OK ){ - for(ii=0; iinKeyVal; ii++){ - sqlite3_bind_value(pStmt, ii+1, sqlite3_column_value(p->pCheck, ii+1)); - } - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - p->zKey = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0)); - } - intckFinalize(p, pStmt); - } - - sqlite3_free(zSql); - intckFinalize(p, pXinfo); -} - -/* -** Find the next database object (table or index) to check. If successful, -** set sqlite3_intck.zObj to point to a nul-terminated buffer containing -** the object's name before returning. -*/ -static void intckFindObject(sqlite3_intck *p){ - sqlite3_stmt *pStmt = 0; - char *zPrev = p->zObj; - p->zObj = 0; - - assert( p->rc==SQLITE_OK ); - assert( p->pCheck==0 ); - - pStmt = intckPrepareFmt(p, - "WITH tables(table_name) AS (" - " SELECT name" - " FROM %Q.sqlite_schema WHERE (type='table' OR type='index') AND rootpage" - " UNION ALL " - " SELECT 'sqlite_schema'" - ")" - "SELECT table_name FROM tables " - "WHERE ?1 IS NULL OR table_name%s?1 " - "ORDER BY 1" - , p->zDb, (p->zKey ? ">=" : ">") - ); - - if( p->rc==SQLITE_OK ){ - sqlite3_bind_text(pStmt, 1, zPrev, -1, SQLITE_TRANSIENT); - if( sqlite3_step(pStmt)==SQLITE_ROW ){ - p->zObj = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0)); - } - } - intckFinalize(p, pStmt); - - /* If this is a new object, ensure the previous key value is cleared. */ - if( sqlite3_stricmp(p->zObj, zPrev) ){ - sqlite3_free(p->zKey); - p->zKey = 0; - } - - sqlite3_free(zPrev); -} - -/* -** Return the size in bytes of the first token in nul-terminated buffer z. -** For the purposes of this call, a token is either: -** -** * a quoted SQL string, -* * a contiguous series of ascii alphabet characters, or -* * any other single byte. -*/ -static int intckGetToken(const char *z){ - char c = z[0]; - int iRet = 1; - if( c=='\'' || c=='"' || c=='`' ){ - while( 1 ){ - if( z[iRet]==c ){ - iRet++; - if( z[iRet]!=c ) break; - } - iRet++; - } - } - else if( c=='[' ){ - while( z[iRet++]!=']' && z[iRet] ); - } - else if( (c>='A' && c<='Z') || (c>='a' && c<='z') ){ - while( (z[iRet]>='A' && z[iRet]<='Z') || (z[iRet]>='a' && z[iRet]<='z') ){ - iRet++; - } - } - - return iRet; -} - -/* -** Return true if argument c is an ascii whitespace character. -*/ -static int intckIsSpace(char c){ - return (c==' ' || c=='\t' || c=='\n' || c=='\r'); -} - -/* -** Argument z points to the text of a CREATE INDEX statement. This function -** identifies the part of the text that contains either the index WHERE -** clause (if iCol<0) or the iCol'th column of the index. -** -** If (iCol<0), the identified fragment does not include the "WHERE" keyword, -** only the expression that follows it. If (iCol>=0) then the identified -** fragment does not include any trailing sort-order keywords - "ASC" or -** "DESC". -** -** If the CREATE INDEX statement does not contain the requested field or -** clause, NULL is returned and (*pnByte) is set to 0. Otherwise, a pointer to -** the identified fragment is returned and output parameter (*pnByte) set -** to its size in bytes. -*/ -static const char *intckParseCreateIndex(const char *z, int iCol, int *pnByte){ - int iOff = 0; - int iThisCol = 0; - int iStart = 0; - int nOpen = 0; - - const char *zRet = 0; - int nRet = 0; - - int iEndOfCol = 0; - - /* Skip forward until the first "(" token */ - while( z[iOff]!='(' ){ - iOff += intckGetToken(&z[iOff]); - if( z[iOff]=='\0' ) return 0; - } - assert( z[iOff]=='(' ); - - nOpen = 1; - iOff++; - iStart = iOff; - while( z[iOff] ){ - const char *zToken = &z[iOff]; - int nToken = 0; - - /* Check if this is the end of the current column - either a "," or ")" - ** when nOpen==1. */ - if( nOpen==1 ){ - if( z[iOff]==',' || z[iOff]==')' ){ - if( iCol==iThisCol ){ - int iEnd = iEndOfCol ? iEndOfCol : iOff; - nRet = (iEnd - iStart); - zRet = &z[iStart]; - break; - } - iStart = iOff+1; - while( intckIsSpace(z[iStart]) ) iStart++; - iThisCol++; - } - if( z[iOff]==')' ) break; - } - if( z[iOff]=='(' ) nOpen++; - if( z[iOff]==')' ) nOpen--; - nToken = intckGetToken(zToken); - - if( (nToken==3 && 0==sqlite3_strnicmp(zToken, "ASC", nToken)) - || (nToken==4 && 0==sqlite3_strnicmp(zToken, "DESC", nToken)) - ){ - iEndOfCol = iOff; - }else if( 0==intckIsSpace(zToken[0]) ){ - iEndOfCol = 0; - } - - iOff += nToken; - } - - /* iStart is now the byte offset of 1 byte passed the final ')' in the - ** CREATE INDEX statement. Try to find a WHERE clause to return. */ - while( zRet==0 && z[iOff] ){ - int n = intckGetToken(&z[iOff]); - if( n==5 && 0==sqlite3_strnicmp(&z[iOff], "where", 5) ){ - zRet = &z[iOff+5]; - nRet = (int)strlen(zRet); - } - iOff += n; - } - - /* Trim any whitespace from the start and end of the returned string. */ - if( zRet ){ - while( intckIsSpace(zRet[0]) ){ - nRet--; - zRet++; - } - while( nRet>0 && intckIsSpace(zRet[nRet-1]) ) nRet--; - } - - *pnByte = nRet; - return zRet; -} - -/* -** User-defined SQL function wrapper for intckParseCreateIndex(): -** -** SELECT parse_create_index(, ); -*/ -static void intckParseCreateIndexFunc( - sqlite3_context *pCtx, - int nVal, - sqlite3_value **apVal -){ - const char *zSql = (const char*)sqlite3_value_text(apVal[0]); - int idx = sqlite3_value_int(apVal[1]); - const char *zRes = 0; - int nRes = 0; - - assert( nVal==2 ); - if( zSql ){ - zRes = intckParseCreateIndex(zSql, idx, &nRes); - } - sqlite3_result_text(pCtx, zRes, nRes, SQLITE_TRANSIENT); -} - -/* -** Return true if sqlite3_intck.db has automatic indexes enabled, false -** otherwise. -*/ -static int intckGetAutoIndex(sqlite3_intck *p){ - int bRet = 0; - sqlite3_stmt *pStmt = 0; - pStmt = intckPrepare(p, "PRAGMA automatic_index"); - if( SQLITE_ROW==intckStep(p, pStmt) ){ - bRet = sqlite3_column_int(pStmt, 0); - } - intckFinalize(p, pStmt); - return bRet; -} - -/* -** Return true if zObj is an index, or false otherwise. -*/ -static int intckIsIndex(sqlite3_intck *p, const char *zObj){ - int bRet = 0; - sqlite3_stmt *pStmt = 0; - pStmt = intckPrepareFmt(p, - "SELECT 1 FROM %Q.sqlite_schema WHERE name=%Q AND type='index'", - p->zDb, zObj - ); - if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - bRet = 1; - } - intckFinalize(p, pStmt); - return bRet; -} - -/* -** Return a pointer to a nul-terminated buffer containing the SQL statement -** used to check database object zObj (a table or index) for corruption. -** If parameter zPrev is not NULL, then it must be a string containing the -** vector key required to restart the check where it left off last time. -** If pnKeyVal is not NULL, then (*pnKeyVal) is set to the number of -** columns in the vector key value for the specified object. -** -** This function uses the sqlite3_intck error code convention. -*/ -static char *intckCheckObjectSql( - sqlite3_intck *p, /* Integrity check object */ - const char *zObj, /* Object (table or index) to scan */ - const char *zPrev, /* Restart key vector, if any */ - int *pnKeyVal /* OUT: Number of key-values for this scan */ -){ - char *zRet = 0; - sqlite3_stmt *pStmt = 0; - int bAutoIndex = 0; - int bIsIndex = 0; - - const char *zCommon = - /* Relation without_rowid also contains just one row. Column "b" is - ** set to true if the table being examined is a WITHOUT ROWID table, - ** or false otherwise. */ - ", without_rowid(b) AS (" - " SELECT EXISTS (" - " SELECT 1 FROM tabname, pragma_index_list(tab, db) AS l" - " WHERE origin='pk' " - " AND NOT EXISTS (SELECT 1 FROM sqlite_schema WHERE name=l.name)" - " )" - ")" - "" - /* Table idx_cols contains 1 row for each column in each index on the - ** table being checked. Columns are: - ** - ** idx_name: Name of the index. - ** idx_ispk: True if this index is the PK of a WITHOUT ROWID table. - ** col_name: Name of indexed column, or NULL for index on expression. - ** col_expr: Indexed expression, including COLLATE clause. - ** col_alias: Alias used for column in 'intck_wrapper' table. - */ - ", idx_cols(idx_name, idx_ispk, col_name, col_expr, col_alias) AS (" - " SELECT l.name, (l.origin=='pk' AND w.b), i.name, COALESCE((" - " SELECT parse_create_index(sql, i.seqno) FROM " - " sqlite_schema WHERE name = l.name" - " ), format('\"%w\"', i.name) || ' COLLATE ' || quote(i.coll))," - " 'c' || row_number() OVER ()" - " FROM " - " tabname t," - " without_rowid w," - " pragma_index_list(t.tab, t.db) l," - " pragma_index_xinfo(l.name) i" - " WHERE i.key" - " UNION ALL" - " SELECT '', 1, '_rowid_', '_rowid_', 'r1' FROM without_rowid WHERE b=0" - ")" - "" - "" - /* - ** For a PK declared as "PRIMARY KEY(a, b) ... WITHOUT ROWID", where - ** the intck_wrapper aliases of "a" and "b" are "c1" and "c2": - ** - ** o_pk: "o.c1, o.c2" - ** i_pk: "i.'a', i.'b'" - ** ... - ** n_pk: 2 - */ - ", tabpk(db, tab, idx, o_pk, i_pk, q_pk, eq_pk, ps_pk, pk_pk, n_pk) AS (" - " WITH pkfields(f, a) AS (" - " SELECT i.col_name, i.col_alias FROM idx_cols i WHERE i.idx_ispk" - " )" - " SELECT t.db, t.tab, t.idx, " - " group_concat(a, ', '), " - " group_concat('i.'||quote(f), ', '), " - " group_concat('quote(o.'||a||')', ' || '','' || '), " - " format('(%s)==(%s)'," - " group_concat('o.'||a, ', '), " - " group_concat(format('\"%w\"', f), ', ')" - " )," - " group_concat('%s', ',')," - " group_concat('quote('||a||')', ', '), " - " count(*)" - " FROM tabname t, pkfields" - ")" - "" - ", idx(name, match_expr, partial, partial_alias, idx_ps, idx_idx) AS (" - " SELECT idx_name," - " format('(%s,%s) IS (%s,%s)', " - " group_concat(i.col_expr, ', '), i_pk," - " group_concat('o.'||i.col_alias, ', '), o_pk" - " ), " - " parse_create_index(" - " (SELECT sql FROM sqlite_schema WHERE name=idx_name), -1" - " )," - " 'cond' || row_number() OVER ()" - " , group_concat('%s', ',')" - " , group_concat('quote('||i.col_alias||')', ', ')" - " FROM tabpk t, " - " without_rowid w," - " idx_cols i" - " WHERE i.idx_ispk==0 " - " GROUP BY idx_name" - ")" - "" - ", wrapper_with(s) AS (" - " SELECT 'intck_wrapper AS (\n SELECT\n ' || (" - " WITH f(a, b) AS (" - " SELECT col_expr, col_alias FROM idx_cols" - " UNION ALL " - " SELECT partial, partial_alias FROM idx WHERE partial IS NOT NULL" - " )" - " SELECT group_concat(format('%s AS %s', a, b), ',\n ') FROM f" - " )" - " || format('\n FROM %Q.%Q ', t.db, t.tab)" - /* If the object being checked is a table, append "NOT INDEXED". - ** Otherwise, append "INDEXED BY ", and then, if the index - ** is a partial index " WHERE ". */ - " || CASE WHEN t.idx IS NULL THEN " - " 'NOT INDEXED'" - " ELSE" - " format('INDEXED BY %Q%s', t.idx, ' WHERE '||i.partial)" - " END" - " || '\n)'" - " FROM tabname t LEFT JOIN idx i ON (i.name=t.idx)" - ")" - "" - ; - - bAutoIndex = intckGetAutoIndex(p); - if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 0"); - - bIsIndex = intckIsIndex(p, zObj); - if( bIsIndex ){ - pStmt = intckPrepareFmt(p, - /* Table idxname contains a single row. The first column, "db", contains - ** the name of the db containing the table (e.g. "main") and the second, - ** "tab", the name of the table itself. */ - "WITH tabname(db, tab, idx) AS (" - " SELECT %Q, (SELECT tbl_name FROM %Q.sqlite_schema WHERE name=%Q), %Q " - ")" - "" - ", whereclause(w_c) AS (%s)" - "" - "%s" /* zCommon */ - "" - ", case_statement(c) AS (" - " SELECT " - " 'CASE WHEN (' || group_concat(col_alias, ', ') || ', 1) IS (\n' " - " || ' SELECT ' || group_concat(col_expr, ', ') || ', 1 FROM '" - " || format('%%Q.%%Q NOT INDEXED WHERE %%s\n', t.db, t.tab, p.eq_pk)" - " || ' )\n THEN NULL\n '" - " || 'ELSE format(''surplus entry ('" - " || group_concat('%%s', ',') || ',' || p.ps_pk" - " || ') in index ' || t.idx || ''', ' " - " || group_concat('quote('||i.col_alias||')', ', ') || ', ' || p.pk_pk" - " || ')'" - " || '\n END AS error_message'" - " FROM tabname t, tabpk p, idx_cols i WHERE i.idx_name=t.idx" - ")" - "" - ", thiskey(k, n) AS (" - " SELECT group_concat(i.col_alias, ', ') || ', ' || p.o_pk, " - " count(*) + p.n_pk " - " FROM tabpk p, idx_cols i WHERE i.idx_name=p.idx" - ")" - "" - ", main_select(m, n) AS (" - " SELECT format(" - " 'WITH %%s\n' ||" - " ', idx_checker AS (\n' ||" - " ' SELECT %%s,\n' ||" - " ' %%s\n' || " - " ' FROM intck_wrapper AS o\n' ||" - " ')\n'," - " ww.s, c, t.k" - " ), t.n" - " FROM case_statement, wrapper_with ww, thiskey t" - ")" - - "SELECT m || " - " group_concat('SELECT * FROM idx_checker ' || w_c, ' UNION ALL '), n" - " FROM " - "main_select, whereclause " - , p->zDb, p->zDb, zObj, zObj - , zPrev ? zPrev : "VALUES('')", zCommon - ); - }else{ - pStmt = intckPrepareFmt(p, - /* Table tabname contains a single row. The first column, "db", contains - ** the name of the db containing the table (e.g. "main") and the second, - ** "tab", the name of the table itself. */ - "WITH tabname(db, tab, idx, prev) AS (SELECT %Q, %Q, NULL, %Q)" - "" - "%s" /* zCommon */ - - /* expr(e) contains one row for each index on table zObj. Value e - ** is set to an expression that evaluates to NULL if the required - ** entry is present in the index, or an error message otherwise. */ - ", expr(e, p) AS (" - " SELECT format('CASE WHEN EXISTS \n" - " (SELECT 1 FROM %%Q.%%Q AS i INDEXED BY %%Q WHERE %%s%%s)\n" - " THEN NULL\n" - " ELSE format(''entry (%%s,%%s) missing from index %%s'', %%s, %%s)\n" - " END\n'" - " , t.db, t.tab, i.name, i.match_expr, ' AND (' || partial || ')'," - " i.idx_ps, t.ps_pk, i.name, i.idx_idx, t.pk_pk)," - " CASE WHEN partial IS NULL THEN NULL ELSE i.partial_alias END" - " FROM tabpk t, idx i" - ")" - - ", numbered(ii, cond, e) AS (" - " SELECT 0, 'n.ii=0', 'NULL'" - " UNION ALL " - " SELECT row_number() OVER ()," - " '(n.ii='||row_number() OVER ()||COALESCE(' AND '||p||')', ')'), e" - " FROM expr" - ")" - - ", counter_with(w) AS (" - " SELECT 'WITH intck_counter(ii) AS (\n ' || " - " group_concat('SELECT '||ii, ' UNION ALL\n ') " - " || '\n)' FROM numbered" - ")" - "" - ", case_statement(c) AS (" - " SELECT 'CASE ' || " - " group_concat(format('\n WHEN %%s THEN (%%s)', cond, e), '') ||" - " '\nEND AS error_message'" - " FROM numbered" - ")" - "" - - /* This table contains a single row consisting of a single value - - ** the text of an SQL expression that may be used by the main SQL - ** statement to output an SQL literal that can be used to resume - ** the scan if it is suspended. e.g. for a rowid table, an expression - ** like: - ** - ** format('(%d,%d)', _rowid_, n.ii) - */ - ", thiskey(k, n) AS (" - " SELECT o_pk || ', ii', n_pk+1 FROM tabpk" - ")" - "" - ", whereclause(w_c) AS (" - " SELECT CASE WHEN prev!='' THEN " - " '\nWHERE (' || o_pk ||', n.ii) > ' || prev" - " ELSE ''" - " END" - " FROM tabpk, tabname" - ")" - "" - ", main_select(m, n) AS (" - " SELECT format(" - " '%%s, %%s\nSELECT %%s,\n%%s\nFROM intck_wrapper AS o" - ", intck_counter AS n%%s\nORDER BY %%s', " - " w, ww.s, c, thiskey.k, whereclause.w_c, t.o_pk" - " ), thiskey.n" - " FROM case_statement, tabpk t, counter_with, " - " wrapper_with ww, thiskey, whereclause" - ")" - - "SELECT m, n FROM main_select", - p->zDb, zObj, zPrev, zCommon - ); - } - - while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ - zRet = intckMprintf(p, "%s", (const char*)sqlite3_column_text(pStmt, 0)); - if( pnKeyVal ){ - *pnKeyVal = sqlite3_column_int(pStmt, 1); - } - } - intckFinalize(p, pStmt); - - if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 1"); - return zRet; -} - -/* -** Open a new integrity-check object. -*/ -int sqlite3_intck_open( - sqlite3 *db, /* Database handle to operate on */ - const char *zDbArg, /* "main", "temp" etc. */ - sqlite3_intck **ppOut /* OUT: New integrity-check handle */ -){ - sqlite3_intck *pNew = 0; - int rc = SQLITE_OK; - const char *zDb = zDbArg ? zDbArg : "main"; - int nDb = (int)strlen(zDb); - - pNew = (sqlite3_intck*)sqlite3_malloc(sizeof(*pNew) + nDb + 1); - if( pNew==0 ){ - rc = SQLITE_NOMEM; - }else{ - memset(pNew, 0, sizeof(*pNew)); - pNew->db = db; - pNew->zDb = (const char*)&pNew[1]; - memcpy(&pNew[1], zDb, nDb+1); - rc = sqlite3_create_function(db, "parse_create_index", - 2, SQLITE_UTF8, 0, intckParseCreateIndexFunc, 0, 0 - ); - if( rc!=SQLITE_OK ){ - sqlite3_intck_close(pNew); - pNew = 0; - } - } - - *ppOut = pNew; - return rc; -} - -/* -** Free the integrity-check object. -*/ -void sqlite3_intck_close(sqlite3_intck *p){ - if( p ){ - sqlite3_finalize(p->pCheck); - sqlite3_create_function( - p->db, "parse_create_index", 1, SQLITE_UTF8, 0, 0, 0, 0 - ); - sqlite3_free(p->zObj); - sqlite3_free(p->zKey); - sqlite3_free(p->zTestSql); - sqlite3_free(p->zErr); - sqlite3_free(p->zMessage); - sqlite3_free(p); - } -} - -/* -** Step the integrity-check object. -*/ -int sqlite3_intck_step(sqlite3_intck *p){ - if( p->rc==SQLITE_OK ){ - - if( p->zMessage ){ - sqlite3_free(p->zMessage); - p->zMessage = 0; - } - - if( p->bCorruptSchema ){ - p->rc = SQLITE_DONE; - }else - if( p->pCheck==0 ){ - intckFindObject(p); - if( p->rc==SQLITE_OK ){ - if( p->zObj ){ - char *zSql = 0; - zSql = intckCheckObjectSql(p, p->zObj, p->zKey, &p->nKeyVal); - p->pCheck = intckPrepare(p, zSql); - sqlite3_free(zSql); - sqlite3_free(p->zKey); - p->zKey = 0; - }else{ - p->rc = SQLITE_DONE; - } - }else if( p->rc==SQLITE_CORRUPT ){ - p->rc = SQLITE_OK; - p->zMessage = intckMprintf(p, "%s", - "corruption found while reading database schema" - ); - p->bCorruptSchema = 1; - } - } - - if( p->pCheck ){ - assert( p->rc==SQLITE_OK ); - if( sqlite3_step(p->pCheck)==SQLITE_ROW ){ - /* Normal case, do nothing. */ - }else{ - intckFinalize(p, p->pCheck); - p->pCheck = 0; - p->nKeyVal = 0; - if( p->rc==SQLITE_CORRUPT ){ - p->rc = SQLITE_OK; - p->zMessage = intckMprintf(p, - "corruption found while scanning database object %s", p->zObj - ); - } - } - } - } - - return p->rc; -} - -/* -** Return a message describing the corruption encountered by the most recent -** call to sqlite3_intck_step(), or NULL if no corruption was encountered. -*/ -const char *sqlite3_intck_message(sqlite3_intck *p){ - assert( p->pCheck==0 || p->zMessage==0 ); - if( p->zMessage ){ - return p->zMessage; - } - if( p->pCheck ){ - return (const char*)sqlite3_column_text(p->pCheck, 0); - } - return 0; -} - -/* -** Return the error code and message. -*/ -int sqlite3_intck_error(sqlite3_intck *p, const char **pzErr){ - if( pzErr ) *pzErr = p->zErr; - return (p->rc==SQLITE_DONE ? SQLITE_OK : p->rc); -} - -/* -** Close any read transaction the integrity-check object is holding open -** on the database. -*/ -int sqlite3_intck_unlock(sqlite3_intck *p){ - if( p->rc==SQLITE_OK && p->pCheck ){ - assert( p->zKey==0 && p->nKeyVal>0 ); - intckSaveKey(p); - intckFinalize(p, p->pCheck); - p->pCheck = 0; - } - return p->rc; -} - -/* -** Return the SQL statement used to check object zObj. Or, if zObj is -** NULL, the current SQL statement. -*/ -const char *sqlite3_intck_test_sql(sqlite3_intck *p, const char *zObj){ - sqlite3_free(p->zTestSql); - if( zObj ){ - p->zTestSql = intckCheckObjectSql(p, zObj, 0, 0); - }else{ - if( p->zObj ){ - p->zTestSql = intckCheckObjectSql(p, p->zObj, p->zKey, 0); - }else{ - sqlite3_free(p->zTestSql); - p->zTestSql = 0; - } - } - return p->zTestSql; -} - -/************************* End ../ext/intck/sqlite3intck.c ********************/ -/************************* Begin ../ext/misc/stmtrand.c ******************/ -/* -** 2024-05-24 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** An SQL function that return pseudo-random non-negative integers. -** -** SELECT stmtrand(123); -** -** A special feature of this function is that the same sequence of random -** integers is returned for each invocation of the statement. This makes -** the results repeatable, and hence useful for testing. The argument is -** an integer which is the seed for the random number sequence. The seed -** is used by the first invocation of this function only and is ignored -** for all subsequent calls within the same statement. -** -** Resetting a statement (sqlite3_reset()) also resets the random number -** sequence. -*/ -/* #include "sqlite3ext.h" */ -SQLITE_EXTENSION_INIT1 -#include -#include - -/* State of the pseudo-random number generator */ -typedef struct Stmtrand { - unsigned int x, y; -} Stmtrand; - -/* auxdata key */ -#define STMTRAND_KEY (-4418371) - -/* -** Function: stmtrand(SEED) -** -** Return a pseudo-random number. -*/ -static void stmtrandFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Stmtrand *p; - - p = (Stmtrand*)sqlite3_get_auxdata(context, STMTRAND_KEY); - if( p==0 ){ - unsigned int seed; - p = sqlite3_malloc( sizeof(*p) ); - if( p==0 ){ - sqlite3_result_error_nomem(context); - return; - } - if( argc>=1 ){ - seed = (unsigned int)sqlite3_value_int(argv[0]); - }else{ - seed = 0; - } - p->x = seed | 1; - p->y = seed; - sqlite3_set_auxdata(context, STMTRAND_KEY, p, sqlite3_free); - p = (Stmtrand*)sqlite3_get_auxdata(context, STMTRAND_KEY); - if( p==0 ){ - sqlite3_result_error_nomem(context); - return; - } - } - p->x = (p->x>>1) ^ ((1+~(p->x&1)) & 0xd0000001); - p->y = p->y*1103515245 + 12345; - sqlite3_result_int(context, (int)((p->x ^ p->y)&0x7fffffff)); -} - -#ifdef _WIN32 - -#endif -int sqlite3_stmtrand_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - int rc = SQLITE_OK; - SQLITE_EXTENSION_INIT2(pApi); - (void)pzErrMsg; /* Unused parameter */ - rc = sqlite3_create_function(db, "stmtrand", 1, SQLITE_UTF8, 0, - stmtrandFunc, 0, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "stmtrand", 0, SQLITE_UTF8, 0, - stmtrandFunc, 0, 0); - } - return rc; -} - -/************************* End ../ext/misc/stmtrand.c ********************/ -/************************* Begin ../ext/misc/vfstrace.c ******************/ -/* -** 2011 March 16 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains code implements a VFS shim that writes diagnostic -** output for each VFS call, similar to "strace". -** -** USAGE: -** -** This source file exports a single symbol which is the name of a -** function: -** -** int vfstrace_register( -** const char *zTraceName, // Name of the newly constructed VFS -** const char *zOldVfsName, // Name of the underlying VFS -** int (*xOut)(const char*,void*), // Output routine. ex: fputs -** void *pOutArg, // 2nd argument to xOut. ex: stderr -** int makeDefault // Make the new VFS the default -** ); -** -** Applications that want to trace their VFS usage must provide a callback -** function with this prototype: -** -** int traceOutput(const char *zMessage, void *pAppData); -** -** This function will "output" the trace messages, where "output" can -** mean different things to different applications. The traceOutput function -** for the command-line shell (see shell.c) is "fputs" from the standard -** library, which means that all trace output is written on the stream -** specified by the second argument. In the case of the command-line shell -** the second argument is stderr. Other applications might choose to output -** trace information to a file, over a socket, or write it into a buffer. -** -** The vfstrace_register() function creates a new "shim" VFS named by -** the zTraceName parameter. A "shim" VFS is an SQLite backend that does -** not really perform the duties of a true backend, but simply filters or -** interprets VFS calls before passing them off to another VFS which does -** the actual work. In this case the other VFS - the one that does the -** real work - is identified by the second parameter, zOldVfsName. If -** the 2nd parameter is NULL then the default VFS is used. The common -** case is for the 2nd parameter to be NULL. -** -** The third and fourth parameters are the pointer to the output function -** and the second argument to the output function. For the SQLite -** command-line shell, when the -vfstrace option is used, these parameters -** are fputs and stderr, respectively. -** -** The fifth argument is true (non-zero) to cause the newly created VFS -** to become the default VFS. The common case is for the fifth parameter -** to be true. -** -** The call to vfstrace_register() simply creates the shim VFS that does -** tracing. The application must also arrange to use the new VFS for -** all database connections that are created and for which tracing is -** desired. This can be done by specifying the trace VFS using URI filename -** notation, or by specifying the trace VFS as the 4th parameter to -** sqlite3_open_v2() or by making the trace VFS be the default (by setting -** the 5th parameter of vfstrace_register() to 1). -** -** -** ENABLING VFSTRACE IN A COMMAND-LINE SHELL -** -** The SQLite command line shell implemented by the shell.c source file -** can be used with this module. To compile in -vfstrace support, first -** gather this file (test_vfstrace.c), the shell source file (shell.c), -** and the SQLite amalgamation source files (sqlite3.c, sqlite3.h) into -** the working directory. Then compile using a command like the following: -** -** gcc -o sqlite3 -Os -I. -DSQLITE_ENABLE_VFSTRACE \ -** -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_RTREE \ -** -DHAVE_READLINE -DHAVE_USLEEP=1 \ -** shell.c test_vfstrace.c sqlite3.c -ldl -lreadline -lncurses -** -** The gcc command above works on Linux and provides (in addition to the -** -vfstrace option) support for FTS3 and FTS4, RTREE, and command-line -** editing using the readline library. The command-line shell does not -** use threads so we added -DSQLITE_THREADSAFE=0 just to make the code -** run a little faster. For compiling on a Mac, you'll probably need -** to omit the -DHAVE_READLINE, the -lreadline, and the -lncurses options. -** The compilation could be simplified to just this: -** -** gcc -DSQLITE_ENABLE_VFSTRACE \ -** shell.c test_vfstrace.c sqlite3.c -ldl -lpthread -** -** In this second example, all unnecessary options have been removed -** Note that since the code is now threadsafe, we had to add the -lpthread -** option to pull in the pthreads library. -** -** To cross-compile for windows using MinGW, a command like this might -** work: -** -** /opt/mingw/bin/i386-mingw32msvc-gcc -o sqlite3.exe -Os -I \ -** -DSQLITE_THREADSAFE=0 -DSQLITE_ENABLE_VFSTRACE \ -** shell.c test_vfstrace.c sqlite3.c -** -** Similar compiler commands will work on different systems. The key -** invariants are (1) you must have -DSQLITE_ENABLE_VFSTRACE so that -** the shell.c source file will know to include the -vfstrace command-line -** option and (2) you must compile and link the three source files -** shell,c, test_vfstrace.c, and sqlite3.c. -*/ -#include -#include -/* #include "sqlite3.h" */ - -/* -** An instance of this structure is attached to the each trace VFS to -** provide auxiliary information. -*/ -typedef struct vfstrace_info vfstrace_info; -struct vfstrace_info { - sqlite3_vfs *pRootVfs; /* The underlying real VFS */ - int (*xOut)(const char*, void*); /* Send output here */ - void *pOutArg; /* First argument to xOut */ - const char *zVfsName; /* Name of this trace-VFS */ - sqlite3_vfs *pTraceVfs; /* Pointer back to the trace VFS */ -}; - -/* -** The sqlite3_file object for the trace VFS -*/ -typedef struct vfstrace_file vfstrace_file; -struct vfstrace_file { - sqlite3_file base; /* Base class. Must be first */ - vfstrace_info *pInfo; /* The trace-VFS to which this file belongs */ - const char *zFName; /* Base name of the file */ - sqlite3_file *pReal; /* The real underlying file */ -}; - -/* -** Method declarations for vfstrace_file. -*/ -static int vfstraceClose(sqlite3_file*); -static int vfstraceRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); -static int vfstraceWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64); -static int vfstraceTruncate(sqlite3_file*, sqlite3_int64 size); -static int vfstraceSync(sqlite3_file*, int flags); -static int vfstraceFileSize(sqlite3_file*, sqlite3_int64 *pSize); -static int vfstraceLock(sqlite3_file*, int); -static int vfstraceUnlock(sqlite3_file*, int); -static int vfstraceCheckReservedLock(sqlite3_file*, int *); -static int vfstraceFileControl(sqlite3_file*, int op, void *pArg); -static int vfstraceSectorSize(sqlite3_file*); -static int vfstraceDeviceCharacteristics(sqlite3_file*); -static int vfstraceShmLock(sqlite3_file*,int,int,int); -static int vfstraceShmMap(sqlite3_file*,int,int,int, void volatile **); -static void vfstraceShmBarrier(sqlite3_file*); -static int vfstraceShmUnmap(sqlite3_file*,int); - -/* -** Method declarations for vfstrace_vfs. -*/ -static int vfstraceOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *); -static int vfstraceDelete(sqlite3_vfs*, const char *zName, int syncDir); -static int vfstraceAccess(sqlite3_vfs*, const char *zName, int flags, int *); -static int vfstraceFullPathname(sqlite3_vfs*, const char *zName, int, char *); -static void *vfstraceDlOpen(sqlite3_vfs*, const char *zFilename); -static void vfstraceDlError(sqlite3_vfs*, int nByte, char *zErrMsg); -static void (*vfstraceDlSym(sqlite3_vfs*,void*, const char *zSymbol))(void); -static void vfstraceDlClose(sqlite3_vfs*, void*); -static int vfstraceRandomness(sqlite3_vfs*, int nByte, char *zOut); -static int vfstraceSleep(sqlite3_vfs*, int microseconds); -static int vfstraceCurrentTime(sqlite3_vfs*, double*); -static int vfstraceGetLastError(sqlite3_vfs*, int, char*); -static int vfstraceCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*); -static int vfstraceSetSystemCall(sqlite3_vfs*,const char*, sqlite3_syscall_ptr); -static sqlite3_syscall_ptr vfstraceGetSystemCall(sqlite3_vfs*, const char *); -static const char *vfstraceNextSystemCall(sqlite3_vfs*, const char *zName); - -/* -** Return a pointer to the tail of the pathname. Examples: -** -** /home/drh/xyzzy.txt -> xyzzy.txt -** xyzzy.txt -> xyzzy.txt -*/ -static const char *fileTail(const char *z){ - size_t i; - if( z==0 ) return 0; - i = strlen(z)-1; - while( i>0 && z[i-1]!='/' ){ i--; } - return &z[i]; -} - -/* -** Send trace output defined by zFormat and subsequent arguments. -*/ -static void vfstrace_printf( - vfstrace_info *pInfo, - const char *zFormat, - ... -){ - va_list ap; - char *zMsg; - va_start(ap, zFormat); - zMsg = sqlite3_vmprintf(zFormat, ap); - va_end(ap); - pInfo->xOut(zMsg, pInfo->pOutArg); - sqlite3_free(zMsg); -} - -/* -** Try to convert an error code into a symbolic name for that error code. -*/ -static const char *vfstrace_errcode_name(int rc ){ - const char *zVal = 0; - switch( rc ){ - case SQLITE_OK: zVal = "SQLITE_OK"; break; - case SQLITE_INTERNAL: zVal = "SQLITE_INTERNAL"; break; - case SQLITE_ERROR: zVal = "SQLITE_ERROR"; break; - case SQLITE_PERM: zVal = "SQLITE_PERM"; break; - case SQLITE_ABORT: zVal = "SQLITE_ABORT"; break; - case SQLITE_BUSY: zVal = "SQLITE_BUSY"; break; - case SQLITE_LOCKED: zVal = "SQLITE_LOCKED"; break; - case SQLITE_NOMEM: zVal = "SQLITE_NOMEM"; break; - case SQLITE_READONLY: zVal = "SQLITE_READONLY"; break; - case SQLITE_INTERRUPT: zVal = "SQLITE_INTERRUPT"; break; - case SQLITE_IOERR: zVal = "SQLITE_IOERR"; break; - case SQLITE_CORRUPT: zVal = "SQLITE_CORRUPT"; break; - case SQLITE_NOTFOUND: zVal = "SQLITE_NOTFOUND"; break; - case SQLITE_FULL: zVal = "SQLITE_FULL"; break; - case SQLITE_CANTOPEN: zVal = "SQLITE_CANTOPEN"; break; - case SQLITE_PROTOCOL: zVal = "SQLITE_PROTOCOL"; break; - case SQLITE_EMPTY: zVal = "SQLITE_EMPTY"; break; - case SQLITE_SCHEMA: zVal = "SQLITE_SCHEMA"; break; - case SQLITE_TOOBIG: zVal = "SQLITE_TOOBIG"; break; - case SQLITE_CONSTRAINT: zVal = "SQLITE_CONSTRAINT"; break; - case SQLITE_MISMATCH: zVal = "SQLITE_MISMATCH"; break; - case SQLITE_MISUSE: zVal = "SQLITE_MISUSE"; break; - case SQLITE_NOLFS: zVal = "SQLITE_NOLFS"; break; - case SQLITE_IOERR_READ: zVal = "SQLITE_IOERR_READ"; break; - case SQLITE_IOERR_SHORT_READ: zVal = "SQLITE_IOERR_SHORT_READ"; break; - case SQLITE_IOERR_WRITE: zVal = "SQLITE_IOERR_WRITE"; break; - case SQLITE_IOERR_FSYNC: zVal = "SQLITE_IOERR_FSYNC"; break; - case SQLITE_IOERR_DIR_FSYNC: zVal = "SQLITE_IOERR_DIR_FSYNC"; break; - case SQLITE_IOERR_TRUNCATE: zVal = "SQLITE_IOERR_TRUNCATE"; break; - case SQLITE_IOERR_FSTAT: zVal = "SQLITE_IOERR_FSTAT"; break; - case SQLITE_IOERR_UNLOCK: zVal = "SQLITE_IOERR_UNLOCK"; break; - case SQLITE_IOERR_RDLOCK: zVal = "SQLITE_IOERR_RDLOCK"; break; - case SQLITE_IOERR_DELETE: zVal = "SQLITE_IOERR_DELETE"; break; - case SQLITE_IOERR_BLOCKED: zVal = "SQLITE_IOERR_BLOCKED"; break; - case SQLITE_IOERR_NOMEM: zVal = "SQLITE_IOERR_NOMEM"; break; - case SQLITE_IOERR_ACCESS: zVal = "SQLITE_IOERR_ACCESS"; break; - case SQLITE_IOERR_CHECKRESERVEDLOCK: - zVal = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break; - case SQLITE_IOERR_LOCK: zVal = "SQLITE_IOERR_LOCK"; break; - case SQLITE_IOERR_CLOSE: zVal = "SQLITE_IOERR_CLOSE"; break; - case SQLITE_IOERR_DIR_CLOSE: zVal = "SQLITE_IOERR_DIR_CLOSE"; break; - case SQLITE_IOERR_SHMOPEN: zVal = "SQLITE_IOERR_SHMOPEN"; break; - case SQLITE_IOERR_SHMSIZE: zVal = "SQLITE_IOERR_SHMSIZE"; break; - case SQLITE_IOERR_SHMLOCK: zVal = "SQLITE_IOERR_SHMLOCK"; break; - case SQLITE_IOERR_SHMMAP: zVal = "SQLITE_IOERR_SHMMAP"; break; - case SQLITE_IOERR_SEEK: zVal = "SQLITE_IOERR_SEEK"; break; - case SQLITE_IOERR_GETTEMPPATH: zVal = "SQLITE_IOERR_GETTEMPPATH"; break; - case SQLITE_IOERR_CONVPATH: zVal = "SQLITE_IOERR_CONVPATH"; break; - case SQLITE_READONLY_DBMOVED: zVal = "SQLITE_READONLY_DBMOVED"; break; - case SQLITE_LOCKED_SHAREDCACHE: zVal = "SQLITE_LOCKED_SHAREDCACHE"; break; - case SQLITE_BUSY_RECOVERY: zVal = "SQLITE_BUSY_RECOVERY"; break; - case SQLITE_CANTOPEN_NOTEMPDIR: zVal = "SQLITE_CANTOPEN_NOTEMPDIR"; break; - } - return zVal; -} - -/* -** Convert value rc into a string and print it using zFormat. zFormat -** should have exactly one %s -*/ -static void vfstrace_print_errcode( - vfstrace_info *pInfo, - const char *zFormat, - int rc -){ - const char *zVal; - char zBuf[50]; - zVal = vfstrace_errcode_name(rc); - if( zVal==0 ){ - zVal = vfstrace_errcode_name(rc&0xff); - if( zVal ){ - sqlite3_snprintf(sizeof(zBuf), zBuf, "%s | 0x%x", zVal, rc&0xffff00); - }else{ - sqlite3_snprintf(sizeof(zBuf), zBuf, "%d (0x%x)", rc, rc); - } - zVal = zBuf; - } - vfstrace_printf(pInfo, zFormat, zVal); -} - -/* -** Append to a buffer. -*/ -static void strappend(char *z, int *pI, const char *zAppend){ - int i = *pI; - while( zAppend[0] ){ z[i++] = *(zAppend++); } - z[i] = 0; - *pI = i; -} - -/* -** Close an vfstrace-file. -*/ -static int vfstraceClose(sqlite3_file *pFile){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - vfstrace_printf(pInfo, "%s.xClose(%s)", pInfo->zVfsName, p->zFName); - rc = p->pReal->pMethods->xClose(p->pReal); - vfstrace_print_errcode(pInfo, " -> %s\n", rc); - if( rc==SQLITE_OK ){ - sqlite3_free((void*)p->base.pMethods); - p->base.pMethods = 0; - } - return rc; -} - -/* -** Read data from an vfstrace-file. -*/ -static int vfstraceRead( - sqlite3_file *pFile, - void *zBuf, - int iAmt, - sqlite_int64 iOfst -){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - vfstrace_printf(pInfo, "%s.xRead(%s,n=%d,ofst=%lld)", - pInfo->zVfsName, p->zFName, iAmt, iOfst); - rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst); - vfstrace_print_errcode(pInfo, " -> %s\n", rc); - return rc; -} - -/* -** Write data to an vfstrace-file. -*/ -static int vfstraceWrite( - sqlite3_file *pFile, - const void *zBuf, - int iAmt, - sqlite_int64 iOfst -){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - vfstrace_printf(pInfo, "%s.xWrite(%s,n=%d,ofst=%lld)", - pInfo->zVfsName, p->zFName, iAmt, iOfst); - rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst); - vfstrace_print_errcode(pInfo, " -> %s\n", rc); - return rc; -} - -/* -** Truncate an vfstrace-file. -*/ -static int vfstraceTruncate(sqlite3_file *pFile, sqlite_int64 size){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - vfstrace_printf(pInfo, "%s.xTruncate(%s,%lld)", pInfo->zVfsName, p->zFName, - size); - rc = p->pReal->pMethods->xTruncate(p->pReal, size); - vfstrace_printf(pInfo, " -> %d\n", rc); - return rc; -} - -/* -** Sync an vfstrace-file. -*/ -static int vfstraceSync(sqlite3_file *pFile, int flags){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - int i; - char zBuf[100]; - memcpy(zBuf, "|0", 3); - i = 0; - if( flags & SQLITE_SYNC_FULL ) strappend(zBuf, &i, "|FULL"); - else if( flags & SQLITE_SYNC_NORMAL ) strappend(zBuf, &i, "|NORMAL"); - if( flags & SQLITE_SYNC_DATAONLY ) strappend(zBuf, &i, "|DATAONLY"); - if( flags & ~(SQLITE_SYNC_FULL|SQLITE_SYNC_DATAONLY) ){ - sqlite3_snprintf(sizeof(zBuf)-i, &zBuf[i], "|0x%x", flags); - } - vfstrace_printf(pInfo, "%s.xSync(%s,%s)", pInfo->zVfsName, p->zFName, - &zBuf[1]); - rc = p->pReal->pMethods->xSync(p->pReal, flags); - vfstrace_printf(pInfo, " -> %d\n", rc); - return rc; -} - -/* -** Return the current file-size of an vfstrace-file. -*/ -static int vfstraceFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - vfstrace_printf(pInfo, "%s.xFileSize(%s)", pInfo->zVfsName, p->zFName); - rc = p->pReal->pMethods->xFileSize(p->pReal, pSize); - vfstrace_print_errcode(pInfo, " -> %s,", rc); - vfstrace_printf(pInfo, " size=%lld\n", *pSize); - return rc; -} - -/* -** Return the name of a lock. -*/ -static const char *lockName(int eLock){ - const char *azLockNames[] = { - "NONE", "SHARED", "RESERVED", "PENDING", "EXCLUSIVE" - }; - if( eLock<0 || eLock>=(int)(sizeof(azLockNames)/sizeof(azLockNames[0])) ){ - return "???"; - }else{ - return azLockNames[eLock]; - } -} - -/* -** Lock an vfstrace-file. -*/ -static int vfstraceLock(sqlite3_file *pFile, int eLock){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - vfstrace_printf(pInfo, "%s.xLock(%s,%s)", pInfo->zVfsName, p->zFName, - lockName(eLock)); - rc = p->pReal->pMethods->xLock(p->pReal, eLock); - vfstrace_print_errcode(pInfo, " -> %s\n", rc); - return rc; -} - -/* -** Unlock an vfstrace-file. -*/ -static int vfstraceUnlock(sqlite3_file *pFile, int eLock){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - vfstrace_printf(pInfo, "%s.xUnlock(%s,%s)", pInfo->zVfsName, p->zFName, - lockName(eLock)); - rc = p->pReal->pMethods->xUnlock(p->pReal, eLock); - vfstrace_print_errcode(pInfo, " -> %s\n", rc); - return rc; -} - -/* -** Check if another file-handle holds a RESERVED lock on an vfstrace-file. -*/ -static int vfstraceCheckReservedLock(sqlite3_file *pFile, int *pResOut){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - vfstrace_printf(pInfo, "%s.xCheckReservedLock(%s,%d)", - pInfo->zVfsName, p->zFName); - rc = p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut); - vfstrace_print_errcode(pInfo, " -> %s", rc); - vfstrace_printf(pInfo, ", out=%d\n", *pResOut); - return rc; -} - -/* -** File control method. For custom operations on an vfstrace-file. -*/ -static int vfstraceFileControl(sqlite3_file *pFile, int op, void *pArg){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - char zBuf[100]; - char zBuf2[100]; - char *zOp; - char *zRVal = 0; - switch( op ){ - case SQLITE_FCNTL_LOCKSTATE: zOp = "LOCKSTATE"; break; - case SQLITE_GET_LOCKPROXYFILE: zOp = "GET_LOCKPROXYFILE"; break; - case SQLITE_SET_LOCKPROXYFILE: zOp = "SET_LOCKPROXYFILE"; break; - case SQLITE_LAST_ERRNO: zOp = "LAST_ERRNO"; break; - case SQLITE_FCNTL_SIZE_HINT: { - sqlite3_snprintf(sizeof(zBuf), zBuf, "SIZE_HINT,%lld", - *(sqlite3_int64*)pArg); - zOp = zBuf; - break; - } - case SQLITE_FCNTL_CHUNK_SIZE: { - sqlite3_snprintf(sizeof(zBuf), zBuf, "CHUNK_SIZE,%d", *(int*)pArg); - zOp = zBuf; - break; - } - case SQLITE_FCNTL_FILE_POINTER: zOp = "FILE_POINTER"; break; - case SQLITE_FCNTL_WIN32_AV_RETRY: zOp = "WIN32_AV_RETRY"; break; - case SQLITE_FCNTL_PERSIST_WAL: { - sqlite3_snprintf(sizeof(zBuf), zBuf, "PERSIST_WAL,%d", *(int*)pArg); - zOp = zBuf; - break; - } - case SQLITE_FCNTL_OVERWRITE: zOp = "OVERWRITE"; break; - case SQLITE_FCNTL_VFSNAME: zOp = "VFSNAME"; break; - case SQLITE_FCNTL_POWERSAFE_OVERWRITE: zOp = "POWERSAFE_OVERWRITE"; break; - case SQLITE_FCNTL_PRAGMA: { - const char *const* a = (const char*const*)pArg; - sqlite3_snprintf(sizeof(zBuf), zBuf, "PRAGMA,[%s,%s]",a[1],a[2]); - zOp = zBuf; - break; - } - case SQLITE_FCNTL_BUSYHANDLER: zOp = "BUSYHANDLER"; break; - case SQLITE_FCNTL_TEMPFILENAME: zOp = "TEMPFILENAME"; break; - case SQLITE_FCNTL_MMAP_SIZE: { - sqlite3_int64 iMMap = *(sqlite3_int64*)pArg; - sqlite3_snprintf(sizeof(zBuf), zBuf, "MMAP_SIZE,%lld",iMMap); - zOp = zBuf; - break; - } - case SQLITE_FCNTL_TRACE: zOp = "TRACE"; break; - case SQLITE_FCNTL_HAS_MOVED: zOp = "HAS_MOVED"; break; - case SQLITE_FCNTL_SYNC: zOp = "SYNC"; break; - case SQLITE_FCNTL_COMMIT_PHASETWO: zOp = "COMMIT_PHASETWO"; break; - case SQLITE_FCNTL_WIN32_SET_HANDLE: zOp = "WIN32_SET_HANDLE"; break; - case SQLITE_FCNTL_WAL_BLOCK: zOp = "WAL_BLOCK"; break; - case SQLITE_FCNTL_ZIPVFS: zOp = "ZIPVFS"; break; - case SQLITE_FCNTL_RBU: zOp = "RBU"; break; - case SQLITE_FCNTL_VFS_POINTER: zOp = "VFS_POINTER"; break; - case SQLITE_FCNTL_JOURNAL_POINTER: zOp = "JOURNAL_POINTER"; break; - case SQLITE_FCNTL_WIN32_GET_HANDLE: zOp = "WIN32_GET_HANDLE"; break; - case SQLITE_FCNTL_PDB: zOp = "PDB"; break; - case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: zOp = "BEGIN_ATOMIC_WRITE"; break; - case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: zOp = "COMMIT_ATOMIC_WRITE"; break; - case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: { - zOp = "ROLLBACK_ATOMIC_WRITE"; - break; - } - case SQLITE_FCNTL_LOCK_TIMEOUT: { - sqlite3_snprintf(sizeof(zBuf), zBuf, "LOCK_TIMEOUT,%d", *(int*)pArg); - zOp = zBuf; - break; - } - case SQLITE_FCNTL_DATA_VERSION: zOp = "DATA_VERSION"; break; - case SQLITE_FCNTL_SIZE_LIMIT: zOp = "SIZE_LIMIT"; break; - case SQLITE_FCNTL_CKPT_DONE: zOp = "CKPT_DONE"; break; - case SQLITE_FCNTL_RESERVE_BYTES: zOp = "RESERVED_BYTES"; break; - case SQLITE_FCNTL_CKPT_START: zOp = "CKPT_START"; break; - case SQLITE_FCNTL_EXTERNAL_READER: zOp = "EXTERNAL_READER"; break; - case SQLITE_FCNTL_CKSM_FILE: zOp = "CKSM_FILE"; break; - case SQLITE_FCNTL_RESET_CACHE: zOp = "RESET_CACHE"; break; - case 0xca093fa0: zOp = "DB_UNCHANGED"; break; - default: { - sqlite3_snprintf(sizeof zBuf, zBuf, "%d", op); - zOp = zBuf; - break; - } - } - vfstrace_printf(pInfo, "%s.xFileControl(%s,%s)", - pInfo->zVfsName, p->zFName, zOp); - rc = p->pReal->pMethods->xFileControl(p->pReal, op, pArg); - if( rc==SQLITE_OK ){ - switch( op ){ - case SQLITE_FCNTL_VFSNAME: { - *(char**)pArg = sqlite3_mprintf("vfstrace.%s/%z", - pInfo->zVfsName, *(char**)pArg); - zRVal = *(char**)pArg; - break; - } - case SQLITE_FCNTL_MMAP_SIZE: { - sqlite3_snprintf(sizeof(zBuf2), zBuf2, "%lld", *(sqlite3_int64*)pArg); - zRVal = zBuf2; - break; - } - case SQLITE_FCNTL_HAS_MOVED: - case SQLITE_FCNTL_PERSIST_WAL: { - sqlite3_snprintf(sizeof(zBuf2), zBuf2, "%d", *(int*)pArg); - zRVal = zBuf2; - break; - } - case SQLITE_FCNTL_PRAGMA: - case SQLITE_FCNTL_TEMPFILENAME: { - zRVal = *(char**)pArg; - break; - } - } - } - if( zRVal ){ - vfstrace_print_errcode(pInfo, " -> %s", rc); - vfstrace_printf(pInfo, ", %s\n", zRVal); - }else{ - vfstrace_print_errcode(pInfo, " -> %s\n", rc); - } - return rc; -} - -/* -** Return the sector-size in bytes for an vfstrace-file. -*/ -static int vfstraceSectorSize(sqlite3_file *pFile){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - vfstrace_printf(pInfo, "%s.xSectorSize(%s)", pInfo->zVfsName, p->zFName); - rc = p->pReal->pMethods->xSectorSize(p->pReal); - vfstrace_printf(pInfo, " -> %d\n", rc); - return rc; -} - -/* -** Return the device characteristic flags supported by an vfstrace-file. -*/ -static int vfstraceDeviceCharacteristics(sqlite3_file *pFile){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - vfstrace_printf(pInfo, "%s.xDeviceCharacteristics(%s)", - pInfo->zVfsName, p->zFName); - rc = p->pReal->pMethods->xDeviceCharacteristics(p->pReal); - vfstrace_printf(pInfo, " -> 0x%08x\n", rc); - return rc; -} - -/* -** Shared-memory operations. -*/ -static int vfstraceShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - char zLck[100]; - int i = 0; - memcpy(zLck, "|0", 3); - if( flags & SQLITE_SHM_UNLOCK ) strappend(zLck, &i, "|UNLOCK"); - if( flags & SQLITE_SHM_LOCK ) strappend(zLck, &i, "|LOCK"); - if( flags & SQLITE_SHM_SHARED ) strappend(zLck, &i, "|SHARED"); - if( flags & SQLITE_SHM_EXCLUSIVE ) strappend(zLck, &i, "|EXCLUSIVE"); - if( flags & ~(0xf) ){ - sqlite3_snprintf(sizeof(zLck)-i, &zLck[i], "|0x%x", flags); - } - vfstrace_printf(pInfo, "%s.xShmLock(%s,ofst=%d,n=%d,%s)", - pInfo->zVfsName, p->zFName, ofst, n, &zLck[1]); - rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags); - vfstrace_print_errcode(pInfo, " -> %s\n", rc); - return rc; -} -static int vfstraceShmMap( - sqlite3_file *pFile, - int iRegion, - int szRegion, - int isWrite, - void volatile **pp -){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - vfstrace_printf(pInfo, "%s.xShmMap(%s,iRegion=%d,szRegion=%d,isWrite=%d,*)", - pInfo->zVfsName, p->zFName, iRegion, szRegion, isWrite); - rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp); - vfstrace_print_errcode(pInfo, " -> %s\n", rc); - return rc; -} -static void vfstraceShmBarrier(sqlite3_file *pFile){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - vfstrace_printf(pInfo, "%s.xShmBarrier(%s)\n", pInfo->zVfsName, p->zFName); - p->pReal->pMethods->xShmBarrier(p->pReal); -} -static int vfstraceShmUnmap(sqlite3_file *pFile, int delFlag){ - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = p->pInfo; - int rc; - vfstrace_printf(pInfo, "%s.xShmUnmap(%s,delFlag=%d)", - pInfo->zVfsName, p->zFName, delFlag); - rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag); - vfstrace_print_errcode(pInfo, " -> %s\n", rc); - return rc; -} - - - -/* -** Open an vfstrace file handle. -*/ -static int vfstraceOpen( - sqlite3_vfs *pVfs, - const char *zName, - sqlite3_file *pFile, - int flags, - int *pOutFlags -){ - int rc; - vfstrace_file *p = (vfstrace_file *)pFile; - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - p->pInfo = pInfo; - p->zFName = zName ? fileTail(zName) : ""; - p->pReal = (sqlite3_file *)&p[1]; - rc = pRoot->xOpen(pRoot, zName, p->pReal, flags, pOutFlags); - vfstrace_printf(pInfo, "%s.xOpen(%s,flags=0x%x)", - pInfo->zVfsName, p->zFName, flags); - if( p->pReal->pMethods ){ - sqlite3_io_methods *pNew = sqlite3_malloc( sizeof(*pNew) ); - const sqlite3_io_methods *pSub = p->pReal->pMethods; - memset(pNew, 0, sizeof(*pNew)); - pNew->iVersion = pSub->iVersion; - pNew->xClose = vfstraceClose; - pNew->xRead = vfstraceRead; - pNew->xWrite = vfstraceWrite; - pNew->xTruncate = vfstraceTruncate; - pNew->xSync = vfstraceSync; - pNew->xFileSize = vfstraceFileSize; - pNew->xLock = vfstraceLock; - pNew->xUnlock = vfstraceUnlock; - pNew->xCheckReservedLock = vfstraceCheckReservedLock; - pNew->xFileControl = vfstraceFileControl; - pNew->xSectorSize = vfstraceSectorSize; - pNew->xDeviceCharacteristics = vfstraceDeviceCharacteristics; - if( pNew->iVersion>=2 ){ - pNew->xShmMap = pSub->xShmMap ? vfstraceShmMap : 0; - pNew->xShmLock = pSub->xShmLock ? vfstraceShmLock : 0; - pNew->xShmBarrier = pSub->xShmBarrier ? vfstraceShmBarrier : 0; - pNew->xShmUnmap = pSub->xShmUnmap ? vfstraceShmUnmap : 0; - } - pFile->pMethods = pNew; - } - vfstrace_print_errcode(pInfo, " -> %s", rc); - if( pOutFlags ){ - vfstrace_printf(pInfo, ", outFlags=0x%x\n", *pOutFlags); - }else{ - vfstrace_printf(pInfo, "\n"); - } - return rc; -} - -/* -** Delete the file located at zPath. If the dirSync argument is true, -** ensure the file-system modifications are synced to disk before -** returning. -*/ -static int vfstraceDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - int rc; - vfstrace_printf(pInfo, "%s.xDelete(\"%s\",%d)", - pInfo->zVfsName, zPath, dirSync); - rc = pRoot->xDelete(pRoot, zPath, dirSync); - vfstrace_print_errcode(pInfo, " -> %s\n", rc); - return rc; -} - -/* -** Test for access permissions. Return true if the requested permission -** is available, or false otherwise. -*/ -static int vfstraceAccess( - sqlite3_vfs *pVfs, - const char *zPath, - int flags, - int *pResOut -){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - int rc; - vfstrace_printf(pInfo, "%s.xAccess(\"%s\",%d)", - pInfo->zVfsName, zPath, flags); - rc = pRoot->xAccess(pRoot, zPath, flags, pResOut); - vfstrace_print_errcode(pInfo, " -> %s", rc); - vfstrace_printf(pInfo, ", out=%d\n", *pResOut); - return rc; -} - -/* -** Populate buffer zOut with the full canonical pathname corresponding -** to the pathname in zPath. zOut is guaranteed to point to a buffer -** of at least (DEVSYM_MAX_PATHNAME+1) bytes. -*/ -static int vfstraceFullPathname( - sqlite3_vfs *pVfs, - const char *zPath, - int nOut, - char *zOut -){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - int rc; - vfstrace_printf(pInfo, "%s.xFullPathname(\"%s\")", - pInfo->zVfsName, zPath); - rc = pRoot->xFullPathname(pRoot, zPath, nOut, zOut); - vfstrace_print_errcode(pInfo, " -> %s", rc); - vfstrace_printf(pInfo, ", out=\"%.*s\"\n", nOut, zOut); - return rc; -} - -/* -** Open the dynamic library located at zPath and return a handle. -*/ -static void *vfstraceDlOpen(sqlite3_vfs *pVfs, const char *zPath){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - vfstrace_printf(pInfo, "%s.xDlOpen(\"%s\")\n", pInfo->zVfsName, zPath); - return pRoot->xDlOpen(pRoot, zPath); -} - -/* -** Populate the buffer zErrMsg (size nByte bytes) with a human readable -** utf-8 string describing the most recent error encountered associated -** with dynamic libraries. -*/ -static void vfstraceDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - vfstrace_printf(pInfo, "%s.xDlError(%d)", pInfo->zVfsName, nByte); - pRoot->xDlError(pRoot, nByte, zErrMsg); - vfstrace_printf(pInfo, " -> \"%s\"", zErrMsg); -} - -/* -** Return a pointer to the symbol zSymbol in the dynamic library pHandle. -*/ -static void (*vfstraceDlSym(sqlite3_vfs *pVfs,void *p,const char *zSym))(void){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - vfstrace_printf(pInfo, "%s.xDlSym(\"%s\")\n", pInfo->zVfsName, zSym); - return pRoot->xDlSym(pRoot, p, zSym); -} - -/* -** Close the dynamic library handle pHandle. -*/ -static void vfstraceDlClose(sqlite3_vfs *pVfs, void *pHandle){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - vfstrace_printf(pInfo, "%s.xDlOpen()\n", pInfo->zVfsName); - pRoot->xDlClose(pRoot, pHandle); -} - -/* -** Populate the buffer pointed to by zBufOut with nByte bytes of -** random data. -*/ -static int vfstraceRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - vfstrace_printf(pInfo, "%s.xRandomness(%d)\n", pInfo->zVfsName, nByte); - return pRoot->xRandomness(pRoot, nByte, zBufOut); -} - -/* -** Sleep for nMicro microseconds. Return the number of microseconds -** actually slept. -*/ -static int vfstraceSleep(sqlite3_vfs *pVfs, int nMicro){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - return pRoot->xSleep(pRoot, nMicro); -} - -/* -** Return the current time as a Julian Day number in *pTimeOut. -*/ -static int vfstraceCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - return pRoot->xCurrentTime(pRoot, pTimeOut); -} -static int vfstraceCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - return pRoot->xCurrentTimeInt64(pRoot, pTimeOut); -} - -/* -** Return th3 most recent error code and message -*/ -static int vfstraceGetLastError(sqlite3_vfs *pVfs, int iErr, char *zErr){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - return pRoot->xGetLastError(pRoot, iErr, zErr); -} - -/* -** Override system calls. -*/ -static int vfstraceSetSystemCall( - sqlite3_vfs *pVfs, - const char *zName, - sqlite3_syscall_ptr pFunc -){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - return pRoot->xSetSystemCall(pRoot, zName, pFunc); -} -static sqlite3_syscall_ptr vfstraceGetSystemCall( - sqlite3_vfs *pVfs, - const char *zName -){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - return pRoot->xGetSystemCall(pRoot, zName); -} -static const char *vfstraceNextSystemCall(sqlite3_vfs *pVfs, const char *zName){ - vfstrace_info *pInfo = (vfstrace_info*)pVfs->pAppData; - sqlite3_vfs *pRoot = pInfo->pRootVfs; - return pRoot->xNextSystemCall(pRoot, zName); -} - - -/* -** Clients invoke this routine to construct a new trace-vfs shim. -** -** Return SQLITE_OK on success. -** -** SQLITE_NOMEM is returned in the case of a memory allocation error. -** SQLITE_NOTFOUND is returned if zOldVfsName does not exist. -*/ -int vfstrace_register( - const char *zTraceName, /* Name of the newly constructed VFS */ - const char *zOldVfsName, /* Name of the underlying VFS */ - int (*xOut)(const char*,void*), /* Output routine. ex: fputs */ - void *pOutArg, /* 2nd argument to xOut. ex: stderr */ - int makeDefault /* True to make the new VFS the default */ -){ - sqlite3_vfs *pNew; - sqlite3_vfs *pRoot; - vfstrace_info *pInfo; - size_t nName; - size_t nByte; - - pRoot = sqlite3_vfs_find(zOldVfsName); - if( pRoot==0 ) return SQLITE_NOTFOUND; - nName = strlen(zTraceName); - nByte = sizeof(*pNew) + sizeof(*pInfo) + nName + 1; - pNew = sqlite3_malloc64( nByte ); - if( pNew==0 ) return SQLITE_NOMEM; - memset(pNew, 0, nByte); - pInfo = (vfstrace_info*)&pNew[1]; - pNew->iVersion = pRoot->iVersion; - pNew->szOsFile = pRoot->szOsFile + sizeof(vfstrace_file); - pNew->mxPathname = pRoot->mxPathname; - pNew->zName = (char*)&pInfo[1]; - memcpy((char*)&pInfo[1], zTraceName, nName+1); - pNew->pAppData = pInfo; - pNew->xOpen = vfstraceOpen; - pNew->xDelete = vfstraceDelete; - pNew->xAccess = vfstraceAccess; - pNew->xFullPathname = vfstraceFullPathname; - pNew->xDlOpen = pRoot->xDlOpen==0 ? 0 : vfstraceDlOpen; - pNew->xDlError = pRoot->xDlError==0 ? 0 : vfstraceDlError; - pNew->xDlSym = pRoot->xDlSym==0 ? 0 : vfstraceDlSym; - pNew->xDlClose = pRoot->xDlClose==0 ? 0 : vfstraceDlClose; - pNew->xRandomness = vfstraceRandomness; - pNew->xSleep = vfstraceSleep; - pNew->xCurrentTime = vfstraceCurrentTime; - pNew->xGetLastError = pRoot->xGetLastError==0 ? 0 : vfstraceGetLastError; - if( pNew->iVersion>=2 ){ - pNew->xCurrentTimeInt64 = pRoot->xCurrentTimeInt64==0 ? 0 : - vfstraceCurrentTimeInt64; - if( pNew->iVersion>=3 ){ - pNew->xSetSystemCall = pRoot->xSetSystemCall==0 ? 0 : - vfstraceSetSystemCall; - pNew->xGetSystemCall = pRoot->xGetSystemCall==0 ? 0 : - vfstraceGetSystemCall; - pNew->xNextSystemCall = pRoot->xNextSystemCall==0 ? 0 : - vfstraceNextSystemCall; - } - } - pInfo->pRootVfs = pRoot; - pInfo->xOut = xOut; - pInfo->pOutArg = pOutArg; - pInfo->zVfsName = pNew->zName; - pInfo->pTraceVfs = pNew; - vfstrace_printf(pInfo, "%s.enabled_for(\"%s\")\n", - pInfo->zVfsName, pRoot->zName); - return sqlite3_vfs_register(pNew, makeDefault); -} - -/* -** Look for the named VFS. If it is a TRACEVFS, then unregister it -** and delete it. -*/ -void vfstrace_unregister(const char *zTraceName){ - sqlite3_vfs *pVfs = sqlite3_vfs_find(zTraceName); - if( pVfs==0 ) return; - if( pVfs->xOpen!=vfstraceOpen ) return; - sqlite3_vfs_unregister(pVfs); - sqlite3_free(pVfs); -} - -/************************* End ../ext/misc/vfstrace.c ********************/ - -#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) -#define SQLITE_SHELL_HAVE_RECOVER 1 -#else -#define SQLITE_SHELL_HAVE_RECOVER 0 -#endif -#if SQLITE_SHELL_HAVE_RECOVER -/************************* Begin ../ext/recover/sqlite3recover.h ******************/ -/* -** 2022-08-27 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains the public interface to the "recover" extension - -** an SQLite extension designed to recover data from corrupted database -** files. -*/ - -/* -** OVERVIEW: -** -** To use the API to recover data from a corrupted database, an -** application: -** -** 1) Creates an sqlite3_recover handle by calling either -** sqlite3_recover_init() or sqlite3_recover_init_sql(). -** -** 2) Configures the new handle using one or more calls to -** sqlite3_recover_config(). -** -** 3) Executes the recovery by repeatedly calling sqlite3_recover_step() on -** the handle until it returns something other than SQLITE_OK. If it -** returns SQLITE_DONE, then the recovery operation completed without -** error. If it returns some other non-SQLITE_OK value, then an error -** has occurred. -** -** 4) Retrieves any error code and English language error message using the -** sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs, -** respectively. -** -** 5) Destroys the sqlite3_recover handle and frees all resources -** using sqlite3_recover_finish(). -** -** The application may abandon the recovery operation at any point -** before it is finished by passing the sqlite3_recover handle to -** sqlite3_recover_finish(). This is not an error, but the final state -** of the output database, or the results of running the partial script -** delivered to the SQL callback, are undefined. -*/ - -#ifndef _SQLITE_RECOVER_H -#define _SQLITE_RECOVER_H - -/* #include "sqlite3.h" */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* -** An instance of the sqlite3_recover object represents a recovery -** operation in progress. -** -** Constructors: -** -** sqlite3_recover_init() -** sqlite3_recover_init_sql() -** -** Destructor: -** -** sqlite3_recover_finish() -** -** Methods: -** -** sqlite3_recover_config() -** sqlite3_recover_errcode() -** sqlite3_recover_errmsg() -** sqlite3_recover_run() -** sqlite3_recover_step() -*/ -typedef struct sqlite3_recover sqlite3_recover; - -/* -** These two APIs attempt to create and return a new sqlite3_recover object. -** In both cases the first two arguments identify the (possibly -** corrupt) database to recover data from. The first argument is an open -** database handle and the second the name of a database attached to that -** handle (i.e. "main", "temp" or the name of an attached database). -** -** If sqlite3_recover_init() is used to create the new sqlite3_recover -** handle, then data is recovered into a new database, identified by -** string parameter zUri. zUri may be an absolute or relative file path, -** or may be an SQLite URI. If the identified database file already exists, -** it is overwritten. -** -** If sqlite3_recover_init_sql() is invoked, then any recovered data will -** be returned to the user as a series of SQL statements. Executing these -** SQL statements results in the same database as would have been created -** had sqlite3_recover_init() been used. For each SQL statement in the -** output, the callback function passed as the third argument (xSql) is -** invoked once. The first parameter is a passed a copy of the fourth argument -** to this function (pCtx) as its first parameter, and a pointer to a -** nul-terminated buffer containing the SQL statement formated as UTF-8 as -** the second. If the xSql callback returns any value other than SQLITE_OK, -** then processing is immediately abandoned and the value returned used as -** the recover handle error code (see below). -** -** If an out-of-memory error occurs, NULL may be returned instead of -** a valid handle. In all other cases, it is the responsibility of the -** application to avoid resource leaks by ensuring that -** sqlite3_recover_finish() is called on all allocated handles. -*/ -sqlite3_recover *sqlite3_recover_init( - sqlite3* db, - const char *zDb, - const char *zUri -); -sqlite3_recover *sqlite3_recover_init_sql( - sqlite3* db, - const char *zDb, - int (*xSql)(void*, const char*), - void *pCtx -); - -/* -** Configure an sqlite3_recover object that has just been created using -** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function -** may only be called before the first call to sqlite3_recover_step() -** or sqlite3_recover_run() on the object. -** -** The second argument passed to this function must be one of the -** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument -** depend on the specific SQLITE_RECOVER_* symbol in use. -** -** SQLITE_OK is returned if the configuration operation was successful, -** or an SQLite error code otherwise. -*/ -int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg); - -/* -** SQLITE_RECOVER_LOST_AND_FOUND: -** The pArg argument points to a string buffer containing the name -** of a "lost-and-found" table in the output database, or NULL. If -** the argument is non-NULL and the database contains seemingly -** valid pages that cannot be associated with any table in the -** recovered part of the schema, data is extracted from these -** pages to add to the lost-and-found table. -** -** SQLITE_RECOVER_FREELIST_CORRUPT: -** The pArg value must actually be a pointer to a value of type -** int containing value 0 or 1 cast as a (void*). If this option is set -** (argument is 1) and a lost-and-found table has been configured using -** SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is -** corrupt and an attempt is made to recover records from pages that -** appear to be linked into the freelist. Otherwise, pages on the freelist -** are ignored. Setting this option can recover more data from the -** database, but often ends up "recovering" deleted records. The default -** value is 0 (clear). -** -** SQLITE_RECOVER_ROWIDS: -** The pArg value must actually be a pointer to a value of type -** int containing value 0 or 1 cast as a (void*). If this option is set -** (argument is 1), then an attempt is made to recover rowid values -** that are not also INTEGER PRIMARY KEY values. If this option is -** clear, then new rowids are assigned to all recovered rows. The -** default value is 1 (set). -** -** SQLITE_RECOVER_SLOWINDEXES: -** The pArg value must actually be a pointer to a value of type -** int containing value 0 or 1 cast as a (void*). If this option is clear -** (argument is 0), then when creating an output database, the recover -** module creates and populates non-UNIQUE indexes right at the end of the -** recovery operation - after all recoverable data has been inserted -** into the new database. This is faster overall, but means that the -** final call to sqlite3_recover_step() for a recovery operation may -** be need to create a large number of indexes, which may be very slow. -** -** Or, if this option is set (argument is 1), then non-UNIQUE indexes -** are created in the output database before it is populated with -** recovered data. This is slower overall, but avoids the slow call -** to sqlite3_recover_step() at the end of the recovery operation. -** -** The default option value is 0. -*/ -#define SQLITE_RECOVER_LOST_AND_FOUND 1 -#define SQLITE_RECOVER_FREELIST_CORRUPT 2 -#define SQLITE_RECOVER_ROWIDS 3 -#define SQLITE_RECOVER_SLOWINDEXES 4 - -/* -** Perform a unit of work towards the recovery operation. This function -** must normally be called multiple times to complete database recovery. -** -** If no error occurs but the recovery operation is not completed, this -** function returns SQLITE_OK. If recovery has been completed successfully -** then SQLITE_DONE is returned. If an error has occurred, then an SQLite -** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not -** considered an error if some or all of the data cannot be recovered -** due to database corruption. -** -** Once sqlite3_recover_step() has returned a value other than SQLITE_OK, -** all further such calls on the same recover handle are no-ops that return -** the same non-SQLITE_OK value. -*/ -int sqlite3_recover_step(sqlite3_recover*); - -/* -** Run the recovery operation to completion. Return SQLITE_OK if successful, -** or an SQLite error code otherwise. Calling this function is the same -** as executing: -** -** while( SQLITE_OK==sqlite3_recover_step(p) ); -** return sqlite3_recover_errcode(p); -*/ -int sqlite3_recover_run(sqlite3_recover*); - -/* -** If an error has been encountered during a prior call to -** sqlite3_recover_step(), then this function attempts to return a -** pointer to a buffer containing an English language explanation of -** the error. If no error message is available, or if an out-of memory -** error occurs while attempting to allocate a buffer in which to format -** the error message, NULL is returned. -** -** The returned buffer remains valid until the sqlite3_recover handle is -** destroyed using sqlite3_recover_finish(). -*/ -const char *sqlite3_recover_errmsg(sqlite3_recover*); - -/* -** If this function is called on an sqlite3_recover handle after -** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK. -*/ -int sqlite3_recover_errcode(sqlite3_recover*); - -/* -** Clean up a recovery object created by a call to sqlite3_recover_init(). -** The results of using a recovery object with any API after it has been -** passed to this function are undefined. -** -** This function returns the same value as sqlite3_recover_errcode(). -*/ -int sqlite3_recover_finish(sqlite3_recover*); - - -#ifdef __cplusplus -} /* end of the 'extern "C"' block */ -#endif - -#endif /* ifndef _SQLITE_RECOVER_H */ - -/************************* End ../ext/recover/sqlite3recover.h ********************/ -# ifndef SQLITE_HAVE_SQLITE3R -/************************* Begin ../ext/recover/dbdata.c ******************/ -/* -** 2019-04-17 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains an implementation of two eponymous virtual tables, -** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the -** "sqlite_dbpage" eponymous virtual table be available. -** -** SQLITE_DBDATA: -** sqlite_dbdata is used to extract data directly from a database b-tree -** page and its associated overflow pages, bypassing the b-tree layer. -** The table schema is equivalent to: -** -** CREATE TABLE sqlite_dbdata( -** pgno INTEGER, -** cell INTEGER, -** field INTEGER, -** value ANY, -** schema TEXT HIDDEN -** ); -** -** IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE -** FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND -** "schema". -** -** Each page of the database is inspected. If it cannot be interpreted as -** a b-tree page, or if it is a b-tree page containing 0 entries, the -** sqlite_dbdata table contains no rows for that page. Otherwise, the -** table contains one row for each field in the record associated with -** each cell on the page. For intkey b-trees, the key value is stored in -** field -1. -** -** For example, for the database: -** -** CREATE TABLE t1(a, b); -- root page is page 2 -** INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five'); -** INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten'); -** -** the sqlite_dbdata table contains, as well as from entries related to -** page 1, content equivalent to: -** -** INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES -** (2, 0, -1, 5 ), -** (2, 0, 0, 'v' ), -** (2, 0, 1, 'five'), -** (2, 1, -1, 10 ), -** (2, 1, 0, 'x' ), -** (2, 1, 1, 'ten' ); -** -** If database corruption is encountered, this module does not report an -** error. Instead, it attempts to extract as much data as possible and -** ignores the corruption. -** -** SQLITE_DBPTR: -** The sqlite_dbptr table has the following schema: -** -** CREATE TABLE sqlite_dbptr( -** pgno INTEGER, -** child INTEGER, -** schema TEXT HIDDEN -** ); -** -** It contains one entry for each b-tree pointer between a parent and -** child page in the database. -*/ - -#if !defined(SQLITEINT_H) -/* #include "sqlite3.h" */ - -/* typedef unsigned char u8; */ -/* typedef unsigned int u32; */ - -#endif -#include -#include - -#ifndef SQLITE_OMIT_VIRTUALTABLE - -#define DBDATA_PADDING_BYTES 100 - -typedef struct DbdataTable DbdataTable; -typedef struct DbdataCursor DbdataCursor; -typedef struct DbdataBuffer DbdataBuffer; - -/* -** Buffer type. -*/ -struct DbdataBuffer { - u8 *aBuf; - sqlite3_int64 nBuf; -}; - -/* Cursor object */ -struct DbdataCursor { - sqlite3_vtab_cursor base; /* Base class. Must be first */ - sqlite3_stmt *pStmt; /* For fetching database pages */ - - int iPgno; /* Current page number */ - u8 *aPage; /* Buffer containing page */ - int nPage; /* Size of aPage[] in bytes */ - int nCell; /* Number of cells on aPage[] */ - int iCell; /* Current cell number */ - int bOnePage; /* True to stop after one page */ - int szDb; - sqlite3_int64 iRowid; - - /* Only for the sqlite_dbdata table */ - DbdataBuffer rec; - sqlite3_int64 nRec; /* Size of pRec[] in bytes */ - sqlite3_int64 nHdr; /* Size of header in bytes */ - int iField; /* Current field number */ - u8 *pHdrPtr; - u8 *pPtr; - u32 enc; /* Text encoding */ - - sqlite3_int64 iIntkey; /* Integer key value */ -}; - -/* Table object */ -struct DbdataTable { - sqlite3_vtab base; /* Base class. Must be first */ - sqlite3 *db; /* The database connection */ - sqlite3_stmt *pStmt; /* For fetching database pages */ - int bPtr; /* True for sqlite3_dbptr table */ -}; - -/* Column and schema definitions for sqlite_dbdata */ -#define DBDATA_COLUMN_PGNO 0 -#define DBDATA_COLUMN_CELL 1 -#define DBDATA_COLUMN_FIELD 2 -#define DBDATA_COLUMN_VALUE 3 -#define DBDATA_COLUMN_SCHEMA 4 -#define DBDATA_SCHEMA \ - "CREATE TABLE x(" \ - " pgno INTEGER," \ - " cell INTEGER," \ - " field INTEGER," \ - " value ANY," \ - " schema TEXT HIDDEN" \ - ")" - -/* Column and schema definitions for sqlite_dbptr */ -#define DBPTR_COLUMN_PGNO 0 -#define DBPTR_COLUMN_CHILD 1 -#define DBPTR_COLUMN_SCHEMA 2 -#define DBPTR_SCHEMA \ - "CREATE TABLE x(" \ - " pgno INTEGER," \ - " child INTEGER," \ - " schema TEXT HIDDEN" \ - ")" - -/* -** Ensure the buffer passed as the first argument is at least nMin bytes -** in size. If an error occurs while attempting to resize the buffer, -** SQLITE_NOMEM is returned. Otherwise, SQLITE_OK. -*/ -static int dbdataBufferSize(DbdataBuffer *pBuf, sqlite3_int64 nMin){ - if( nMin>pBuf->nBuf ){ - sqlite3_int64 nNew = nMin+16384; - u8 *aNew = (u8*)sqlite3_realloc64(pBuf->aBuf, nNew); - - if( aNew==0 ) return SQLITE_NOMEM; - pBuf->aBuf = aNew; - pBuf->nBuf = nNew; - } - return SQLITE_OK; -} - -/* -** Release the allocation managed by buffer pBuf. -*/ -static void dbdataBufferFree(DbdataBuffer *pBuf){ - sqlite3_free(pBuf->aBuf); - memset(pBuf, 0, sizeof(*pBuf)); -} - -/* -** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual -** table. -*/ -static int dbdataConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - DbdataTable *pTab = 0; - int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA); - - (void)argc; - (void)argv; - (void)pzErr; - sqlite3_vtab_config(db, SQLITE_VTAB_USES_ALL_SCHEMAS); - if( rc==SQLITE_OK ){ - pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable)); - if( pTab==0 ){ - rc = SQLITE_NOMEM; - }else{ - memset(pTab, 0, sizeof(DbdataTable)); - pTab->db = db; - pTab->bPtr = (pAux!=0); - } - } - - *ppVtab = (sqlite3_vtab*)pTab; - return rc; -} - -/* -** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table. -*/ -static int dbdataDisconnect(sqlite3_vtab *pVtab){ - DbdataTable *pTab = (DbdataTable*)pVtab; - if( pTab ){ - sqlite3_finalize(pTab->pStmt); - sqlite3_free(pVtab); - } - return SQLITE_OK; -} - -/* -** This function interprets two types of constraints: -** -** schema=? -** pgno=? -** -** If neither are present, idxNum is set to 0. If schema=? is present, -** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit -** in idxNum is set. -** -** If both parameters are present, schema is in position 0 and pgno in -** position 1. -*/ -static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){ - DbdataTable *pTab = (DbdataTable*)tab; - int i; - int iSchema = -1; - int iPgno = -1; - int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA); - - for(i=0; inConstraint; i++){ - struct sqlite3_index_constraint *p = &pIdx->aConstraint[i]; - if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ - if( p->iColumn==colSchema ){ - if( p->usable==0 ) return SQLITE_CONSTRAINT; - iSchema = i; - } - if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){ - iPgno = i; - } - } - } - - if( iSchema>=0 ){ - pIdx->aConstraintUsage[iSchema].argvIndex = 1; - pIdx->aConstraintUsage[iSchema].omit = 1; - } - if( iPgno>=0 ){ - pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0); - pIdx->aConstraintUsage[iPgno].omit = 1; - pIdx->estimatedCost = 100; - pIdx->estimatedRows = 50; - - if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){ - int iCol = pIdx->aOrderBy[0].iColumn; - if( pIdx->nOrderBy==1 ){ - pIdx->orderByConsumed = (iCol==0 || iCol==1); - }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){ - pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1); - } - } - - }else{ - pIdx->estimatedCost = 100000000; - pIdx->estimatedRows = 1000000000; - } - pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00); - return SQLITE_OK; -} - -/* -** Open a new sqlite_dbdata or sqlite_dbptr cursor. -*/ -static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ - DbdataCursor *pCsr; - - pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor)); - if( pCsr==0 ){ - return SQLITE_NOMEM; - }else{ - memset(pCsr, 0, sizeof(DbdataCursor)); - pCsr->base.pVtab = pVTab; - } - - *ppCursor = (sqlite3_vtab_cursor *)pCsr; - return SQLITE_OK; -} - -/* -** Restore a cursor object to the state it was in when first allocated -** by dbdataOpen(). -*/ -static void dbdataResetCursor(DbdataCursor *pCsr){ - DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab); - if( pTab->pStmt==0 ){ - pTab->pStmt = pCsr->pStmt; - }else{ - sqlite3_finalize(pCsr->pStmt); - } - pCsr->pStmt = 0; - pCsr->iPgno = 1; - pCsr->iCell = 0; - pCsr->iField = 0; - pCsr->bOnePage = 0; - sqlite3_free(pCsr->aPage); - dbdataBufferFree(&pCsr->rec); - pCsr->aPage = 0; - pCsr->nRec = 0; -} - -/* -** Close an sqlite_dbdata or sqlite_dbptr cursor. -*/ -static int dbdataClose(sqlite3_vtab_cursor *pCursor){ - DbdataCursor *pCsr = (DbdataCursor*)pCursor; - dbdataResetCursor(pCsr); - sqlite3_free(pCsr); - return SQLITE_OK; -} - -/* -** Utility methods to decode 16 and 32-bit big-endian unsigned integers. -*/ -static u32 get_uint16(unsigned char *a){ - return (a[0]<<8)|a[1]; -} -static u32 get_uint32(unsigned char *a){ - return ((u32)a[0]<<24) - | ((u32)a[1]<<16) - | ((u32)a[2]<<8) - | ((u32)a[3]); -} - -/* -** Load page pgno from the database via the sqlite_dbpage virtual table. -** If successful, set (*ppPage) to point to a buffer containing the page -** data, (*pnPage) to the size of that buffer in bytes and return -** SQLITE_OK. In this case it is the responsibility of the caller to -** eventually free the buffer using sqlite3_free(). -** -** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and -** return an SQLite error code. -*/ -static int dbdataLoadPage( - DbdataCursor *pCsr, /* Cursor object */ - u32 pgno, /* Page number of page to load */ - u8 **ppPage, /* OUT: pointer to page buffer */ - int *pnPage /* OUT: Size of (*ppPage) in bytes */ -){ - int rc2; - int rc = SQLITE_OK; - sqlite3_stmt *pStmt = pCsr->pStmt; - - *ppPage = 0; - *pnPage = 0; - if( pgno>0 ){ - sqlite3_bind_int64(pStmt, 2, pgno); - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - int nCopy = sqlite3_column_bytes(pStmt, 0); - if( nCopy>0 ){ - u8 *pPage; - pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES); - if( pPage==0 ){ - rc = SQLITE_NOMEM; - }else{ - const u8 *pCopy = sqlite3_column_blob(pStmt, 0); - memcpy(pPage, pCopy, nCopy); - memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES); - } - *ppPage = pPage; - *pnPage = nCopy; - } - } - rc2 = sqlite3_reset(pStmt); - if( rc==SQLITE_OK ) rc = rc2; - } - - return rc; -} - -/* -** Read a varint. Put the value in *pVal and return the number of bytes. -*/ -static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){ - sqlite3_uint64 u = 0; - int i; - for(i=0; i<8; i++){ - u = (u<<7) + (z[i]&0x7f); - if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; } - } - u = (u<<8) + (z[i]&0xff); - *pVal = (sqlite3_int64)u; - return 9; -} - -/* -** Like dbdataGetVarint(), but set the output to 0 if it is less than 0 -** or greater than 0xFFFFFFFF. This can be used for all varints in an -** SQLite database except for key values in intkey tables. -*/ -static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){ - sqlite3_int64 val; - int nRet = dbdataGetVarint(z, &val); - if( val<0 || val>0xFFFFFFFF ) val = 0; - *pVal = val; - return nRet; -} - -/* -** Return the number of bytes of space used by an SQLite value of type -** eType. -*/ -static int dbdataValueBytes(int eType){ - switch( eType ){ - case 0: case 8: case 9: - case 10: case 11: - return 0; - case 1: - return 1; - case 2: - return 2; - case 3: - return 3; - case 4: - return 4; - case 5: - return 6; - case 6: - case 7: - return 8; - default: - if( eType>0 ){ - return ((eType-12) / 2); - } - return 0; - } -} - -/* -** Load a value of type eType from buffer pData and use it to set the -** result of context object pCtx. -*/ -static void dbdataValue( - sqlite3_context *pCtx, - u32 enc, - int eType, - u8 *pData, - sqlite3_int64 nData -){ - if( eType>=0 ){ - if( dbdataValueBytes(eType)<=nData ){ - switch( eType ){ - case 0: - case 10: - case 11: - sqlite3_result_null(pCtx); - break; - - case 8: - sqlite3_result_int(pCtx, 0); - break; - case 9: - sqlite3_result_int(pCtx, 1); - break; - - case 1: case 2: case 3: case 4: case 5: case 6: case 7: { - sqlite3_uint64 v = (signed char)pData[0]; - pData++; - switch( eType ){ - case 7: - case 6: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2; - case 5: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2; - case 4: v = (v<<8) + pData[0]; pData++; - case 3: v = (v<<8) + pData[0]; pData++; - case 2: v = (v<<8) + pData[0]; pData++; - } - - if( eType==7 ){ - double r; - memcpy(&r, &v, sizeof(r)); - sqlite3_result_double(pCtx, r); - }else{ - sqlite3_result_int64(pCtx, (sqlite3_int64)v); - } - break; - } - - default: { - int n = ((eType-12) / 2); - if( eType % 2 ){ - switch( enc ){ - #ifndef SQLITE_OMIT_UTF16 - case SQLITE_UTF16BE: - sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT); - break; - case SQLITE_UTF16LE: - sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT); - break; - #endif - default: - sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT); - break; - } - }else{ - sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT); - } - } - } - }else{ - if( eType==7 ){ - sqlite3_result_double(pCtx, 0.0); - }else if( eType<7 ){ - sqlite3_result_int(pCtx, 0); - }else if( eType%2 ){ - sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC); - }else{ - sqlite3_result_blob(pCtx, "", 0, SQLITE_STATIC); - } - } - } -} - -/* This macro is a copy of the MX_CELL() macro in the SQLite core. Given -** a page-size, it returns the maximum number of cells that may be present -** on the page. */ -#define DBDATA_MX_CELL(pgsz) ((pgsz-8)/6) - -/* Maximum number of fields that may appear in a single record. This is -** the "hard-limit", according to comments in sqliteLimit.h. */ -#define DBDATA_MX_FIELD 32676 - -/* -** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry. -*/ -static int dbdataNext(sqlite3_vtab_cursor *pCursor){ - DbdataCursor *pCsr = (DbdataCursor*)pCursor; - DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; - - pCsr->iRowid++; - while( 1 ){ - int rc; - int iOff = (pCsr->iPgno==1 ? 100 : 0); - int bNextPage = 0; - - if( pCsr->aPage==0 ){ - while( 1 ){ - if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK; - rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage); - if( rc!=SQLITE_OK ) return rc; - if( pCsr->aPage && pCsr->nPage>=256 ) break; - sqlite3_free(pCsr->aPage); - pCsr->aPage = 0; - if( pCsr->bOnePage ) return SQLITE_OK; - pCsr->iPgno++; - } - - assert( iOff+3+2<=pCsr->nPage ); - pCsr->iCell = pTab->bPtr ? -2 : 0; - pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]); - if( pCsr->nCell>DBDATA_MX_CELL(pCsr->nPage) ){ - pCsr->nCell = DBDATA_MX_CELL(pCsr->nPage); - } - } - - if( pTab->bPtr ){ - if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){ - pCsr->iCell = pCsr->nCell; - } - pCsr->iCell++; - if( pCsr->iCell>=pCsr->nCell ){ - sqlite3_free(pCsr->aPage); - pCsr->aPage = 0; - if( pCsr->bOnePage ) return SQLITE_OK; - pCsr->iPgno++; - }else{ - return SQLITE_OK; - } - }else{ - /* If there is no record loaded, load it now. */ - assert( pCsr->rec.aBuf!=0 || pCsr->nRec==0 ); - if( pCsr->nRec==0 ){ - int bHasRowid = 0; - int nPointer = 0; - sqlite3_int64 nPayload = 0; - sqlite3_int64 nHdr = 0; - int iHdr; - int U, X; - int nLocal; - - switch( pCsr->aPage[iOff] ){ - case 0x02: - nPointer = 4; - break; - case 0x0a: - break; - case 0x0d: - bHasRowid = 1; - break; - default: - /* This is not a b-tree page with records on it. Continue. */ - pCsr->iCell = pCsr->nCell; - break; - } - - if( pCsr->iCell>=pCsr->nCell ){ - bNextPage = 1; - }else{ - int iCellPtr = iOff + 8 + nPointer + pCsr->iCell*2; - - if( iCellPtr>pCsr->nPage ){ - bNextPage = 1; - }else{ - iOff = get_uint16(&pCsr->aPage[iCellPtr]); - } - - /* For an interior node cell, skip past the child-page number */ - iOff += nPointer; - - /* Load the "byte of payload including overflow" field */ - if( bNextPage || iOff>pCsr->nPage || iOff<=iCellPtr ){ - bNextPage = 1; - }else{ - iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload); - if( nPayload>0x7fffff00 ) nPayload &= 0x3fff; - if( nPayload==0 ) nPayload = 1; - } - - /* If this is a leaf intkey cell, load the rowid */ - if( bHasRowid && !bNextPage && iOffnPage ){ - iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey); - } - - /* Figure out how much data to read from the local page */ - U = pCsr->nPage; - if( bHasRowid ){ - X = U-35; - }else{ - X = ((U-12)*64/255)-23; - } - if( nPayload<=X ){ - nLocal = nPayload; - }else{ - int M, K; - M = ((U-12)*32/255)-23; - K = M+((nPayload-M)%(U-4)); - if( K<=X ){ - nLocal = K; - }else{ - nLocal = M; - } - } - - if( bNextPage || nLocal+iOff>pCsr->nPage ){ - bNextPage = 1; - }else{ - - /* Allocate space for payload. And a bit more to catch small buffer - ** overruns caused by attempting to read a varint or similar from - ** near the end of a corrupt record. */ - rc = dbdataBufferSize(&pCsr->rec, nPayload+DBDATA_PADDING_BYTES); - if( rc!=SQLITE_OK ) return rc; - assert( pCsr->rec.aBuf!=0 ); - assert( nPayload!=0 ); - - /* Load the nLocal bytes of payload */ - memcpy(pCsr->rec.aBuf, &pCsr->aPage[iOff], nLocal); - iOff += nLocal; - - /* Load content from overflow pages */ - if( nPayload>nLocal ){ - sqlite3_int64 nRem = nPayload - nLocal; - u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]); - while( nRem>0 ){ - u8 *aOvfl = 0; - int nOvfl = 0; - int nCopy; - rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl); - assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage ); - if( rc!=SQLITE_OK ) return rc; - if( aOvfl==0 ) break; - - nCopy = U-4; - if( nCopy>nRem ) nCopy = nRem; - memcpy(&pCsr->rec.aBuf[nPayload-nRem], &aOvfl[4], nCopy); - nRem -= nCopy; - - pgnoOvfl = get_uint32(aOvfl); - sqlite3_free(aOvfl); - } - nPayload -= nRem; - } - memset(&pCsr->rec.aBuf[nPayload], 0, DBDATA_PADDING_BYTES); - pCsr->nRec = nPayload; - - iHdr = dbdataGetVarintU32(pCsr->rec.aBuf, &nHdr); - if( nHdr>nPayload ) nHdr = 0; - pCsr->nHdr = nHdr; - pCsr->pHdrPtr = &pCsr->rec.aBuf[iHdr]; - pCsr->pPtr = &pCsr->rec.aBuf[pCsr->nHdr]; - pCsr->iField = (bHasRowid ? -1 : 0); - } - } - }else{ - pCsr->iField++; - if( pCsr->iField>0 ){ - sqlite3_int64 iType; - if( pCsr->pHdrPtr>=&pCsr->rec.aBuf[pCsr->nRec] - || pCsr->iField>=DBDATA_MX_FIELD - ){ - bNextPage = 1; - }else{ - int szField = 0; - pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType); - szField = dbdataValueBytes(iType); - if( (pCsr->nRec - (pCsr->pPtr - pCsr->rec.aBuf))pPtr = &pCsr->rec.aBuf[pCsr->nRec]; - }else{ - pCsr->pPtr += szField; - } - } - } - } - - if( bNextPage ){ - sqlite3_free(pCsr->aPage); - pCsr->aPage = 0; - pCsr->nRec = 0; - if( pCsr->bOnePage ) return SQLITE_OK; - pCsr->iPgno++; - }else{ - if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->rec.aBuf[pCsr->nHdr] ){ - return SQLITE_OK; - } - - /* Advance to the next cell. The next iteration of the loop will load - ** the record and so on. */ - pCsr->nRec = 0; - pCsr->iCell++; - } - } - } - - assert( !"can't get here" ); - return SQLITE_OK; -} - -/* -** Return true if the cursor is at EOF. -*/ -static int dbdataEof(sqlite3_vtab_cursor *pCursor){ - DbdataCursor *pCsr = (DbdataCursor*)pCursor; - return pCsr->aPage==0; -} - -/* -** Return true if nul-terminated string zSchema ends in "()". Or false -** otherwise. -*/ -static int dbdataIsFunction(const char *zSchema){ - size_t n = strlen(zSchema); - if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){ - return (int)n-2; - } - return 0; -} - -/* -** Determine the size in pages of database zSchema (where zSchema is -** "main", "temp" or the name of an attached database) and set -** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise, -** an SQLite error code. -*/ -static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){ - DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab; - char *zSql = 0; - int rc, rc2; - int nFunc = 0; - sqlite3_stmt *pStmt = 0; - - if( (nFunc = dbdataIsFunction(zSchema))>0 ){ - zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema); - }else{ - zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema); - } - if( zSql==0 ) return SQLITE_NOMEM; - - rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ - pCsr->szDb = sqlite3_column_int(pStmt, 0); - } - rc2 = sqlite3_finalize(pStmt); - if( rc==SQLITE_OK ) rc = rc2; - return rc; -} - -/* -** Attempt to figure out the encoding of the database by retrieving page 1 -** and inspecting the header field. If successful, set the pCsr->enc variable -** and return SQLITE_OK. Otherwise, return an SQLite error code. -*/ -static int dbdataGetEncoding(DbdataCursor *pCsr){ - int rc = SQLITE_OK; - int nPg1 = 0; - u8 *aPg1 = 0; - rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1); - if( rc==SQLITE_OK && nPg1>=(56+4) ){ - pCsr->enc = get_uint32(&aPg1[56]); - } - sqlite3_free(aPg1); - return rc; -} - - -/* -** xFilter method for sqlite_dbdata and sqlite_dbptr. -*/ -static int dbdataFilter( - sqlite3_vtab_cursor *pCursor, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - DbdataCursor *pCsr = (DbdataCursor*)pCursor; - DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; - int rc = SQLITE_OK; - const char *zSchema = "main"; - (void)idxStr; - (void)argc; - - dbdataResetCursor(pCsr); - assert( pCsr->iPgno==1 ); - if( idxNum & 0x01 ){ - zSchema = (const char*)sqlite3_value_text(argv[0]); - if( zSchema==0 ) zSchema = ""; - } - if( idxNum & 0x02 ){ - pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]); - pCsr->bOnePage = 1; - }else{ - rc = dbdataDbsize(pCsr, zSchema); - } - - if( rc==SQLITE_OK ){ - int nFunc = 0; - if( pTab->pStmt ){ - pCsr->pStmt = pTab->pStmt; - pTab->pStmt = 0; - }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){ - char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema); - if( zSql==0 ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0); - sqlite3_free(zSql); - } - }else{ - rc = sqlite3_prepare_v2(pTab->db, - "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1, - &pCsr->pStmt, 0 - ); - } - } - if( rc==SQLITE_OK ){ - rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT); - } - - /* Try to determine the encoding of the db by inspecting the header - ** field on page 1. */ - if( rc==SQLITE_OK ){ - rc = dbdataGetEncoding(pCsr); - } - - if( rc!=SQLITE_OK ){ - pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db)); - } - - if( rc==SQLITE_OK ){ - rc = dbdataNext(pCursor); - } - return rc; -} - -/* -** Return a column for the sqlite_dbdata or sqlite_dbptr table. -*/ -static int dbdataColumn( - sqlite3_vtab_cursor *pCursor, - sqlite3_context *ctx, - int i -){ - DbdataCursor *pCsr = (DbdataCursor*)pCursor; - DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; - if( pTab->bPtr ){ - switch( i ){ - case DBPTR_COLUMN_PGNO: - sqlite3_result_int64(ctx, pCsr->iPgno); - break; - case DBPTR_COLUMN_CHILD: { - int iOff = pCsr->iPgno==1 ? 100 : 0; - if( pCsr->iCell<0 ){ - iOff += 8; - }else{ - iOff += 12 + pCsr->iCell*2; - if( iOff>pCsr->nPage ) return SQLITE_OK; - iOff = get_uint16(&pCsr->aPage[iOff]); - } - if( iOff<=pCsr->nPage ){ - sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff])); - } - break; - } - } - }else{ - switch( i ){ - case DBDATA_COLUMN_PGNO: - sqlite3_result_int64(ctx, pCsr->iPgno); - break; - case DBDATA_COLUMN_CELL: - sqlite3_result_int(ctx, pCsr->iCell); - break; - case DBDATA_COLUMN_FIELD: - sqlite3_result_int(ctx, pCsr->iField); - break; - case DBDATA_COLUMN_VALUE: { - if( pCsr->iField<0 ){ - sqlite3_result_int64(ctx, pCsr->iIntkey); - }else if( &pCsr->rec.aBuf[pCsr->nRec] >= pCsr->pPtr ){ - sqlite3_int64 iType; - dbdataGetVarintU32(pCsr->pHdrPtr, &iType); - dbdataValue( - ctx, pCsr->enc, iType, pCsr->pPtr, - &pCsr->rec.aBuf[pCsr->nRec] - pCsr->pPtr - ); - } - break; - } - } - } - return SQLITE_OK; -} - -/* -** Return the rowid for an sqlite_dbdata or sqlite_dptr table. -*/ -static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ - DbdataCursor *pCsr = (DbdataCursor*)pCursor; - *pRowid = pCsr->iRowid; - return SQLITE_OK; -} - - -/* -** Invoke this routine to register the "sqlite_dbdata" virtual table module -*/ -static int sqlite3DbdataRegister(sqlite3 *db){ - static sqlite3_module dbdata_module = { - 0, /* iVersion */ - 0, /* xCreate */ - dbdataConnect, /* xConnect */ - dbdataBestIndex, /* xBestIndex */ - dbdataDisconnect, /* xDisconnect */ - 0, /* xDestroy */ - dbdataOpen, /* xOpen - open a cursor */ - dbdataClose, /* xClose - close a cursor */ - dbdataFilter, /* xFilter - configure scan constraints */ - dbdataNext, /* xNext - advance a cursor */ - dbdataEof, /* xEof - check for end of scan */ - dbdataColumn, /* xColumn - read data */ - dbdataRowid, /* xRowid - read data */ - 0, /* xUpdate */ - 0, /* xBegin */ - 0, /* xSync */ - 0, /* xCommit */ - 0, /* xRollback */ - 0, /* xFindMethod */ - 0, /* xRename */ - 0, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ - 0, /* xShadowName */ - 0 /* xIntegrity */ - }; - - int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1); - } - return rc; -} - -int sqlite3_dbdata_init( - sqlite3 *db, - char **pzErrMsg, - const sqlite3_api_routines *pApi -){ - (void)pzErrMsg; - return sqlite3DbdataRegister(db); -} - -#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ - -/************************* End ../ext/recover/dbdata.c ********************/ -/************************* Begin ../ext/recover/sqlite3recover.c ******************/ -/* -** 2022-08-27 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -*/ - - -/* #include "sqlite3recover.h" */ -#include -#include - -#ifndef SQLITE_OMIT_VIRTUALTABLE - -/* -** Declaration for public API function in file dbdata.c. This may be called -** with NULL as the final two arguments to register the sqlite_dbptr and -** sqlite_dbdata virtual tables with a database handle. -*/ -#ifdef _WIN32 - -#endif -int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*); - -/* typedef unsigned int u32; */ -/* typedef unsigned char u8; */ -/* typedef sqlite3_int64 i64; */ - -typedef struct RecoverTable RecoverTable; -typedef struct RecoverColumn RecoverColumn; - -/* -** When recovering rows of data that can be associated with table -** definitions recovered from the sqlite_schema table, each table is -** represented by an instance of the following object. -** -** iRoot: -** The root page in the original database. Not necessarily (and usually -** not) the same in the recovered database. -** -** zTab: -** Name of the table. -** -** nCol/aCol[]: -** aCol[] is an array of nCol columns. In the order in which they appear -** in the table. -** -** bIntkey: -** Set to true for intkey tables, false for WITHOUT ROWID. -** -** iRowidBind: -** Each column in the aCol[] array has associated with it the index of -** the bind parameter its values will be bound to in the INSERT statement -** used to construct the output database. If the table does has a rowid -** but not an INTEGER PRIMARY KEY column, then iRowidBind contains the -** index of the bind paramater to which the rowid value should be bound. -** Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY -** KEY column, then the rowid value should be bound to the index associated -** with the column. -** -** pNext: -** All RecoverTable objects used by the recovery operation are allocated -** and populated as part of creating the recovered database schema in -** the output database, before any non-schema data are recovered. They -** are then stored in a singly-linked list linked by this variable beginning -** at sqlite3_recover.pTblList. -*/ -struct RecoverTable { - u32 iRoot; /* Root page in original database */ - char *zTab; /* Name of table */ - int nCol; /* Number of columns in table */ - RecoverColumn *aCol; /* Array of columns */ - int bIntkey; /* True for intkey, false for without rowid */ - int iRowidBind; /* If >0, bind rowid to INSERT here */ - RecoverTable *pNext; -}; - -/* -** Each database column is represented by an instance of the following object -** stored in the RecoverTable.aCol[] array of the associated table. -** -** iField: -** The index of the associated field within database records. Or -1 if -** there is no associated field (e.g. for virtual generated columns). -** -** iBind: -** The bind index of the INSERT statement to bind this columns values -** to. Or 0 if there is no such index (iff (iField<0)). -** -** bIPK: -** True if this is the INTEGER PRIMARY KEY column. -** -** zCol: -** Name of column. -** -** eHidden: -** A RECOVER_EHIDDEN_* constant value (see below for interpretation of each). -*/ -struct RecoverColumn { - int iField; /* Field in record on disk */ - int iBind; /* Binding to use in INSERT */ - int bIPK; /* True for IPK column */ - char *zCol; - int eHidden; -}; - -#define RECOVER_EHIDDEN_NONE 0 /* Normal database column */ -#define RECOVER_EHIDDEN_HIDDEN 1 /* Column is __HIDDEN__ */ -#define RECOVER_EHIDDEN_VIRTUAL 2 /* Virtual generated column */ -#define RECOVER_EHIDDEN_STORED 3 /* Stored generated column */ - -/* -** Bitmap object used to track pages in the input database. Allocated -** and manipulated only by the following functions: -** -** recoverBitmapAlloc() -** recoverBitmapFree() -** recoverBitmapSet() -** recoverBitmapQuery() -** -** nPg: -** Largest page number that may be stored in the bitmap. The range -** of valid keys is 1 to nPg, inclusive. -** -** aElem[]: -** Array large enough to contain a bit for each key. For key value -** iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32]. -** In other words, the following is true if bit iKey is set, or -** false if it is clear: -** -** (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0 -*/ -typedef struct RecoverBitmap RecoverBitmap; -struct RecoverBitmap { - i64 nPg; /* Size of bitmap */ - u32 aElem[1]; /* Array of 32-bit bitmasks */ -}; - -/* -** State variables (part of the sqlite3_recover structure) used while -** recovering data for tables identified in the recovered schema (state -** RECOVER_STATE_WRITING). -*/ -typedef struct RecoverStateW1 RecoverStateW1; -struct RecoverStateW1 { - sqlite3_stmt *pTbls; - sqlite3_stmt *pSel; - sqlite3_stmt *pInsert; - int nInsert; - - RecoverTable *pTab; /* Table currently being written */ - int nMax; /* Max column count in any schema table */ - sqlite3_value **apVal; /* Array of nMax values */ - int nVal; /* Number of valid entries in apVal[] */ - int bHaveRowid; - i64 iRowid; - i64 iPrevPage; - int iPrevCell; -}; - -/* -** State variables (part of the sqlite3_recover structure) used while -** recovering data destined for the lost and found table (states -** RECOVER_STATE_LOSTANDFOUND[123]). -*/ -typedef struct RecoverStateLAF RecoverStateLAF; -struct RecoverStateLAF { - RecoverBitmap *pUsed; - i64 nPg; /* Size of db in pages */ - sqlite3_stmt *pAllAndParent; - sqlite3_stmt *pMapInsert; - sqlite3_stmt *pMaxField; - sqlite3_stmt *pUsedPages; - sqlite3_stmt *pFindRoot; - sqlite3_stmt *pInsert; /* INSERT INTO lost_and_found ... */ - sqlite3_stmt *pAllPage; - sqlite3_stmt *pPageData; - sqlite3_value **apVal; - int nMaxField; -}; - -/* -** Main recover handle structure. -*/ -struct sqlite3_recover { - /* Copies of sqlite3_recover_init[_sql]() parameters */ - sqlite3 *dbIn; /* Input database */ - char *zDb; /* Name of input db ("main" etc.) */ - char *zUri; /* URI for output database */ - void *pSqlCtx; /* SQL callback context */ - int (*xSql)(void*,const char*); /* Pointer to SQL callback function */ - - /* Values configured by sqlite3_recover_config() */ - char *zStateDb; /* State database to use (or NULL) */ - char *zLostAndFound; /* Name of lost-and-found table (or NULL) */ - int bFreelistCorrupt; /* SQLITE_RECOVER_FREELIST_CORRUPT setting */ - int bRecoverRowid; /* SQLITE_RECOVER_ROWIDS setting */ - int bSlowIndexes; /* SQLITE_RECOVER_SLOWINDEXES setting */ - - int pgsz; - int detected_pgsz; - int nReserve; - u8 *pPage1Disk; - u8 *pPage1Cache; - - /* Error code and error message */ - int errCode; /* For sqlite3_recover_errcode() */ - char *zErrMsg; /* For sqlite3_recover_errmsg() */ - - int eState; - int bCloseTransaction; - - /* Variables used with eState==RECOVER_STATE_WRITING */ - RecoverStateW1 w1; - - /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */ - RecoverStateLAF laf; - - /* Fields used within sqlite3_recover_run() */ - sqlite3 *dbOut; /* Output database */ - sqlite3_stmt *pGetPage; /* SELECT against input db sqlite_dbdata */ - RecoverTable *pTblList; /* List of tables recovered from schema */ -}; - -/* -** The various states in which an sqlite3_recover object may exist: -** -** RECOVER_STATE_INIT: -** The object is initially created in this state. sqlite3_recover_step() -** has yet to be called. This is the only state in which it is permitted -** to call sqlite3_recover_config(). -** -** RECOVER_STATE_WRITING: -** -** RECOVER_STATE_LOSTANDFOUND1: -** State to populate the bitmap of pages used by other tables or the -** database freelist. -** -** RECOVER_STATE_LOSTANDFOUND2: -** Populate the recovery.map table - used to figure out a "root" page -** for each lost page from in the database from which records are -** extracted. -** -** RECOVER_STATE_LOSTANDFOUND3: -** Populate the lost-and-found table itself. -*/ -#define RECOVER_STATE_INIT 0 -#define RECOVER_STATE_WRITING 1 -#define RECOVER_STATE_LOSTANDFOUND1 2 -#define RECOVER_STATE_LOSTANDFOUND2 3 -#define RECOVER_STATE_LOSTANDFOUND3 4 -#define RECOVER_STATE_SCHEMA2 5 -#define RECOVER_STATE_DONE 6 - - -/* -** Global variables used by this extension. -*/ -typedef struct RecoverGlobal RecoverGlobal; -struct RecoverGlobal { - const sqlite3_io_methods *pMethods; - sqlite3_recover *p; -}; -static RecoverGlobal recover_g; - -/* -** Use this static SQLite mutex to protect the globals during the -** first call to sqlite3_recover_step(). -*/ -#define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2 - - -/* -** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid). -*/ -#define RECOVER_ROWID_DEFAULT 1 - -/* -** Mutex handling: -** -** recoverEnterMutex() - Enter the recovery mutex -** recoverLeaveMutex() - Leave the recovery mutex -** recoverAssertMutexHeld() - Assert that the recovery mutex is held -*/ -#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0 -# define recoverEnterMutex() -# define recoverLeaveMutex() -#else -static void recoverEnterMutex(void){ - sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)); -} -static void recoverLeaveMutex(void){ - sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)); -} -#endif -#if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG) -static void recoverAssertMutexHeld(void){ - assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) ); -} -#else -# define recoverAssertMutexHeld() -#endif - - -/* -** Like strlen(). But handles NULL pointer arguments. -*/ -static int recoverStrlen(const char *zStr){ - if( zStr==0 ) return 0; - return (int)(strlen(zStr)&0x7fffffff); -} - -/* -** This function is a no-op if the recover handle passed as the first -** argument already contains an error (if p->errCode!=SQLITE_OK). -** -** Otherwise, an attempt is made to allocate, zero and return a buffer nByte -** bytes in size. If successful, a pointer to the new buffer is returned. Or, -** if an OOM error occurs, NULL is returned and the handle error code -** (p->errCode) set to SQLITE_NOMEM. -*/ -static void *recoverMalloc(sqlite3_recover *p, i64 nByte){ - void *pRet = 0; - assert( nByte>0 ); - if( p->errCode==SQLITE_OK ){ - pRet = sqlite3_malloc64(nByte); - if( pRet ){ - memset(pRet, 0, nByte); - }else{ - p->errCode = SQLITE_NOMEM; - } - } - return pRet; -} - -/* -** Set the error code and error message for the recover handle passed as -** the first argument. The error code is set to the value of parameter -** errCode. -** -** Parameter zFmt must be a printf() style formatting string. The handle -** error message is set to the result of using any trailing arguments for -** parameter substitutions in the formatting string. -** -** For example: -** -** recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename); -*/ -static int recoverError( - sqlite3_recover *p, - int errCode, - const char *zFmt, ... -){ - char *z = 0; - va_list ap; - va_start(ap, zFmt); - if( zFmt ){ - z = sqlite3_vmprintf(zFmt, ap); - } - va_end(ap); - sqlite3_free(p->zErrMsg); - p->zErrMsg = z; - p->errCode = errCode; - return errCode; -} - - -/* -** This function is a no-op if p->errCode is initially other than SQLITE_OK. -** In this case it returns NULL. -** -** Otherwise, an attempt is made to allocate and return a bitmap object -** large enough to store a bit for all page numbers between 1 and nPg, -** inclusive. The bitmap is initially zeroed. -*/ -static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){ - int nElem = (nPg+1+31) / 32; - int nByte = sizeof(RecoverBitmap) + nElem*sizeof(u32); - RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte); - - if( pRet ){ - pRet->nPg = nPg; - } - return pRet; -} - -/* -** Free a bitmap object allocated by recoverBitmapAlloc(). -*/ -static void recoverBitmapFree(RecoverBitmap *pMap){ - sqlite3_free(pMap); -} - -/* -** Set the bit associated with page iPg in bitvec pMap. -*/ -static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){ - if( iPg<=pMap->nPg ){ - int iElem = (iPg / 32); - int iBit = (iPg % 32); - pMap->aElem[iElem] |= (((u32)1) << iBit); - } -} - -/* -** Query bitmap object pMap for the state of the bit associated with page -** iPg. Return 1 if it is set, or 0 otherwise. -*/ -static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){ - int ret = 1; - if( iPg<=pMap->nPg && iPg>0 ){ - int iElem = (iPg / 32); - int iBit = (iPg % 32); - ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0; - } - return ret; -} - -/* -** Set the recover handle error to the error code and message returned by -** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database -** handle db. -*/ -static int recoverDbError(sqlite3_recover *p, sqlite3 *db){ - return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db)); -} - -/* -** This function is a no-op if recover handle p already contains an error -** (if p->errCode!=SQLITE_OK). -** -** Otherwise, it attempts to prepare the SQL statement in zSql against -** database handle db. If successful, the statement handle is returned. -** Or, if an error occurs, NULL is returned and an error left in the -** recover handle. -*/ -static sqlite3_stmt *recoverPrepare( - sqlite3_recover *p, - sqlite3 *db, - const char *zSql -){ - sqlite3_stmt *pStmt = 0; - if( p->errCode==SQLITE_OK ){ - if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){ - recoverDbError(p, db); - } - } - return pStmt; -} - -/* -** This function is a no-op if recover handle p already contains an error -** (if p->errCode!=SQLITE_OK). -** -** Otherwise, argument zFmt is used as a printf() style format string, -** along with any trailing arguments, to create an SQL statement. This -** SQL statement is prepared against database handle db and, if successful, -** the statment handle returned. Or, if an error occurs - either during -** the printf() formatting or when preparing the resulting SQL - an -** error code and message are left in the recover handle. -*/ -static sqlite3_stmt *recoverPreparePrintf( - sqlite3_recover *p, - sqlite3 *db, - const char *zFmt, ... -){ - sqlite3_stmt *pStmt = 0; - if( p->errCode==SQLITE_OK ){ - va_list ap; - char *z; - va_start(ap, zFmt); - z = sqlite3_vmprintf(zFmt, ap); - va_end(ap); - if( z==0 ){ - p->errCode = SQLITE_NOMEM; - }else{ - pStmt = recoverPrepare(p, db, z); - sqlite3_free(z); - } - } - return pStmt; -} - -/* -** Reset SQLite statement handle pStmt. If the call to sqlite3_reset() -** indicates that an error occurred, and there is not already an error -** in the recover handle passed as the first argument, set the error -** code and error message appropriately. -** -** This function returns a copy of the statement handle pointer passed -** as the second argument. -*/ -static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){ - int rc = sqlite3_reset(pStmt); - if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){ - recoverDbError(p, sqlite3_db_handle(pStmt)); - } - return pStmt; -} - -/* -** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset() -** indicates that an error occurred, and there is not already an error -** in the recover handle passed as the first argument, set the error -** code and error message appropriately. -*/ -static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){ - sqlite3 *db = sqlite3_db_handle(pStmt); - int rc = sqlite3_finalize(pStmt); - if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){ - recoverDbError(p, db); - } -} - -/* -** This function is a no-op if recover handle p already contains an error -** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this -** case. -** -** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK. -** Or, if an error occurs, leave an error code and message in the recover -** handle and return a copy of the error code. -*/ -static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){ - if( p->errCode==SQLITE_OK ){ - int rc = sqlite3_exec(db, zSql, 0, 0, 0); - if( rc ){ - recoverDbError(p, db); - } - } - return p->errCode; -} - -/* -** Bind the value pVal to parameter iBind of statement pStmt. Leave an -** error in the recover handle passed as the first argument if an error -** (e.g. an OOM) occurs. -*/ -static void recoverBindValue( - sqlite3_recover *p, - sqlite3_stmt *pStmt, - int iBind, - sqlite3_value *pVal -){ - if( p->errCode==SQLITE_OK ){ - int rc = sqlite3_bind_value(pStmt, iBind, pVal); - if( rc ) recoverError(p, rc, 0); - } -} - -/* -** This function is a no-op if recover handle p already contains an error -** (if p->errCode!=SQLITE_OK). NULL is returned in this case. -** -** Otherwise, an attempt is made to interpret zFmt as a printf() style -** formatting string and the result of using the trailing arguments for -** parameter substitution with it written into a buffer obtained from -** sqlite3_malloc(). If successful, a pointer to the buffer is returned. -** It is the responsibility of the caller to eventually free the buffer -** using sqlite3_free(). -** -** Or, if an error occurs, an error code and message is left in the recover -** handle and NULL returned. -*/ -static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){ - va_list ap; - char *z; - va_start(ap, zFmt); - z = sqlite3_vmprintf(zFmt, ap); - va_end(ap); - if( p->errCode==SQLITE_OK ){ - if( z==0 ) p->errCode = SQLITE_NOMEM; - }else{ - sqlite3_free(z); - z = 0; - } - return z; -} - -/* -** This function is a no-op if recover handle p already contains an error -** (if p->errCode!=SQLITE_OK). Zero is returned in this case. -** -** Otherwise, execute "PRAGMA page_count" against the input database. If -** successful, return the integer result. Or, if an error occurs, leave an -** error code and error message in the sqlite3_recover handle and return -** zero. -*/ -static i64 recoverPageCount(sqlite3_recover *p){ - i64 nPg = 0; - if( p->errCode==SQLITE_OK ){ - sqlite3_stmt *pStmt = 0; - pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb); - if( pStmt ){ - sqlite3_step(pStmt); - nPg = sqlite3_column_int64(pStmt, 0); - } - recoverFinalize(p, pStmt); - } - return nPg; -} - -/* -** Implementation of SQL scalar function "read_i32". The first argument to -** this function must be a blob. The second a non-negative integer. This -** function reads and returns a 32-bit big-endian integer from byte -** offset (4*) of the blob. -** -** SELECT read_i32(, ) -*/ -static void recoverReadI32( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const unsigned char *pBlob; - int nBlob; - int iInt; - - assert( argc==2 ); - nBlob = sqlite3_value_bytes(argv[0]); - pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]); - iInt = sqlite3_value_int(argv[1]) & 0xFFFF; - - if( (iInt+1)*4<=nBlob ){ - const unsigned char *a = &pBlob[iInt*4]; - i64 iVal = ((i64)a[0]<<24) - + ((i64)a[1]<<16) - + ((i64)a[2]<< 8) - + ((i64)a[3]<< 0); - sqlite3_result_int64(context, iVal); - } -} - -/* -** Implementation of SQL scalar function "page_is_used". This function -** is used as part of the procedure for locating orphan rows for the -** lost-and-found table, and it depends on those routines having populated -** the sqlite3_recover.laf.pUsed variable. -** -** The only argument to this function is a page-number. It returns true -** if the page has already been used somehow during data recovery, or false -** otherwise. -** -** SELECT page_is_used(); -*/ -static void recoverPageIsUsed( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx); - i64 pgno = sqlite3_value_int64(apArg[0]); - assert( nArg==1 ); - sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno)); -} - -/* -** The implementation of a user-defined SQL function invoked by the -** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages -** of the database being recovered. -** -** This function always takes a single integer argument. If the argument -** is zero, then the value returned is the number of pages in the db being -** recovered. If the argument is greater than zero, it is a page number. -** The value returned in this case is an SQL blob containing the data for -** the identified page of the db being recovered. e.g. -** -** SELECT getpage(0); -- return number of pages in db -** SELECT getpage(4); -- return page 4 of db as a blob of data -*/ -static void recoverGetPage( - sqlite3_context *pCtx, - int nArg, - sqlite3_value **apArg -){ - sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx); - i64 pgno = sqlite3_value_int64(apArg[0]); - sqlite3_stmt *pStmt = 0; - - assert( nArg==1 ); - if( pgno==0 ){ - i64 nPg = recoverPageCount(p); - sqlite3_result_int64(pCtx, nPg); - return; - }else{ - if( p->pGetPage==0 ){ - pStmt = p->pGetPage = recoverPreparePrintf( - p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb - ); - }else if( p->errCode==SQLITE_OK ){ - pStmt = p->pGetPage; - } - - if( pStmt ){ - sqlite3_bind_int64(pStmt, 1, pgno); - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - const u8 *aPg; - int nPg; - assert( p->errCode==SQLITE_OK ); - aPg = sqlite3_column_blob(pStmt, 0); - nPg = sqlite3_column_bytes(pStmt, 0); - if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){ - aPg = p->pPage1Disk; - } - sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT); - } - recoverReset(p, pStmt); - } - } - - if( p->errCode ){ - if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1); - sqlite3_result_error_code(pCtx, p->errCode); - } -} - -/* -** Find a string that is not found anywhere in z[]. Return a pointer -** to that string. -** -** Try to use zA and zB first. If both of those are already found in z[] -** then make up some string and store it in the buffer zBuf. -*/ -static const char *recoverUnusedString( - const char *z, /* Result must not appear anywhere in z */ - const char *zA, const char *zB, /* Try these first */ - char *zBuf /* Space to store a generated string */ -){ - unsigned i = 0; - if( strstr(z, zA)==0 ) return zA; - if( strstr(z, zB)==0 ) return zB; - do{ - sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); - }while( strstr(z,zBuf)!=0 ); - return zBuf; -} - -/* -** Implementation of scalar SQL function "escape_crlf". The argument passed to -** this function is the output of built-in function quote(). If the first -** character of the input is "'", indicating that the value passed to quote() -** was a text value, then this function searches the input for "\n" and "\r" -** characters and adds a wrapper similar to the following: -** -** replace(replace(, '\n', char(10), '\r', char(13)); -** -** Or, if the first character of the input is not "'", then a copy of the input -** is returned. -*/ -static void recoverEscapeCrlf( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const char *zText = (const char*)sqlite3_value_text(argv[0]); - (void)argc; - if( zText && zText[0]=='\'' ){ - int nText = sqlite3_value_bytes(argv[0]); - int i; - char zBuf1[20]; - char zBuf2[20]; - const char *zNL = 0; - const char *zCR = 0; - int nCR = 0; - int nNL = 0; - - for(i=0; zText[i]; i++){ - if( zNL==0 && zText[i]=='\n' ){ - zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1); - nNL = (int)strlen(zNL); - } - if( zCR==0 && zText[i]=='\r' ){ - zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2); - nCR = (int)strlen(zCR); - } - } - - if( zNL || zCR ){ - int iOut = 0; - i64 nMax = (nNL > nCR) ? nNL : nCR; - i64 nAlloc = nMax * nText + (nMax+64)*2; - char *zOut = (char*)sqlite3_malloc64(nAlloc); - if( zOut==0 ){ - sqlite3_result_error_nomem(context); - return; - } - - if( zNL && zCR ){ - memcpy(&zOut[iOut], "replace(replace(", 16); - iOut += 16; - }else{ - memcpy(&zOut[iOut], "replace(", 8); - iOut += 8; - } - for(i=0; zText[i]; i++){ - if( zText[i]=='\n' ){ - memcpy(&zOut[iOut], zNL, nNL); - iOut += nNL; - }else if( zText[i]=='\r' ){ - memcpy(&zOut[iOut], zCR, nCR); - iOut += nCR; - }else{ - zOut[iOut] = zText[i]; - iOut++; - } - } - - if( zNL ){ - memcpy(&zOut[iOut], ",'", 2); iOut += 2; - memcpy(&zOut[iOut], zNL, nNL); iOut += nNL; - memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12; - } - if( zCR ){ - memcpy(&zOut[iOut], ",'", 2); iOut += 2; - memcpy(&zOut[iOut], zCR, nCR); iOut += nCR; - memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12; - } - - sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT); - sqlite3_free(zOut); - return; - } - } - - sqlite3_result_value(context, argv[0]); -} - -/* -** This function is a no-op if recover handle p already contains an error -** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in -** this case. -** -** Otherwise, attempt to populate temporary table "recovery.schema" with the -** parts of the database schema that can be extracted from the input database. -** -** If no error occurs, SQLITE_OK is returned. Otherwise, an error code -** and error message are left in the recover handle and a copy of the -** error code returned. It is not considered an error if part of all of -** the database schema cannot be recovered due to corruption. -*/ -static int recoverCacheSchema(sqlite3_recover *p){ - return recoverExec(p, p->dbOut, - "WITH RECURSIVE pages(p) AS (" - " SELECT 1" - " UNION" - " SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p" - ")" - "INSERT INTO recovery.schema SELECT" - " max(CASE WHEN field=0 THEN value ELSE NULL END)," - " max(CASE WHEN field=1 THEN value ELSE NULL END)," - " max(CASE WHEN field=2 THEN value ELSE NULL END)," - " max(CASE WHEN field=3 THEN value ELSE NULL END)," - " max(CASE WHEN field=4 THEN value ELSE NULL END)" - "FROM sqlite_dbdata('getpage()') WHERE pgno IN (" - " SELECT p FROM pages" - ") GROUP BY pgno, cell" - ); -} - -/* -** If this recover handle is not in SQL callback mode (i.e. was not created -** using sqlite3_recover_init_sql()) of if an error has already occurred, -** this function is a no-op. Otherwise, issue a callback with SQL statement -** zSql as the parameter. -** -** If the callback returns non-zero, set the recover handle error code to -** the value returned (so that the caller will abandon processing). -*/ -static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){ - if( p->errCode==SQLITE_OK && p->xSql ){ - int res = p->xSql(p->pSqlCtx, zSql); - if( res ){ - recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res); - } - } -} - -/* -** Transfer the following settings from the input database to the output -** database: -** -** + page-size, -** + auto-vacuum settings, -** + database encoding, -** + user-version (PRAGMA user_version), and -** + application-id (PRAGMA application_id), and -*/ -static void recoverTransferSettings(sqlite3_recover *p){ - const char *aPragma[] = { - "encoding", - "page_size", - "auto_vacuum", - "user_version", - "application_id" - }; - int ii; - - /* Truncate the output database to 0 pages in size. This is done by - ** opening a new, empty, temp db, then using the backup API to clobber - ** any existing output db with a copy of it. */ - if( p->errCode==SQLITE_OK ){ - sqlite3 *db2 = 0; - int rc = sqlite3_open("", &db2); - if( rc!=SQLITE_OK ){ - recoverDbError(p, db2); - return; - } - - for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){ - const char *zPrag = aPragma[ii]; - sqlite3_stmt *p1 = 0; - p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag); - if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){ - const char *zArg = (const char*)sqlite3_column_text(p1, 0); - char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg); - recoverSqlCallback(p, z2); - recoverExec(p, db2, z2); - sqlite3_free(z2); - if( zArg==0 ){ - recoverError(p, SQLITE_NOMEM, 0); - } - } - recoverFinalize(p, p1); - } - recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;"); - - if( p->errCode==SQLITE_OK ){ - sqlite3 *db = p->dbOut; - sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main"); - if( pBackup ){ - sqlite3_backup_step(pBackup, -1); - p->errCode = sqlite3_backup_finish(pBackup); - }else{ - recoverDbError(p, db); - } - } - - sqlite3_close(db2); - } -} - -/* -** This function is a no-op if recover handle p already contains an error -** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in -** this case. -** -** Otherwise, an attempt is made to open the output database, attach -** and create the schema of the temporary database used to store -** intermediate data, and to register all required user functions and -** virtual table modules with the output handle. -** -** If no error occurs, SQLITE_OK is returned. Otherwise, an error code -** and error message are left in the recover handle and a copy of the -** error code returned. -*/ -static int recoverOpenOutput(sqlite3_recover *p){ - struct Func { - const char *zName; - int nArg; - void (*xFunc)(sqlite3_context*,int,sqlite3_value **); - } aFunc[] = { - { "getpage", 1, recoverGetPage }, - { "page_is_used", 1, recoverPageIsUsed }, - { "read_i32", 2, recoverReadI32 }, - { "escape_crlf", 1, recoverEscapeCrlf }, - }; - - const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE; - sqlite3 *db = 0; /* New database handle */ - int ii; /* For iterating through aFunc[] */ - - assert( p->dbOut==0 ); - - if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){ - recoverDbError(p, db); - } - - /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules. - ** These two are registered with the output database handle - this - ** module depends on the input handle supporting the sqlite_dbpage - ** virtual table only. */ - if( p->errCode==SQLITE_OK ){ - p->errCode = sqlite3_dbdata_init(db, 0, 0); - } - - /* Register the custom user-functions with the output handle. */ - for(ii=0; - p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0])); - ii++){ - p->errCode = sqlite3_create_function(db, aFunc[ii].zName, - aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0 - ); - } - - p->dbOut = db; - return p->errCode; -} - -/* -** Attach the auxiliary database 'recovery' to the output database handle. -** This temporary database is used during the recovery process and then -** discarded. -*/ -static void recoverOpenRecovery(sqlite3_recover *p){ - char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb); - recoverExec(p, p->dbOut, zSql); - recoverExec(p, p->dbOut, - "PRAGMA writable_schema = 1;" - "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);" - "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);" - ); - sqlite3_free(zSql); -} - - -/* -** This function is a no-op if recover handle p already contains an error -** (if p->errCode!=SQLITE_OK). -** -** Otherwise, argument zName must be the name of a table that has just been -** created in the output database. This function queries the output db -** for the schema of said table, and creates a RecoverTable object to -** store the schema in memory. The new RecoverTable object is linked into -** the list at sqlite3_recover.pTblList. -** -** Parameter iRoot must be the root page of table zName in the INPUT -** database. -*/ -static void recoverAddTable( - sqlite3_recover *p, - const char *zName, /* Name of table created in output db */ - i64 iRoot /* Root page of same table in INPUT db */ -){ - sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut, - "PRAGMA table_xinfo(%Q)", zName - ); - - if( pStmt ){ - int iPk = -1; - int iBind = 1; - RecoverTable *pNew = 0; - int nCol = 0; - int nName = recoverStrlen(zName); - int nByte = 0; - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - nCol++; - nByte += (sqlite3_column_bytes(pStmt, 1)+1); - } - nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1; - recoverReset(p, pStmt); - - pNew = recoverMalloc(p, nByte); - if( pNew ){ - int i = 0; - int iField = 0; - char *csr = 0; - pNew->aCol = (RecoverColumn*)&pNew[1]; - pNew->zTab = csr = (char*)&pNew->aCol[nCol]; - pNew->nCol = nCol; - pNew->iRoot = iRoot; - memcpy(csr, zName, nName); - csr += nName+1; - - for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){ - int iPKF = sqlite3_column_int(pStmt, 5); - int n = sqlite3_column_bytes(pStmt, 1); - const char *z = (const char*)sqlite3_column_text(pStmt, 1); - const char *zType = (const char*)sqlite3_column_text(pStmt, 2); - int eHidden = sqlite3_column_int(pStmt, 6); - - if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i; - if( iPKF>1 ) iPk = -2; - pNew->aCol[i].zCol = csr; - pNew->aCol[i].eHidden = eHidden; - if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){ - pNew->aCol[i].iField = -1; - }else{ - pNew->aCol[i].iField = iField++; - } - if( eHidden!=RECOVER_EHIDDEN_VIRTUAL - && eHidden!=RECOVER_EHIDDEN_STORED - ){ - pNew->aCol[i].iBind = iBind++; - } - memcpy(csr, z, n); - csr += (n+1); - } - - pNew->pNext = p->pTblList; - p->pTblList = pNew; - pNew->bIntkey = 1; - } - - recoverFinalize(p, pStmt); - - pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName); - while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ - int iField = sqlite3_column_int(pStmt, 0); - int iCol = sqlite3_column_int(pStmt, 1); - - assert( iColnCol ); - pNew->aCol[iCol].iField = iField; - - pNew->bIntkey = 0; - iPk = -2; - } - recoverFinalize(p, pStmt); - - if( p->errCode==SQLITE_OK ){ - if( iPk>=0 ){ - pNew->aCol[iPk].bIPK = 1; - }else if( pNew->bIntkey ){ - pNew->iRowidBind = iBind++; - } - } - } -} - -/* -** This function is called after recoverCacheSchema() has cached those parts -** of the input database schema that could be recovered in temporary table -** "recovery.schema". This function creates in the output database copies -** of all parts of that schema that must be created before the tables can -** be populated. Specifically, this means: -** -** * all tables that are not VIRTUAL, and -** * UNIQUE indexes. -** -** If the recovery handle uses SQL callbacks, then callbacks containing -** the associated "CREATE TABLE" and "CREATE INDEX" statements are made. -** -** Additionally, records are added to the sqlite_schema table of the -** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE -** records are written directly to sqlite_schema, not actually executed. -** If the handle is in SQL callback mode, then callbacks are invoked -** with equivalent SQL statements. -*/ -static int recoverWriteSchema1(sqlite3_recover *p){ - sqlite3_stmt *pSelect = 0; - sqlite3_stmt *pTblname = 0; - - pSelect = recoverPrepare(p, p->dbOut, - "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS (" - " SELECT rootpage, name, sql, " - " type='table', " - " sql LIKE 'create virtual%'," - " (type='index' AND (sql LIKE '%unique%' OR ?1))" - " FROM recovery.schema" - ")" - "SELECT rootpage, tbl, isVirtual, name, sql" - " FROM dbschema " - " WHERE tbl OR isIndex" - " ORDER BY tbl DESC, name=='sqlite_sequence' DESC" - ); - - pTblname = recoverPrepare(p, p->dbOut, - "SELECT name FROM sqlite_schema " - "WHERE type='table' ORDER BY rowid DESC LIMIT 1" - ); - - if( pSelect ){ - sqlite3_bind_int(pSelect, 1, p->bSlowIndexes); - while( sqlite3_step(pSelect)==SQLITE_ROW ){ - i64 iRoot = sqlite3_column_int64(pSelect, 0); - int bTable = sqlite3_column_int(pSelect, 1); - int bVirtual = sqlite3_column_int(pSelect, 2); - const char *zName = (const char*)sqlite3_column_text(pSelect, 3); - const char *zSql = (const char*)sqlite3_column_text(pSelect, 4); - char *zFree = 0; - int rc = SQLITE_OK; - - if( bVirtual ){ - zSql = (const char*)(zFree = recoverMPrintf(p, - "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)", - zName, zName, zSql - )); - } - rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0); - if( rc==SQLITE_OK ){ - recoverSqlCallback(p, zSql); - if( bTable && !bVirtual ){ - if( SQLITE_ROW==sqlite3_step(pTblname) ){ - const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0); - if( zTbl ) recoverAddTable(p, zTbl, iRoot); - } - recoverReset(p, pTblname); - } - }else if( rc!=SQLITE_ERROR ){ - recoverDbError(p, p->dbOut); - } - sqlite3_free(zFree); - } - } - recoverFinalize(p, pSelect); - recoverFinalize(p, pTblname); - - return p->errCode; -} - -/* -** This function is called after the output database has been populated. It -** adds all recovered schema elements that were not created in the output -** database by recoverWriteSchema1() - everything except for tables and -** UNIQUE indexes. Specifically: -** -** * views, -** * triggers, -** * non-UNIQUE indexes. -** -** If the recover handle is in SQL callback mode, then equivalent callbacks -** are issued to create the schema elements. -*/ -static int recoverWriteSchema2(sqlite3_recover *p){ - sqlite3_stmt *pSelect = 0; - - pSelect = recoverPrepare(p, p->dbOut, - p->bSlowIndexes ? - "SELECT rootpage, sql FROM recovery.schema " - " WHERE type!='table' AND type!='index'" - : - "SELECT rootpage, sql FROM recovery.schema " - " WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')" - ); - - if( pSelect ){ - while( sqlite3_step(pSelect)==SQLITE_ROW ){ - const char *zSql = (const char*)sqlite3_column_text(pSelect, 1); - int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0); - if( rc==SQLITE_OK ){ - recoverSqlCallback(p, zSql); - }else if( rc!=SQLITE_ERROR ){ - recoverDbError(p, p->dbOut); - } - } - } - recoverFinalize(p, pSelect); - - return p->errCode; -} - -/* -** This function is a no-op if recover handle p already contains an error -** (if p->errCode!=SQLITE_OK). In this case it returns NULL. -** -** Otherwise, if the recover handle is configured to create an output -** database (was created by sqlite3_recover_init()), then this function -** prepares and returns an SQL statement to INSERT a new record into table -** pTab, assuming the first nField fields of a record extracted from disk -** are valid. -** -** For example, if table pTab is: -** -** CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e); -** -** And nField is 4, then the SQL statement prepared and returned is: -** -** INSERT INTO (a, c, d) VALUES (?1, ?2, ?3); -** -** In this case even though 4 values were extracted from the input db, -** only 3 are written to the output, as the generated STORED column -** cannot be written. -** -** If the recover handle is in SQL callback mode, then the SQL statement -** prepared is such that evaluating it returns a single row containing -** a single text value - itself an SQL statement similar to the above, -** except with SQL literals in place of the variables. For example: -** -** SELECT 'INSERT INTO (a, c, d) VALUES (' -** || quote(?1) || ', ' -** || quote(?2) || ', ' -** || quote(?3) || ')'; -** -** In either case, it is the responsibility of the caller to eventually -** free the statement handle using sqlite3_finalize(). -*/ -static sqlite3_stmt *recoverInsertStmt( - sqlite3_recover *p, - RecoverTable *pTab, - int nField -){ - sqlite3_stmt *pRet = 0; - const char *zSep = ""; - const char *zSqlSep = ""; - char *zSql = 0; - char *zFinal = 0; - char *zBind = 0; - int ii; - int bSql = p->xSql ? 1 : 0; - - if( nField<=0 ) return 0; - - assert( nField<=pTab->nCol ); - - zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab); - - if( pTab->iRowidBind ){ - assert( pTab->bIntkey ); - zSql = recoverMPrintf(p, "%z_rowid_", zSql); - if( bSql ){ - zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind); - }else{ - zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind); - } - zSqlSep = "||', '||"; - zSep = ", "; - } - - for(ii=0; iiaCol[ii].eHidden; - if( eHidden!=RECOVER_EHIDDEN_VIRTUAL - && eHidden!=RECOVER_EHIDDEN_STORED - ){ - assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 ); - zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol); - - if( bSql ){ - zBind = recoverMPrintf(p, - "%z%sescape_crlf(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind - ); - zSqlSep = "||', '||"; - }else{ - zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind); - } - zSep = ", "; - } - } - - if( bSql ){ - zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'", - zSql, zBind - ); - }else{ - zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind); - } - - pRet = recoverPrepare(p, p->dbOut, zFinal); - sqlite3_free(zSql); - sqlite3_free(zBind); - sqlite3_free(zFinal); - - return pRet; -} - - -/* -** Search the list of RecoverTable objects at p->pTblList for one that -** has root page iRoot in the input database. If such an object is found, -** return a pointer to it. Otherwise, return NULL. -*/ -static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){ - RecoverTable *pRet = 0; - for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext); - return pRet; -} - -/* -** This function attempts to create a lost and found table within the -** output db. If successful, it returns a pointer to a buffer containing -** the name of the new table. It is the responsibility of the caller to -** eventually free this buffer using sqlite3_free(). -** -** If an error occurs, NULL is returned and an error code and error -** message left in the recover handle. -*/ -static char *recoverLostAndFoundCreate( - sqlite3_recover *p, /* Recover object */ - int nField /* Number of column fields in new table */ -){ - char *zTbl = 0; - sqlite3_stmt *pProbe = 0; - int ii = 0; - - pProbe = recoverPrepare(p, p->dbOut, - "SELECT 1 FROM sqlite_schema WHERE name=?" - ); - for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){ - int bFail = 0; - if( ii<0 ){ - zTbl = recoverMPrintf(p, "%s", p->zLostAndFound); - }else{ - zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii); - } - - if( p->errCode==SQLITE_OK ){ - sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC); - if( SQLITE_ROW==sqlite3_step(pProbe) ){ - bFail = 1; - } - recoverReset(p, pProbe); - } - - if( bFail ){ - sqlite3_clear_bindings(pProbe); - sqlite3_free(zTbl); - zTbl = 0; - } - } - recoverFinalize(p, pProbe); - - if( zTbl ){ - const char *zSep = 0; - char *zField = 0; - char *zSql = 0; - - zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, "; - for(ii=0; p->errCode==SQLITE_OK && iidbOut, zSql); - recoverSqlCallback(p, zSql); - sqlite3_free(zSql); - }else if( p->errCode==SQLITE_OK ){ - recoverError( - p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound - ); - } - - return zTbl; -} - -/* -** Synthesize and prepare an INSERT statement to write to the lost_and_found -** table in the output database. The name of the table is zTab, and it has -** nField c* fields. -*/ -static sqlite3_stmt *recoverLostAndFoundInsert( - sqlite3_recover *p, - const char *zTab, - int nField -){ - int nTotal = nField + 4; - int ii; - char *zBind = 0; - sqlite3_stmt *pRet = 0; - - if( p->xSql==0 ){ - for(ii=0; iidbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind - ); - }else{ - const char *zSep = ""; - for(ii=0; iidbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind - ); - } - - sqlite3_free(zBind); - return pRet; -} - -/* -** Input database page iPg contains data that will be written to the -** lost-and-found table of the output database. This function attempts -** to identify the root page of the tree that page iPg belonged to. -** If successful, it sets output variable (*piRoot) to the page number -** of the root page and returns SQLITE_OK. Otherwise, if an error occurs, -** an SQLite error code is returned and the final value of *piRoot -** undefined. -*/ -static int recoverLostAndFoundFindRoot( - sqlite3_recover *p, - i64 iPg, - i64 *piRoot -){ - RecoverStateLAF *pLaf = &p->laf; - - if( pLaf->pFindRoot==0 ){ - pLaf->pFindRoot = recoverPrepare(p, p->dbOut, - "WITH RECURSIVE p(pgno) AS (" - " SELECT ?" - " UNION" - " SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno" - ") " - "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno " - " AND m.parent IS NULL" - ); - } - if( p->errCode==SQLITE_OK ){ - sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg); - if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){ - *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0); - }else{ - *piRoot = iPg; - } - recoverReset(p, pLaf->pFindRoot); - } - return p->errCode; -} - -/* -** Recover data from page iPage of the input database and write it to -** the lost-and-found table in the output database. -*/ -static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){ - RecoverStateLAF *pLaf = &p->laf; - sqlite3_value **apVal = pLaf->apVal; - sqlite3_stmt *pPageData = pLaf->pPageData; - sqlite3_stmt *pInsert = pLaf->pInsert; - - int nVal = -1; - int iPrevCell = 0; - i64 iRoot = 0; - int bHaveRowid = 0; - i64 iRowid = 0; - int ii = 0; - - if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return; - sqlite3_bind_int64(pPageData, 1, iPage); - while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){ - int iCell = sqlite3_column_int64(pPageData, 0); - int iField = sqlite3_column_int64(pPageData, 1); - - if( iPrevCell!=iCell && nVal>=0 ){ - /* Insert the new row */ - sqlite3_bind_int64(pInsert, 1, iRoot); /* rootpgno */ - sqlite3_bind_int64(pInsert, 2, iPage); /* pgno */ - sqlite3_bind_int(pInsert, 3, nVal); /* nfield */ - if( bHaveRowid ){ - sqlite3_bind_int64(pInsert, 4, iRowid); /* id */ - } - for(ii=0; iinMaxField ){ - sqlite3_value *pVal = sqlite3_column_value(pPageData, 2); - apVal[iField] = sqlite3_value_dup(pVal); - assert( iField==nVal || (nVal==-1 && iField==0) ); - nVal = iField+1; - if( apVal[iField]==0 ){ - recoverError(p, SQLITE_NOMEM, 0); - } - } - - iPrevCell = iCell; - } - recoverReset(p, pPageData); - - for(ii=0; iilaf; - if( p->errCode==SQLITE_OK ){ - if( pLaf->pInsert==0 ){ - return SQLITE_DONE; - }else{ - if( p->errCode==SQLITE_OK ){ - int res = sqlite3_step(pLaf->pAllPage); - if( res==SQLITE_ROW ){ - i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0); - if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){ - recoverLostAndFoundOnePage(p, iPage); - } - }else{ - recoverReset(p, pLaf->pAllPage); - return SQLITE_DONE; - } - } - } - } - return SQLITE_OK; -} - -/* -** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3 -** state - during which the lost-and-found table of the output database -** is populated with recovered data that can not be assigned to any -** recovered schema object. -*/ -static void recoverLostAndFound3Init(sqlite3_recover *p){ - RecoverStateLAF *pLaf = &p->laf; - - if( pLaf->nMaxField>0 ){ - char *zTab = 0; /* Name of lost_and_found table */ - - zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField); - pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField); - sqlite3_free(zTab); - - pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut, - "WITH RECURSIVE seq(ii) AS (" - " SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld" - ")" - "SELECT ii FROM seq" , p->laf.nPg - ); - pLaf->pPageData = recoverPrepare(p, p->dbOut, - "SELECT cell, field, value " - "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? " - "UNION ALL " - "SELECT -1, -1, -1" - ); - - pLaf->apVal = (sqlite3_value**)recoverMalloc(p, - pLaf->nMaxField*sizeof(sqlite3_value*) - ); - } -} - -/* -** Initialize resources required in RECOVER_STATE_WRITING state - during which -** tables recovered from the schema of the input database are populated with -** recovered data. -*/ -static int recoverWriteDataInit(sqlite3_recover *p){ - RecoverStateW1 *p1 = &p->w1; - RecoverTable *pTbl = 0; - int nByte = 0; - - /* Figure out the maximum number of columns for any table in the schema */ - assert( p1->nMax==0 ); - for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){ - if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol; - } - - /* Allocate an array of (sqlite3_value*) in which to accumulate the values - ** that will be written to the output database in a single row. */ - nByte = sizeof(sqlite3_value*) * (p1->nMax+1); - p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte); - if( p1->apVal==0 ) return p->errCode; - - /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT - ** to loop through cells that appear to belong to a single table (pSel). */ - p1->pTbls = recoverPrepare(p, p->dbOut, - "SELECT rootpage FROM recovery.schema " - " WHERE type='table' AND (sql NOT LIKE 'create virtual%')" - " ORDER BY (tbl_name='sqlite_sequence') ASC" - ); - p1->pSel = recoverPrepare(p, p->dbOut, - "WITH RECURSIVE pages(page) AS (" - " SELECT ?1" - " UNION" - " SELECT child FROM sqlite_dbptr('getpage()'), pages " - " WHERE pgno=page" - ") " - "SELECT page, cell, field, value " - "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno " - "UNION ALL " - "SELECT 0, 0, 0, 0" - ); - - return p->errCode; -} - -/* -** Clean up resources allocated by recoverWriteDataInit() (stuff in -** sqlite3_recover.w1). -*/ -static void recoverWriteDataCleanup(sqlite3_recover *p){ - RecoverStateW1 *p1 = &p->w1; - int ii; - for(ii=0; iinVal; ii++){ - sqlite3_value_free(p1->apVal[ii]); - } - sqlite3_free(p1->apVal); - recoverFinalize(p, p1->pInsert); - recoverFinalize(p, p1->pTbls); - recoverFinalize(p, p1->pSel); - memset(p1, 0, sizeof(*p1)); -} - -/* -** Perform one step (sqlite3_recover_step()) of work for the connection -** passed as the only argument, which is guaranteed to be in -** RECOVER_STATE_WRITING state - during which tables recovered from the -** schema of the input database are populated with recovered data. -*/ -static int recoverWriteDataStep(sqlite3_recover *p){ - RecoverStateW1 *p1 = &p->w1; - sqlite3_stmt *pSel = p1->pSel; - sqlite3_value **apVal = p1->apVal; - - if( p->errCode==SQLITE_OK && p1->pTab==0 ){ - if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){ - i64 iRoot = sqlite3_column_int64(p1->pTbls, 0); - p1->pTab = recoverFindTable(p, iRoot); - - recoverFinalize(p, p1->pInsert); - p1->pInsert = 0; - - /* If this table is unknown, return early. The caller will invoke this - ** function again and it will move on to the next table. */ - if( p1->pTab==0 ) return p->errCode; - - /* If this is the sqlite_sequence table, delete any rows added by - ** earlier INSERT statements on tables with AUTOINCREMENT primary - ** keys before recovering its contents. The p1->pTbls SELECT statement - ** is rigged to deliver "sqlite_sequence" last of all, so we don't - ** worry about it being modified after it is recovered. */ - if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){ - recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence"); - recoverSqlCallback(p, "DELETE FROM sqlite_sequence"); - } - - /* Bind the root page of this table within the original database to - ** SELECT statement p1->pSel. The SELECT statement will then iterate - ** through cells that look like they belong to table pTab. */ - sqlite3_bind_int64(pSel, 1, iRoot); - - p1->nVal = 0; - p1->bHaveRowid = 0; - p1->iPrevPage = -1; - p1->iPrevCell = -1; - }else{ - return SQLITE_DONE; - } - } - assert( p->errCode!=SQLITE_OK || p1->pTab ); - - if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){ - RecoverTable *pTab = p1->pTab; - - i64 iPage = sqlite3_column_int64(pSel, 0); - int iCell = sqlite3_column_int(pSel, 1); - int iField = sqlite3_column_int(pSel, 2); - sqlite3_value *pVal = sqlite3_column_value(pSel, 3); - int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell); - - assert( bNewCell==0 || (iField==-1 || iField==0) ); - assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol ); - - if( bNewCell ){ - int ii = 0; - if( p1->nVal>=0 ){ - if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){ - recoverFinalize(p, p1->pInsert); - p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal); - p1->nInsert = p1->nVal; - } - if( p1->nVal>0 ){ - sqlite3_stmt *pInsert = p1->pInsert; - for(ii=0; iinCol; ii++){ - RecoverColumn *pCol = &pTab->aCol[ii]; - int iBind = pCol->iBind; - if( iBind>0 ){ - if( pCol->bIPK ){ - sqlite3_bind_int64(pInsert, iBind, p1->iRowid); - }else if( pCol->iFieldnVal ){ - recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]); - } - } - } - if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){ - sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid); - } - if( SQLITE_ROW==sqlite3_step(pInsert) ){ - const char *z = (const char*)sqlite3_column_text(pInsert, 0); - recoverSqlCallback(p, z); - } - recoverReset(p, pInsert); - assert( p->errCode || pInsert ); - if( pInsert ) sqlite3_clear_bindings(pInsert); - } - } - - for(ii=0; iinVal; ii++){ - sqlite3_value_free(apVal[ii]); - apVal[ii] = 0; - } - p1->nVal = -1; - p1->bHaveRowid = 0; - } - - if( iPage!=0 ){ - if( iField<0 ){ - p1->iRowid = sqlite3_column_int64(pSel, 3); - assert( p1->nVal==-1 ); - p1->nVal = 0; - p1->bHaveRowid = 1; - }else if( iFieldnCol ){ - assert( apVal[iField]==0 ); - apVal[iField] = sqlite3_value_dup( pVal ); - if( apVal[iField]==0 ){ - recoverError(p, SQLITE_NOMEM, 0); - } - p1->nVal = iField+1; - } - p1->iPrevCell = iCell; - p1->iPrevPage = iPage; - } - }else{ - recoverReset(p, pSel); - p1->pTab = 0; - } - - return p->errCode; -} - -/* -** Initialize resources required by sqlite3_recover_step() in -** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not -** already allocated to a recovered schema element is determined. -*/ -static void recoverLostAndFound1Init(sqlite3_recover *p){ - RecoverStateLAF *pLaf = &p->laf; - sqlite3_stmt *pStmt = 0; - - assert( p->laf.pUsed==0 ); - pLaf->nPg = recoverPageCount(p); - pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg); - - /* Prepare a statement to iterate through all pages that are part of any tree - ** in the recoverable part of the input database schema to the bitmap. And, - ** if !p->bFreelistCorrupt, add all pages that appear to be part of the - ** freelist. */ - pStmt = recoverPrepare( - p, p->dbOut, - "WITH trunk(pgno) AS (" - " SELECT read_i32(getpage(1), 8) AS x WHERE x>0" - " UNION" - " SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0" - ")," - "trunkdata(pgno, data) AS (" - " SELECT pgno, getpage(pgno) FROM trunk" - ")," - "freelist(data, n, freepgno) AS (" - " SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata" - " UNION ALL" - " SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0" - ")," - "" - "roots(r) AS (" - " SELECT 1 UNION ALL" - " SELECT rootpage FROM recovery.schema WHERE rootpage>0" - ")," - "used(page) AS (" - " SELECT r FROM roots" - " UNION" - " SELECT child FROM sqlite_dbptr('getpage()'), used " - " WHERE pgno=page" - ") " - "SELECT page FROM used" - " UNION ALL " - "SELECT freepgno FROM freelist WHERE NOT ?" - ); - if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt); - pLaf->pUsedPages = pStmt; -} - -/* -** Perform one step (sqlite3_recover_step()) of work for the connection -** passed as the only argument, which is guaranteed to be in -** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not -** already allocated to a recovered schema element is determined. -*/ -static int recoverLostAndFound1Step(sqlite3_recover *p){ - RecoverStateLAF *pLaf = &p->laf; - int rc = p->errCode; - if( rc==SQLITE_OK ){ - rc = sqlite3_step(pLaf->pUsedPages); - if( rc==SQLITE_ROW ){ - i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0); - recoverBitmapSet(pLaf->pUsed, iPg); - rc = SQLITE_OK; - }else{ - recoverFinalize(p, pLaf->pUsedPages); - pLaf->pUsedPages = 0; - } - } - return rc; -} - -/* -** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2 -** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1 -** are sorted into sets that likely belonged to the same database tree. -*/ -static void recoverLostAndFound2Init(sqlite3_recover *p){ - RecoverStateLAF *pLaf = &p->laf; - - assert( p->laf.pAllAndParent==0 ); - assert( p->laf.pMapInsert==0 ); - assert( p->laf.pMaxField==0 ); - assert( p->laf.nMaxField==0 ); - - pLaf->pMapInsert = recoverPrepare(p, p->dbOut, - "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)" - ); - pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut, - "WITH RECURSIVE seq(ii) AS (" - " SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld" - ")" - "SELECT pgno, child FROM sqlite_dbptr('getpage()') " - " UNION ALL " - "SELECT NULL, ii FROM seq", p->laf.nPg - ); - pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut, - "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?" - ); -} - -/* -** Perform one step (sqlite3_recover_step()) of work for the connection -** passed as the only argument, which is guaranteed to be in -** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified -** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged -** to the same database tree. -*/ -static int recoverLostAndFound2Step(sqlite3_recover *p){ - RecoverStateLAF *pLaf = &p->laf; - if( p->errCode==SQLITE_OK ){ - int res = sqlite3_step(pLaf->pAllAndParent); - if( res==SQLITE_ROW ){ - i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1); - if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){ - sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild); - sqlite3_bind_value(pLaf->pMapInsert, 2, - sqlite3_column_value(pLaf->pAllAndParent, 0) - ); - sqlite3_step(pLaf->pMapInsert); - recoverReset(p, pLaf->pMapInsert); - sqlite3_bind_int64(pLaf->pMaxField, 1, iChild); - if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){ - int nMax = sqlite3_column_int(pLaf->pMaxField, 0); - if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax; - } - recoverReset(p, pLaf->pMaxField); - } - }else{ - recoverFinalize(p, pLaf->pAllAndParent); - pLaf->pAllAndParent =0; - return SQLITE_DONE; - } - } - return p->errCode; -} - -/* -** Free all resources allocated as part of sqlite3_recover_step() calls -** in one of the RECOVER_STATE_LOSTANDFOUND[123] states. -*/ -static void recoverLostAndFoundCleanup(sqlite3_recover *p){ - recoverBitmapFree(p->laf.pUsed); - p->laf.pUsed = 0; - sqlite3_finalize(p->laf.pUsedPages); - sqlite3_finalize(p->laf.pAllAndParent); - sqlite3_finalize(p->laf.pMapInsert); - sqlite3_finalize(p->laf.pMaxField); - sqlite3_finalize(p->laf.pFindRoot); - sqlite3_finalize(p->laf.pInsert); - sqlite3_finalize(p->laf.pAllPage); - sqlite3_finalize(p->laf.pPageData); - p->laf.pUsedPages = 0; - p->laf.pAllAndParent = 0; - p->laf.pMapInsert = 0; - p->laf.pMaxField = 0; - p->laf.pFindRoot = 0; - p->laf.pInsert = 0; - p->laf.pAllPage = 0; - p->laf.pPageData = 0; - sqlite3_free(p->laf.apVal); - p->laf.apVal = 0; -} - -/* -** Free all resources allocated as part of sqlite3_recover_step() calls. -*/ -static void recoverFinalCleanup(sqlite3_recover *p){ - RecoverTable *pTab = 0; - RecoverTable *pNext = 0; - - recoverWriteDataCleanup(p); - recoverLostAndFoundCleanup(p); - - for(pTab=p->pTblList; pTab; pTab=pNext){ - pNext = pTab->pNext; - sqlite3_free(pTab); - } - p->pTblList = 0; - sqlite3_finalize(p->pGetPage); - p->pGetPage = 0; - sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0); - - { -#ifndef NDEBUG - int res = -#endif - sqlite3_close(p->dbOut); - assert( res==SQLITE_OK ); - } - p->dbOut = 0; -} - -/* -** Decode and return an unsigned 16-bit big-endian integer value from -** buffer a[]. -*/ -static u32 recoverGetU16(const u8 *a){ - return (((u32)a[0])<<8) + ((u32)a[1]); -} - -/* -** Decode and return an unsigned 32-bit big-endian integer value from -** buffer a[]. -*/ -static u32 recoverGetU32(const u8 *a){ - return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]); -} - -/* -** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal) -** and return the number of bytes consumed. -*/ -static int recoverGetVarint(const u8 *a, i64 *pVal){ - sqlite3_uint64 u = 0; - int i; - for(i=0; i<8; i++){ - u = (u<<7) + (a[i]&0x7f); - if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; } - } - u = (u<<8) + (a[i]&0xff); - *pVal = (sqlite3_int64)u; - return 9; -} - -/* -** The second argument points to a buffer n bytes in size. If this buffer -** or a prefix thereof appears to contain a well-formed SQLite b-tree page, -** return the page-size in bytes. Otherwise, if the buffer does not -** appear to contain a well-formed b-tree page, return 0. -*/ -static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){ - u8 *aUsed = aTmp; - int nFrag = 0; - int nActual = 0; - int iFree = 0; - int nCell = 0; /* Number of cells on page */ - int iCellOff = 0; /* Offset of cell array in page */ - int iContent = 0; - int eType = 0; - int ii = 0; - - eType = (int)a[0]; - if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0; - - iFree = (int)recoverGetU16(&a[1]); - nCell = (int)recoverGetU16(&a[3]); - iContent = (int)recoverGetU16(&a[5]); - if( iContent==0 ) iContent = 65536; - nFrag = (int)a[7]; - - if( iContent>n ) return 0; - - memset(aUsed, 0, n); - memset(aUsed, 0xFF, iContent); - - /* Follow the free-list. This is the same format for all b-tree pages. */ - if( iFree && iFree<=iContent ) return 0; - while( iFree ){ - int iNext = 0; - int nByte = 0; - if( iFree>(n-4) ) return 0; - iNext = recoverGetU16(&a[iFree]); - nByte = recoverGetU16(&a[iFree+2]); - if( iFree+nByte>n || nByte<4 ) return 0; - if( iNext && iNextiContent ) return 0; - for(ii=0; iin ){ - return 0; - } - if( eType==0x05 || eType==0x02 ) nByte += 4; - nByte += recoverGetVarint(&a[iOff+nByte], &nPayload); - if( eType==0x0D ){ - i64 dummy = 0; - nByte += recoverGetVarint(&a[iOff+nByte], &dummy); - } - if( eType!=0x05 ){ - int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23); - int M = ((n-12)*32/255)-23; - int K = M+((nPayload-M)%(n-4)); - - if( nPayloadn ){ - return 0; - } - for(iByte=iOff; iByte<(iOff+nByte); iByte++){ - if( aUsed[iByte]!=0 ){ - return 0; - } - aUsed[iByte] = 0xFF; - } - } - - nActual = 0; - for(ii=0; iipMethods!=&recover_methods ); - return pFd->pMethods->xClose(pFd); -} - -/* -** Write value v to buffer a[] as a 16-bit big-endian unsigned integer. -*/ -static void recoverPutU16(u8 *a, u32 v){ - a[0] = (v>>8) & 0x00FF; - a[1] = (v>>0) & 0x00FF; -} - -/* -** Write value v to buffer a[] as a 32-bit big-endian unsigned integer. -*/ -static void recoverPutU32(u8 *a, u32 v){ - a[0] = (v>>24) & 0x00FF; - a[1] = (v>>16) & 0x00FF; - a[2] = (v>>8) & 0x00FF; - a[3] = (v>>0) & 0x00FF; -} - -/* -** Detect the page-size of the database opened by file-handle pFd by -** searching the first part of the file for a well-formed SQLite b-tree -** page. If parameter nReserve is non-zero, then as well as searching for -** a b-tree page with zero reserved bytes, this function searches for one -** with nReserve reserved bytes at the end of it. -** -** If successful, set variable p->detected_pgsz to the detected page-size -** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page -** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or, -** if an error occurs (e.g. an IO or OOM error), then an SQLite error code -** is returned. The final value of p->detected_pgsz is undefined in this -** case. -*/ -static int recoverVfsDetectPagesize( - sqlite3_recover *p, /* Recover handle */ - sqlite3_file *pFd, /* File-handle open on input database */ - u32 nReserve, /* Possible nReserve value */ - i64 nSz /* Size of database file in bytes */ -){ - int rc = SQLITE_OK; - const int nMin = 512; - const int nMax = 65536; - const int nMaxBlk = 4; - u32 pgsz = 0; - int iBlk = 0; - u8 *aPg = 0; - u8 *aTmp = 0; - int nBlk = 0; - - aPg = (u8*)sqlite3_malloc(2*nMax); - if( aPg==0 ) return SQLITE_NOMEM; - aTmp = &aPg[nMax]; - - nBlk = (nSz+nMax-1)/nMax; - if( nBlk>nMaxBlk ) nBlk = nMaxBlk; - - do { - for(iBlk=0; rc==SQLITE_OK && iBlk=((iBlk+1)*nMax)) ? nMax : (nSz % nMax); - memset(aPg, 0, nMax); - rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax); - if( rc==SQLITE_OK ){ - int pgsz2; - for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){ - int iOff; - for(iOff=0; iOff(u32)p->detected_pgsz ){ - p->detected_pgsz = pgsz; - p->nReserve = nReserve; - } - if( nReserve==0 ) break; - nReserve = 0; - }while( 1 ); - - p->detected_pgsz = pgsz; - sqlite3_free(aPg); - return rc; -} - -/* -** The xRead() method of the wrapper VFS. This is used to intercept calls -** to read page 1 of the input database. -*/ -static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){ - int rc = SQLITE_OK; - if( pFd->pMethods==&recover_methods ){ - pFd->pMethods = recover_g.pMethods; - rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff); - if( nByte==16 ){ - sqlite3_randomness(16, aBuf); - }else - if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){ - /* Ensure that the database has a valid header file. The only fields - ** that really matter to recovery are: - ** - ** + Database page size (16-bits at offset 16) - ** + Size of db in pages (32-bits at offset 28) - ** + Database encoding (32-bits at offset 56) - ** - ** Also preserved are: - ** - ** + first freelist page (32-bits at offset 32) - ** + size of freelist (32-bits at offset 36) - ** + the wal-mode flags (16-bits at offset 18) - ** - ** We also try to preserve the auto-vacuum, incr-value, user-version - ** and application-id fields - all 32 bit quantities at offsets - ** 52, 60, 64 and 68. All other fields are set to known good values. - ** - ** Byte offset 105 should also contain the page-size as a 16-bit - ** integer. - */ - const int aPreserve[] = {32, 36, 52, 60, 64, 68}; - u8 aHdr[108] = { - 0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, - 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00, - 0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20, - 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, - 0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x2e, 0x5b, 0x30, - - 0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00 - }; - u8 *a = (u8*)aBuf; - - u32 pgsz = recoverGetU16(&a[16]); - u32 nReserve = a[20]; - u32 enc = recoverGetU32(&a[56]); - u32 dbsz = 0; - i64 dbFileSize = 0; - int ii; - sqlite3_recover *p = recover_g.p; - - if( pgsz==0x01 ) pgsz = 65536; - rc = pFd->pMethods->xFileSize(pFd, &dbFileSize); - - if( rc==SQLITE_OK && p->detected_pgsz==0 ){ - rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize); - } - if( p->detected_pgsz ){ - pgsz = p->detected_pgsz; - nReserve = p->nReserve; - } - - if( pgsz ){ - dbsz = dbFileSize / pgsz; - } - if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){ - enc = SQLITE_UTF8; - } - - sqlite3_free(p->pPage1Cache); - p->pPage1Cache = 0; - p->pPage1Disk = 0; - - p->pgsz = nByte; - p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2); - if( p->pPage1Cache ){ - p->pPage1Disk = &p->pPage1Cache[nByte]; - memcpy(p->pPage1Disk, aBuf, nByte); - aHdr[18] = a[18]; - aHdr[19] = a[19]; - recoverPutU32(&aHdr[28], dbsz); - recoverPutU32(&aHdr[56], enc); - recoverPutU16(&aHdr[105], pgsz-nReserve); - if( pgsz==65536 ) pgsz = 1; - recoverPutU16(&aHdr[16], pgsz); - aHdr[20] = nReserve; - for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){ - memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4); - } - memcpy(aBuf, aHdr, sizeof(aHdr)); - memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr)); - - memcpy(p->pPage1Cache, aBuf, nByte); - }else{ - rc = p->errCode; - } - - } - pFd->pMethods = &recover_methods; - }else{ - rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff); - } - return rc; -} - -/* -** Used to make sqlite3_io_methods wrapper methods less verbose. -*/ -#define RECOVER_VFS_WRAPPER(code) \ - int rc = SQLITE_OK; \ - if( pFd->pMethods==&recover_methods ){ \ - pFd->pMethods = recover_g.pMethods; \ - rc = code; \ - pFd->pMethods = &recover_methods; \ - }else{ \ - rc = code; \ - } \ - return rc; - -/* -** Methods of the wrapper VFS. All methods except for xRead() and xClose() -** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent -** method on the lower level VFS, then reinstall the wrapper before returning. -** Those that return an integer value use the RECOVER_VFS_WRAPPER macro. -*/ -static int recoverVfsWrite( - sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff -){ - RECOVER_VFS_WRAPPER ( - pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff) - ); -} -static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){ - RECOVER_VFS_WRAPPER ( - pFd->pMethods->xTruncate(pFd, size) - ); -} -static int recoverVfsSync(sqlite3_file *pFd, int flags){ - RECOVER_VFS_WRAPPER ( - pFd->pMethods->xSync(pFd, flags) - ); -} -static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){ - RECOVER_VFS_WRAPPER ( - pFd->pMethods->xFileSize(pFd, pSize) - ); -} -static int recoverVfsLock(sqlite3_file *pFd, int eLock){ - RECOVER_VFS_WRAPPER ( - pFd->pMethods->xLock(pFd, eLock) - ); -} -static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){ - RECOVER_VFS_WRAPPER ( - pFd->pMethods->xUnlock(pFd, eLock) - ); -} -static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){ - RECOVER_VFS_WRAPPER ( - pFd->pMethods->xCheckReservedLock(pFd, pResOut) - ); -} -static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){ - RECOVER_VFS_WRAPPER ( - (pFd->pMethods ? pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND) - ); -} -static int recoverVfsSectorSize(sqlite3_file *pFd){ - RECOVER_VFS_WRAPPER ( - pFd->pMethods->xSectorSize(pFd) - ); -} -static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){ - RECOVER_VFS_WRAPPER ( - pFd->pMethods->xDeviceCharacteristics(pFd) - ); -} -static int recoverVfsShmMap( - sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp -){ - RECOVER_VFS_WRAPPER ( - pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp) - ); -} -static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){ - RECOVER_VFS_WRAPPER ( - pFd->pMethods->xShmLock(pFd, offset, n, flags) - ); -} -static void recoverVfsShmBarrier(sqlite3_file *pFd){ - if( pFd->pMethods==&recover_methods ){ - pFd->pMethods = recover_g.pMethods; - pFd->pMethods->xShmBarrier(pFd); - pFd->pMethods = &recover_methods; - }else{ - pFd->pMethods->xShmBarrier(pFd); - } -} -static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){ - RECOVER_VFS_WRAPPER ( - pFd->pMethods->xShmUnmap(pFd, deleteFlag) - ); -} - -static int recoverVfsFetch( - sqlite3_file *pFd, - sqlite3_int64 iOff, - int iAmt, - void **pp -){ - (void)pFd; - (void)iOff; - (void)iAmt; - *pp = 0; - return SQLITE_OK; -} -static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){ - (void)pFd; - (void)iOff; - (void)p; - return SQLITE_OK; -} - -/* -** Install the VFS wrapper around the file-descriptor open on the input -** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held -** when this function is called. -*/ -static void recoverInstallWrapper(sqlite3_recover *p){ - sqlite3_file *pFd = 0; - assert( recover_g.pMethods==0 ); - recoverAssertMutexHeld(); - sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd); - assert( pFd==0 || pFd->pMethods!=&recover_methods ); - if( pFd && pFd->pMethods ){ - int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0); - recover_g.pMethods = pFd->pMethods; - recover_g.p = p; - recover_methods.iVersion = iVersion; - pFd->pMethods = &recover_methods; - } -} - -/* -** Uninstall the VFS wrapper that was installed around the file-descriptor open -** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be -** held when this function is called. -*/ -static void recoverUninstallWrapper(sqlite3_recover *p){ - sqlite3_file *pFd = 0; - recoverAssertMutexHeld(); - sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd); - if( pFd && pFd->pMethods ){ - pFd->pMethods = recover_g.pMethods; - recover_g.pMethods = 0; - recover_g.p = 0; - } -} - -/* -** This function does the work of a single sqlite3_recover_step() call. It -** is guaranteed that the handle is not in an error state when this -** function is called. -*/ -static void recoverStep(sqlite3_recover *p){ - assert( p && p->errCode==SQLITE_OK ); - switch( p->eState ){ - case RECOVER_STATE_INIT: - /* This is the very first call to sqlite3_recover_step() on this object. - */ - recoverSqlCallback(p, "BEGIN"); - recoverSqlCallback(p, "PRAGMA writable_schema = on"); - - recoverEnterMutex(); - recoverInstallWrapper(p); - - /* Open the output database. And register required virtual tables and - ** user functions with the new handle. */ - recoverOpenOutput(p); - - /* Open transactions on both the input and output databases. */ - sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0); - recoverExec(p, p->dbIn, "PRAGMA writable_schema = on"); - recoverExec(p, p->dbIn, "BEGIN"); - if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1; - recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema"); - recoverTransferSettings(p); - recoverOpenRecovery(p); - recoverCacheSchema(p); - - recoverUninstallWrapper(p); - recoverLeaveMutex(); - - recoverExec(p, p->dbOut, "BEGIN"); - - recoverWriteSchema1(p); - p->eState = RECOVER_STATE_WRITING; - break; - - case RECOVER_STATE_WRITING: { - if( p->w1.pTbls==0 ){ - recoverWriteDataInit(p); - } - if( SQLITE_DONE==recoverWriteDataStep(p) ){ - recoverWriteDataCleanup(p); - if( p->zLostAndFound ){ - p->eState = RECOVER_STATE_LOSTANDFOUND1; - }else{ - p->eState = RECOVER_STATE_SCHEMA2; - } - } - break; - } - - case RECOVER_STATE_LOSTANDFOUND1: { - if( p->laf.pUsed==0 ){ - recoverLostAndFound1Init(p); - } - if( SQLITE_DONE==recoverLostAndFound1Step(p) ){ - p->eState = RECOVER_STATE_LOSTANDFOUND2; - } - break; - } - case RECOVER_STATE_LOSTANDFOUND2: { - if( p->laf.pAllAndParent==0 ){ - recoverLostAndFound2Init(p); - } - if( SQLITE_DONE==recoverLostAndFound2Step(p) ){ - p->eState = RECOVER_STATE_LOSTANDFOUND3; - } - break; - } - - case RECOVER_STATE_LOSTANDFOUND3: { - if( p->laf.pInsert==0 ){ - recoverLostAndFound3Init(p); - } - if( SQLITE_DONE==recoverLostAndFound3Step(p) ){ - p->eState = RECOVER_STATE_SCHEMA2; - } - break; - } - - case RECOVER_STATE_SCHEMA2: { - int rc = SQLITE_OK; - - recoverWriteSchema2(p); - p->eState = RECOVER_STATE_DONE; - - /* If no error has occurred, commit the write transaction on the output - ** database. Regardless of whether or not an error has occurred, make - ** an attempt to end the read transaction on the input database. */ - recoverExec(p, p->dbOut, "COMMIT"); - rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0); - if( p->errCode==SQLITE_OK ) p->errCode = rc; - - recoverSqlCallback(p, "PRAGMA writable_schema = off"); - recoverSqlCallback(p, "COMMIT"); - p->eState = RECOVER_STATE_DONE; - recoverFinalCleanup(p); - break; - }; - - case RECOVER_STATE_DONE: { - /* no-op */ - break; - }; - } -} - - -/* -** This is a worker function that does the heavy lifting for both init -** functions: -** -** sqlite3_recover_init() -** sqlite3_recover_init_sql() -** -** All this function does is allocate space for the recover handle and -** take copies of the input parameters. All the real work is done within -** sqlite3_recover_run(). -*/ -sqlite3_recover *recoverInit( - sqlite3* db, - const char *zDb, - const char *zUri, /* Output URI for _recover_init() */ - int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */ - void *pSqlCtx /* Context arg for _recover_init_sql() */ -){ - sqlite3_recover *pRet = 0; - int nDb = 0; - int nUri = 0; - int nByte = 0; - - if( zDb==0 ){ zDb = "main"; } - - nDb = recoverStrlen(zDb); - nUri = recoverStrlen(zUri); - - nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1; - pRet = (sqlite3_recover*)sqlite3_malloc(nByte); - if( pRet ){ - memset(pRet, 0, nByte); - pRet->dbIn = db; - pRet->zDb = (char*)&pRet[1]; - pRet->zUri = &pRet->zDb[nDb+1]; - memcpy(pRet->zDb, zDb, nDb); - if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri); - pRet->xSql = xSql; - pRet->pSqlCtx = pSqlCtx; - pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT; - } - - return pRet; -} - -/* -** Initialize a recovery handle that creates a new database containing -** the recovered data. -*/ -sqlite3_recover *sqlite3_recover_init( - sqlite3* db, - const char *zDb, - const char *zUri -){ - return recoverInit(db, zDb, zUri, 0, 0); -} - -/* -** Initialize a recovery handle that returns recovered data in the -** form of SQL statements via a callback. -*/ -sqlite3_recover *sqlite3_recover_init_sql( - sqlite3* db, - const char *zDb, - int (*xSql)(void*, const char*), - void *pSqlCtx -){ - return recoverInit(db, zDb, 0, xSql, pSqlCtx); -} - -/* -** Return the handle error message, if any. -*/ -const char *sqlite3_recover_errmsg(sqlite3_recover *p){ - return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory"; -} - -/* -** Return the handle error code. -*/ -int sqlite3_recover_errcode(sqlite3_recover *p){ - return p ? p->errCode : SQLITE_NOMEM; -} - -/* -** Configure the handle. -*/ -int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){ - int rc = SQLITE_OK; - if( p==0 ){ - rc = SQLITE_NOMEM; - }else if( p->eState!=RECOVER_STATE_INIT ){ - rc = SQLITE_MISUSE; - }else{ - switch( op ){ - case 789: - /* This undocumented magic configuration option is used to set the - ** name of the auxiliary database that is ATTACH-ed to the database - ** connection and used to hold state information during the - ** recovery process. This option is for debugging use only and - ** is subject to change or removal at any time. */ - sqlite3_free(p->zStateDb); - p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg); - break; - - case SQLITE_RECOVER_LOST_AND_FOUND: { - const char *zArg = (const char*)pArg; - sqlite3_free(p->zLostAndFound); - if( zArg ){ - p->zLostAndFound = recoverMPrintf(p, "%s", zArg); - }else{ - p->zLostAndFound = 0; - } - break; - } - - case SQLITE_RECOVER_FREELIST_CORRUPT: - p->bFreelistCorrupt = *(int*)pArg; - break; - - case SQLITE_RECOVER_ROWIDS: - p->bRecoverRowid = *(int*)pArg; - break; - - case SQLITE_RECOVER_SLOWINDEXES: - p->bSlowIndexes = *(int*)pArg; - break; - - default: - rc = SQLITE_NOTFOUND; - break; - } - } - - return rc; -} - -/* -** Do a unit of work towards the recovery job. Return SQLITE_OK if -** no error has occurred but database recovery is not finished, SQLITE_DONE -** if database recovery has been successfully completed, or an SQLite -** error code if an error has occurred. -*/ -int sqlite3_recover_step(sqlite3_recover *p){ - if( p==0 ) return SQLITE_NOMEM; - if( p->errCode==SQLITE_OK ) recoverStep(p); - if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){ - return SQLITE_DONE; - } - return p->errCode; -} - -/* -** Do the configured recovery operation. Return SQLITE_OK if successful, or -** else an SQLite error code. -*/ -int sqlite3_recover_run(sqlite3_recover *p){ - while( SQLITE_OK==sqlite3_recover_step(p) ); - return sqlite3_recover_errcode(p); -} - - -/* -** Free all resources associated with the recover handle passed as the only -** argument. The results of using a handle with any sqlite3_recover_** -** API function after it has been passed to this function are undefined. -** -** A copy of the value returned by the first call made to sqlite3_recover_run() -** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has -** not been called on this handle. -*/ -int sqlite3_recover_finish(sqlite3_recover *p){ - int rc; - if( p==0 ){ - rc = SQLITE_NOMEM; - }else{ - recoverFinalCleanup(p); - if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){ - rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0); - if( p->errCode==SQLITE_OK ) p->errCode = rc; - } - rc = p->errCode; - sqlite3_free(p->zErrMsg); - sqlite3_free(p->zStateDb); - sqlite3_free(p->zLostAndFound); - sqlite3_free(p->pPage1Cache); - sqlite3_free(p); - } - return rc; -} - -#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ - -/************************* End ../ext/recover/sqlite3recover.c ********************/ -# endif /* SQLITE_HAVE_SQLITE3R */ -#endif -#ifdef SQLITE_SHELL_EXTSRC -# include SHELL_STRINGIFY(SQLITE_SHELL_EXTSRC) -#endif - -#if defined(SQLITE_ENABLE_SESSION) -/* -** State information for a single open session -*/ -typedef struct OpenSession OpenSession; -struct OpenSession { - char *zName; /* Symbolic name for this session */ - int nFilter; /* Number of xFilter rejection GLOB patterns */ - char **azFilter; /* Array of xFilter rejection GLOB patterns */ - sqlite3_session *p; /* The open session */ -}; -#endif - -typedef struct ExpertInfo ExpertInfo; -struct ExpertInfo { - sqlite3expert *pExpert; - int bVerbose; -}; - -/* A single line in the EQP output */ -typedef struct EQPGraphRow EQPGraphRow; -struct EQPGraphRow { - int iEqpId; /* ID for this row */ - int iParentId; /* ID of the parent row */ - EQPGraphRow *pNext; /* Next row in sequence */ - char zText[1]; /* Text to display for this row */ -}; - -/* All EQP output is collected into an instance of the following */ -typedef struct EQPGraph EQPGraph; -struct EQPGraph { - EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */ - EQPGraphRow *pLast; /* Last element of the pRow list */ - char zPrefix[100]; /* Graph prefix */ -}; - -/* Parameters affecting columnar mode result display (defaulting together) */ -typedef struct ColModeOpts { - int iWrap; /* In columnar modes, wrap lines reaching this limit */ - u8 bQuote; /* Quote results for .mode box and table */ - u8 bWordWrap; /* In columnar modes, wrap at word boundaries */ -} ColModeOpts; -#define ColModeOpts_default { 60, 0, 0 } -#define ColModeOpts_default_qbox { 60, 1, 0 } - -/* -** State information about the database connection is contained in an -** instance of the following structure. -*/ -typedef struct ShellState ShellState; -struct ShellState { - sqlite3 *db; /* The database */ - u8 autoExplain; /* Automatically turn on .explain mode */ - u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to each SQL stmt */ - u8 autoEQPtest; /* autoEQP is in test mode */ - u8 autoEQPtrace; /* autoEQP is in trace mode */ - u8 scanstatsOn; /* True to display scan stats before each finalize */ - u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */ - u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */ - u8 nEqpLevel; /* Depth of the EQP output graph */ - u8 eTraceType; /* SHELL_TRACE_* value for type of trace */ - u8 bSafeMode; /* True to prohibit unsafe operations */ - u8 bSafeModePersist; /* The long-term value of bSafeMode */ - u8 eRestoreState; /* See comments above doAutoDetectRestore() */ - u8 crlfMode; /* Do NL-to-CRLF translations when enabled (maybe) */ - ColModeOpts cmOpts; /* Option values affecting columnar mode output */ - unsigned statsOn; /* True to display memory stats before each finalize */ - unsigned mEqpLines; /* Mask of vertical lines in the EQP output graph */ - int inputNesting; /* Track nesting level of .read and other redirects */ - int outCount; /* Revert to stdout when reaching zero */ - int cnt; /* Number of records displayed so far */ - int lineno; /* Line number of last line read from in */ - int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */ - FILE *in; /* Read commands from this stream */ - FILE *out; /* Write results here */ - FILE *traceOut; /* Output for sqlite3_trace() */ - int nErr; /* Number of errors seen */ - int mode; /* An output mode setting */ - int modePrior; /* Saved mode */ - int cMode; /* temporary output mode for the current query */ - int normalMode; /* Output mode before ".explain on" */ - int writableSchema; /* True if PRAGMA writable_schema=ON */ - int showHeader; /* True to show column names in List or Column mode */ - int nCheck; /* Number of ".check" commands run */ - unsigned nProgress; /* Number of progress callbacks encountered */ - unsigned mxProgress; /* Maximum progress callbacks before failing */ - unsigned flgProgress; /* Flags for the progress callback */ - unsigned shellFlgs; /* Various flags */ - unsigned priorShFlgs; /* Saved copy of flags */ - sqlite3_int64 szMax; /* --maxsize argument to .open */ - char *zDestTable; /* Name of destination table when MODE_Insert */ - char *zTempFile; /* Temporary file that might need deleting */ - char zTestcase[30]; /* Name of current test case */ - char colSeparator[20]; /* Column separator character for several modes */ - char rowSeparator[20]; /* Row separator character for MODE_Ascii */ - char colSepPrior[20]; /* Saved column separator */ - char rowSepPrior[20]; /* Saved row separator */ - int *colWidth; /* Requested width of each column in columnar modes */ - int *actualWidth; /* Actual width of each column */ - int nWidth; /* Number of slots in colWidth[] and actualWidth[] */ - char nullValue[20]; /* The text to print when a NULL comes back from - ** the database */ - char outfile[FILENAME_MAX]; /* Filename for *out */ - sqlite3_stmt *pStmt; /* Current statement if any. */ - FILE *pLog; /* Write log output here */ - struct AuxDb { /* Storage space for auxiliary database connections */ - sqlite3 *db; /* Connection pointer */ - const char *zDbFilename; /* Filename used to open the connection */ - char *zFreeOnClose; /* Free this memory allocation on close */ -#if defined(SQLITE_ENABLE_SESSION) - int nSession; /* Number of active sessions */ - OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */ -#endif - } aAuxDb[5], /* Array of all database connections */ - *pAuxDb; /* Currently active database connection */ - int *aiIndent; /* Array of indents used in MODE_Explain */ - int nIndent; /* Size of array aiIndent[] */ - int iIndent; /* Index of current op in aiIndent[] */ - char *zNonce; /* Nonce for temporary safe-mode escapes */ - EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */ - ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */ -#ifdef SQLITE_SHELL_FIDDLE - struct { - const char * zInput; /* Input string from wasm/JS proxy */ - const char * zPos; /* Cursor pos into zInput */ - const char * zDefaultDbName; /* Default name for db file */ - } wasm; -#endif -}; - -#ifdef SQLITE_SHELL_FIDDLE -static ShellState shellState; -#endif - - -/* Allowed values for ShellState.autoEQP -*/ -#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */ -#define AUTOEQP_on 1 /* Automatic EQP is on */ -#define AUTOEQP_trigger 2 /* On and also show plans for triggers */ -#define AUTOEQP_full 3 /* Show full EXPLAIN */ - -/* Allowed values for ShellState.openMode -*/ -#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */ -#define SHELL_OPEN_NORMAL 1 /* Normal database file */ -#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */ -#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */ -#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */ -#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */ -#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */ - -/* Allowed values for ShellState.eTraceType -*/ -#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */ -#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */ -#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */ - -/* Bits in the ShellState.flgProgress variable */ -#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */ -#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progress - ** callback limit is reached, and for each - ** top-level SQL statement */ -#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */ - -/* -** These are the allowed shellFlgs values -*/ -#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */ -#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */ -#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */ -#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */ -#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */ -#define SHFLG_CountChanges 0x00000020 /* .changes setting */ -#define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */ -#define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */ -#define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */ -#define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */ -#define SHFLG_TestingMode 0x00000400 /* allow unsafe testing features */ - -/* -** Macros for testing and setting shellFlgs -*/ -#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0) -#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X)) -#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X))) - -/* -** These are the allowed modes. -*/ -#define MODE_Line 0 /* One column per line. Blank line between records */ -#define MODE_Column 1 /* One record per line in neat columns */ -#define MODE_List 2 /* One record per line with a separator */ -#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ -#define MODE_Html 4 /* Generate an XHTML table */ -#define MODE_Insert 5 /* Generate SQL "insert" statements */ -#define MODE_Quote 6 /* Quote values as for SQL */ -#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */ -#define MODE_Csv 8 /* Quote strings, numbers are plain */ -#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */ -#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */ -#define MODE_Pretty 11 /* Pretty-print schemas */ -#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */ -#define MODE_Json 13 /* Output JSON */ -#define MODE_Markdown 14 /* Markdown formatting */ -#define MODE_Table 15 /* MySQL-style table formatting */ -#define MODE_Box 16 /* Unicode box-drawing characters */ -#define MODE_Count 17 /* Output only a count of the rows of output */ -#define MODE_Off 18 /* No query output shown */ -#define MODE_ScanExp 19 /* Like MODE_Explain, but for ".scanstats vm" */ -#define MODE_Www 20 /* Full web-page output */ - -static const char *modeDescr[] = { - "line", - "column", - "list", - "semi", - "html", - "insert", - "quote", - "tcl", - "csv", - "explain", - "ascii", - "prettyprint", - "eqp", - "json", - "markdown", - "table", - "box", - "count", - "off", - "scanexp", - "www", -}; - -/* -** These are the column/row/line separators used by the various -** import/export modes. -*/ -#define SEP_Column "|" -#define SEP_Row "\n" -#define SEP_Tab "\t" -#define SEP_Space " " -#define SEP_Comma "," -#define SEP_CrLf "\r\n" -#define SEP_Unit "\x1F" -#define SEP_Record "\x1E" - -/* -** Limit input nesting via .read or any other input redirect. -** It's not too expensive, so a generous allowance can be made. -*/ -#define MAX_INPUT_NESTING 25 - -/* -** A callback for the sqlite3_log() interface. -*/ -static void shellLog(void *pArg, int iErrCode, const char *zMsg){ - ShellState *p = (ShellState*)pArg; - if( p->pLog==0 ) return; - sqlite3_fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg); - fflush(p->pLog); -} - -/* -** SQL function: shell_putsnl(X) -** -** Write the text X to the screen (or whatever output is being directed) -** adding a newline at the end, and then return X. -*/ -static void shellPutsFunc( - sqlite3_context *pCtx, - int nVal, - sqlite3_value **apVal -){ - ShellState *p = (ShellState*)sqlite3_user_data(pCtx); - (void)nVal; - sqlite3_fprintf(p->out, "%s\n", sqlite3_value_text(apVal[0])); - sqlite3_result_value(pCtx, apVal[0]); -} - -/* -** If in safe mode, print an error message described by the arguments -** and exit immediately. -*/ -static void failIfSafeMode( - ShellState *p, - const char *zErrMsg, - ... -){ - if( p->bSafeMode ){ - va_list ap; - char *zMsg; - va_start(ap, zErrMsg); - zMsg = sqlite3_vmprintf(zErrMsg, ap); - va_end(ap); - sqlite3_fprintf(stderr, "line %d: %s\n", p->lineno, zMsg); - exit(1); - } -} - -/* -** SQL function: edit(VALUE) -** edit(VALUE,EDITOR) -** -** These steps: -** -** (1) Write VALUE into a temporary file. -** (2) Run program EDITOR on that temporary file. -** (3) Read the temporary file back and return its content as the result. -** (4) Delete the temporary file -** -** If the EDITOR argument is omitted, use the value in the VISUAL -** environment variable. If still there is no EDITOR, through an error. -** -** Also throw an error if the EDITOR program returns a non-zero exit code. -*/ -#ifndef SQLITE_NOHAVE_SYSTEM -static void editFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const char *zEditor; - char *zTempFile = 0; - sqlite3 *db; - char *zCmd = 0; - int bBin; - int rc; - int hasCRLF = 0; - FILE *f = 0; - sqlite3_int64 sz; - sqlite3_int64 x; - unsigned char *p = 0; - - if( argc==2 ){ - zEditor = (const char*)sqlite3_value_text(argv[1]); - }else{ - zEditor = getenv("VISUAL"); - } - if( zEditor==0 ){ - sqlite3_result_error(context, "no editor for edit()", -1); - return; - } - if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ - sqlite3_result_error(context, "NULL input to edit()", -1); - return; - } - db = sqlite3_context_db_handle(context); - zTempFile = 0; - sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile); - if( zTempFile==0 ){ - sqlite3_uint64 r = 0; - sqlite3_randomness(sizeof(r), &r); - zTempFile = sqlite3_mprintf("temp%llx", r); - if( zTempFile==0 ){ - sqlite3_result_error_nomem(context); - return; - } - } - bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB; - /* When writing the file to be edited, do \n to \r\n conversions on systems - ** that want \r\n line endings */ - f = sqlite3_fopen(zTempFile, bBin ? "wb" : "w"); - if( f==0 ){ - sqlite3_result_error(context, "edit() cannot open temp file", -1); - goto edit_func_end; - } - sz = sqlite3_value_bytes(argv[0]); - if( bBin ){ - x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f); - }else{ - const char *z = (const char*)sqlite3_value_text(argv[0]); - /* Remember whether or not the value originally contained \r\n */ - if( z && strstr(z,"\r\n")!=0 ) hasCRLF = 1; - x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f); - } - fclose(f); - f = 0; - if( x!=sz ){ - sqlite3_result_error(context, "edit() could not write the whole file", -1); - goto edit_func_end; - } - zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile); - if( zCmd==0 ){ - sqlite3_result_error_nomem(context); - goto edit_func_end; - } - rc = system(zCmd); - sqlite3_free(zCmd); - if( rc ){ - sqlite3_result_error(context, "EDITOR returned non-zero", -1); - goto edit_func_end; - } - f = sqlite3_fopen(zTempFile, "rb"); - if( f==0 ){ - sqlite3_result_error(context, - "edit() cannot reopen temp file after edit", -1); - goto edit_func_end; - } - fseek(f, 0, SEEK_END); - sz = ftell(f); - rewind(f); - p = sqlite3_malloc64( sz+1 ); - if( p==0 ){ - sqlite3_result_error_nomem(context); - goto edit_func_end; - } - x = fread(p, 1, (size_t)sz, f); - fclose(f); - f = 0; - if( x!=sz ){ - sqlite3_result_error(context, "could not read back the whole file", -1); - goto edit_func_end; - } - if( bBin ){ - sqlite3_result_blob64(context, p, sz, sqlite3_free); - }else{ - sqlite3_int64 i, j; - if( hasCRLF ){ - /* If the original contains \r\n then do no conversions back to \n */ - }else{ - /* If the file did not originally contain \r\n then convert any new - ** \r\n back into \n */ - p[sz] = 0; - for(i=j=0; imodePrior = p->mode; - p->priorShFlgs = p->shellFlgs; - memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); - memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); -} -static void outputModePop(ShellState *p){ - p->mode = p->modePrior; - p->shellFlgs = p->priorShFlgs; - memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); - memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); -} - -/* -** Set output mode to text or binary for Windows. -*/ -static void setCrlfMode(ShellState *p){ -#ifdef _WIN32 - if( p->crlfMode ){ - sqlite3_fsetmode(p->out, _O_TEXT); - }else{ - sqlite3_fsetmode(p->out, _O_BINARY); - } -#else - UNUSED_PARAMETER(p); -#endif -} - -/* -** Output the given string as a hex-encoded blob (eg. X'1234' ) -*/ -static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ - int i; - unsigned char *aBlob = (unsigned char*)pBlob; - - char *zStr = sqlite3_malloc(nBlob*2 + 1); - shell_check_oom(zStr); - - for(i=0; i> 4) ]; - zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ]; - } - zStr[i*2] = '\0'; - - sqlite3_fprintf(out, "X'%s'", zStr); - sqlite3_free(zStr); -} - -/* -** Find a string that is not found anywhere in z[]. Return a pointer -** to that string. -** -** Try to use zA and zB first. If both of those are already found in z[] -** then make up some string and store it in the buffer zBuf. -*/ -static const char *unused_string( - const char *z, /* Result must not appear anywhere in z */ - const char *zA, const char *zB, /* Try these first */ - char *zBuf /* Space to store a generated string */ -){ - unsigned i = 0; - if( strstr(z, zA)==0 ) return zA; - if( strstr(z, zB)==0 ) return zB; - do{ - sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); - }while( strstr(z,zBuf)!=0 ); - return zBuf; -} - -/* -** Output the given string as a quoted string using SQL quoting conventions. -** -** See also: output_quoted_escaped_string() -*/ -static void output_quoted_string(ShellState *p, const char *z){ - int i; - char c; - FILE *out = p->out; - sqlite3_fsetmode(out, _O_BINARY); - if( z==0 ) return; - for(i=0; (c = z[i])!=0 && c!='\''; i++){} - if( c==0 ){ - sqlite3_fprintf(out, "'%s'",z); - }else{ - sqlite3_fputs("'", out); - while( *z ){ - for(i=0; (c = z[i])!=0 && c!='\''; i++){} - if( c=='\'' ) i++; - if( i ){ - sqlite3_fprintf(out, "%.*s", i, z); - z += i; - } - if( c=='\'' ){ - sqlite3_fputs("'", out); - continue; - } - if( c==0 ){ - break; - } - z++; - } - sqlite3_fputs("'", out); - } - setCrlfMode(p); -} - -/* -** Output the given string as a quoted string using SQL quoting conventions. -** Additionallly , escape the "\n" and "\r" characters so that they do not -** get corrupted by end-of-line translation facilities in some operating -** systems. -** -** This is like output_quoted_string() but with the addition of the \r\n -** escape mechanism. -*/ -static void output_quoted_escaped_string(ShellState *p, const char *z){ - int i; - char c; - FILE *out = p->out; - sqlite3_fsetmode(out, _O_BINARY); - for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){} - if( c==0 ){ - sqlite3_fprintf(out, "'%s'",z); - }else{ - const char *zNL = 0; - const char *zCR = 0; - int nNL = 0; - int nCR = 0; - char zBuf1[20], zBuf2[20]; - for(i=0; z[i]; i++){ - if( z[i]=='\n' ) nNL++; - if( z[i]=='\r' ) nCR++; - } - if( nNL ){ - sqlite3_fputs("replace(", out); - zNL = unused_string(z, "\\n", "\\012", zBuf1); - } - if( nCR ){ - sqlite3_fputs("replace(", out); - zCR = unused_string(z, "\\r", "\\015", zBuf2); - } - sqlite3_fputs("'", out); - while( *z ){ - for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){} - if( c=='\'' ) i++; - if( i ){ - sqlite3_fprintf(out, "%.*s", i, z); - z += i; - } - if( c=='\'' ){ - sqlite3_fputs("'", out); - continue; - } - if( c==0 ){ - break; - } - z++; - if( c=='\n' ){ - sqlite3_fputs(zNL, out); - continue; - } - sqlite3_fputs(zCR, out); - } - sqlite3_fputs("'", out); - if( nCR ){ - sqlite3_fprintf(out, ",'%s',char(13))", zCR); - } - if( nNL ){ - sqlite3_fprintf(out, ",'%s',char(10))", zNL); - } - } - setCrlfMode(p); -} - -/* -** Find earliest of chars within s specified in zAny. -** With ns == ~0, is like strpbrk(s,zAny) and s must be 0-terminated. -*/ -static const char *anyOfInStr(const char *s, const char *zAny, size_t ns){ - const char *pcFirst = 0; - if( ns == ~(size_t)0 ) ns = strlen(s); - while(*zAny){ - const char *pc = (const char*)memchr(s, *zAny&0xff, ns); - if( pc ){ - pcFirst = pc; - ns = pcFirst - s; - } - ++zAny; - } - return pcFirst; -} - -/* Skip over as much z[] input char sequence as is valid UTF-8, -** limited per nAccept char's or whole characters and containing -** no char cn such that ((1<=0 => char count, nAccept<0 => character - */ -const char *zSkipValidUtf8(const char *z, int nAccept, long ccm){ - int ng = (nAccept<0)? -nAccept : 0; - const char *pcLimit = (nAccept>=0)? z+nAccept : 0; - assert(z!=0); - while( (pcLimit)? (z= pcLimit ) return z; - else{ - char ct = *zt++; - if( ct==0 || (zt-z)>4 || (ct & 0xC0)!=0x80 ){ - /* Trailing bytes are too few, too many, or invalid. */ - return z; - } - } - } while( ((c <<= 1) & 0x40) == 0x40 ); /* Eat lead byte's count. */ - z = zt; - } - } - return z; -} - - -/* -** Output the given string as a quoted according to C or TCL quoting rules. -*/ -static void output_c_string(FILE *out, const char *z){ - char c; - static const char *zq = "\""; - static long ctrlMask = ~0L; - static const char *zDQBSRO = "\"\\\x7f"; /* double-quote, backslash, rubout */ - char ace[3] = "\\?"; - char cbsSay; - sqlite3_fputs(zq, out); - while( *z!=0 ){ - const char *pcDQBSRO = anyOfInStr(z, zDQBSRO, ~(size_t)0); - const char *pcPast = zSkipValidUtf8(z, INT_MAX, ctrlMask); - const char *pcEnd = (pcDQBSRO && pcDQBSRO < pcPast)? pcDQBSRO : pcPast; - if( pcEnd > z ){ - sqlite3_fprintf(out, "%.*s", (int)(pcEnd-z), z); - } - if( (c = *pcEnd)==0 ) break; - ++pcEnd; - switch( c ){ - case '\\': case '"': - cbsSay = (char)c; - break; - case '\t': cbsSay = 't'; break; - case '\n': cbsSay = 'n'; break; - case '\r': cbsSay = 'r'; break; - case '\f': cbsSay = 'f'; break; - default: cbsSay = 0; break; - } - if( cbsSay ){ - ace[1] = cbsSay; - sqlite3_fputs(ace, out); - }else if( !isprint(c&0xff) ){ - sqlite3_fprintf(out, "\\%03o", c&0xff); - }else{ - ace[1] = (char)c; - sqlite3_fputs(ace+1, out); - } - z = pcEnd; - } - sqlite3_fputs(zq, out); -} - -/* -** Output the given string as a quoted according to JSON quoting rules. -*/ -static void output_json_string(FILE *out, const char *z, i64 n){ - char c; - static const char *zq = "\""; - static long ctrlMask = ~0L; - static const char *zDQBS = "\"\\"; - const char *pcLimit; - char ace[3] = "\\?"; - char cbsSay; - - if( z==0 ) z = ""; - pcLimit = z + ((n<0)? strlen(z) : (size_t)n); - sqlite3_fputs(zq, out); - while( z < pcLimit ){ - const char *pcDQBS = anyOfInStr(z, zDQBS, pcLimit-z); - const char *pcPast = zSkipValidUtf8(z, (int)(pcLimit-z), ctrlMask); - const char *pcEnd = (pcDQBS && pcDQBS < pcPast)? pcDQBS : pcPast; - if( pcEnd > z ){ - sqlite3_fprintf(out, "%.*s", (int)(pcEnd-z), z); - z = pcEnd; - } - if( z >= pcLimit ) break; - c = *(z++); - switch( c ){ - case '"': case '\\': - cbsSay = (char)c; - break; - case '\b': cbsSay = 'b'; break; - case '\f': cbsSay = 'f'; break; - case '\n': cbsSay = 'n'; break; - case '\r': cbsSay = 'r'; break; - case '\t': cbsSay = 't'; break; - default: cbsSay = 0; break; - } - if( cbsSay ){ - ace[1] = cbsSay; - sqlite3_fputs(ace, out); - }else if( c<=0x1f ){ - sqlite3_fprintf(out, "u%04x", c); - }else{ - ace[1] = (char)c; - sqlite3_fputs(ace+1, out); - } - } - sqlite3_fputs(zq, out); -} - -/* -** Output the given string with characters that are special to -** HTML escaped. -*/ -static void output_html_string(FILE *out, const char *z){ - int i; - if( z==0 ) z = ""; - while( *z ){ - for(i=0; z[i] - && z[i]!='<' - && z[i]!='&' - && z[i]!='>' - && z[i]!='\"' - && z[i]!='\''; - i++){} - if( i>0 ){ - sqlite3_fprintf(out, "%.*s",i,z); - } - if( z[i]=='<' ){ - sqlite3_fputs("<", out); - }else if( z[i]=='&' ){ - sqlite3_fputs("&", out); - }else if( z[i]=='>' ){ - sqlite3_fputs(">", out); - }else if( z[i]=='\"' ){ - sqlite3_fputs(""", out); - }else if( z[i]=='\'' ){ - sqlite3_fputs("'", out); - }else{ - break; - } - z += i + 1; - } -} - -/* -** If a field contains any character identified by a 1 in the following -** array, then the string must be quoted for CSV. -*/ -static const char needCsvQuote[] = { - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -}; - -/* -** Output a single term of CSV. Actually, p->colSeparator is used for -** the separator, which may or may not be a comma. p->nullValue is -** the null value. Strings are quoted if necessary. The separator -** is only issued if bSep is true. -*/ -static void output_csv(ShellState *p, const char *z, int bSep){ - if( z==0 ){ - sqlite3_fprintf(p->out, "%s",p->nullValue); - }else{ - unsigned i; - for(i=0; z[i]; i++){ - if( needCsvQuote[((unsigned char*)z)[i]] ){ - i = 0; - break; - } - } - if( i==0 || strstr(z, p->colSeparator)!=0 ){ - char *zQuoted = sqlite3_mprintf("\"%w\"", z); - shell_check_oom(zQuoted); - sqlite3_fputs(zQuoted, p->out); - sqlite3_free(zQuoted); - }else{ - sqlite3_fputs(z, p->out); - } - } - if( bSep ){ - sqlite3_fputs(p->colSeparator, p->out); - } -} - -/* -** This routine runs when the user presses Ctrl-C -*/ -static void interrupt_handler(int NotUsed){ - UNUSED_PARAMETER(NotUsed); - if( ++seenInterrupt>1 ) exit(1); - if( globalDb ) sqlite3_interrupt(globalDb); -} - -#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) -/* -** This routine runs for console events (e.g. Ctrl-C) on Win32 -*/ -static BOOL WINAPI ConsoleCtrlHandler( - DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */ -){ - if( dwCtrlType==CTRL_C_EVENT ){ - interrupt_handler(0); - return TRUE; - } - return FALSE; -} -#endif - -#ifndef SQLITE_OMIT_AUTHORIZATION -/* -** This authorizer runs in safe mode. -*/ -static int safeModeAuth( - void *pClientData, - int op, - const char *zA1, - const char *zA2, - const char *zA3, - const char *zA4 -){ - ShellState *p = (ShellState*)pClientData; - static const char *azProhibitedFunctions[] = { - "edit", - "fts3_tokenizer", - "load_extension", - "readfile", - "writefile", - "zipfile", - "zipfile_cds", - }; - UNUSED_PARAMETER(zA1); - UNUSED_PARAMETER(zA3); - UNUSED_PARAMETER(zA4); - switch( op ){ - case SQLITE_ATTACH: { -#ifndef SQLITE_SHELL_FIDDLE - /* In WASM builds the filesystem is a virtual sandbox, so - ** there's no harm in using ATTACH. */ - failIfSafeMode(p, "cannot run ATTACH in safe mode"); -#endif - break; - } - case SQLITE_FUNCTION: { - int i; - for(i=0; iout, "authorizer: %s", azAction[op]); - for(i=0; i<4; i++){ - sqlite3_fputs(" ", p->out); - if( az[i] ){ - output_c_string(p->out, az[i]); - }else{ - sqlite3_fputs("NULL", p->out); - } - } - sqlite3_fputs("\n", p->out); - if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4); - return SQLITE_OK; -} -#endif - -/* -** Print a schema statement. Part of MODE_Semi and MODE_Pretty output. -** -** This routine converts some CREATE TABLE statements for shadow tables -** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements. -** -** If the schema statement in z[] contains a start-of-comment and if -** sqlite3_complete() returns false, try to terminate the comment before -** printing the result. https://sqlite.org/forum/forumpost/d7be961c5c -*/ -static void printSchemaLine(FILE *out, const char *z, const char *zTail){ - char *zToFree = 0; - if( z==0 ) return; - if( zTail==0 ) return; - if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){ - const char *zOrig = z; - static const char *azTerm[] = { "", "*/", "\n" }; - int i; - for(i=0; iautoEQPtest ){ - sqlite3_fprintf(p->out, "%d,%d,%s\n", iEqpId, p2, zText); - } - pNew = sqlite3_malloc64( sizeof(*pNew) + nText ); - shell_check_oom(pNew); - pNew->iEqpId = iEqpId; - pNew->iParentId = p2; - memcpy(pNew->zText, zText, nText+1); - pNew->pNext = 0; - if( p->sGraph.pLast ){ - p->sGraph.pLast->pNext = pNew; - }else{ - p->sGraph.pRow = pNew; - } - p->sGraph.pLast = pNew; -} - -/* -** Free and reset the EXPLAIN QUERY PLAN data that has been collected -** in p->sGraph. -*/ -static void eqp_reset(ShellState *p){ - EQPGraphRow *pRow, *pNext; - for(pRow = p->sGraph.pRow; pRow; pRow = pNext){ - pNext = pRow->pNext; - sqlite3_free(pRow); - } - memset(&p->sGraph, 0, sizeof(p->sGraph)); -} - -/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after -** pOld, or return the first such line if pOld is NULL -*/ -static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){ - EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow; - while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext; - return pRow; -} - -/* Render a single level of the graph that has iEqpId as its parent. Called -** recursively to render sublevels. -*/ -static void eqp_render_level(ShellState *p, int iEqpId){ - EQPGraphRow *pRow, *pNext; - i64 n = strlen(p->sGraph.zPrefix); - char *z; - for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){ - pNext = eqp_next_row(p, iEqpId, pRow); - z = pRow->zText; - sqlite3_fprintf(p->out, "%s%s%s\n", p->sGraph.zPrefix, - pNext ? "|--" : "`--", z); - if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){ - memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4); - eqp_render_level(p, pRow->iEqpId); - p->sGraph.zPrefix[n] = 0; - } - } -} - -/* -** Display and reset the EXPLAIN QUERY PLAN data -*/ -static void eqp_render(ShellState *p, i64 nCycle){ - EQPGraphRow *pRow = p->sGraph.pRow; - if( pRow ){ - if( pRow->zText[0]=='-' ){ - if( pRow->pNext==0 ){ - eqp_reset(p); - return; - } - sqlite3_fprintf(p->out, "%s\n", pRow->zText+3); - p->sGraph.pRow = pRow->pNext; - sqlite3_free(pRow); - }else if( nCycle>0 ){ - sqlite3_fprintf(p->out, "QUERY PLAN (cycles=%lld [100%%])\n", nCycle); - }else{ - sqlite3_fputs("QUERY PLAN\n", p->out); - } - p->sGraph.zPrefix[0] = 0; - eqp_render_level(p, 0); - eqp_reset(p); - } -} - -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK -/* -** Progress handler callback. -*/ -static int progress_handler(void *pClientData) { - ShellState *p = (ShellState*)pClientData; - p->nProgress++; - if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ - sqlite3_fprintf(p->out, "Progress limit reached (%u)\n", p->nProgress); - if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; - if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; - return 1; - } - if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ - sqlite3_fprintf(p->out, "Progress %u\n", p->nProgress); - } - return 0; -} -#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ - -/* -** Print N dashes -*/ -static void print_dashes(FILE *out, int N){ - const char zDash[] = "--------------------------------------------------"; - const int nDash = sizeof(zDash) - 1; - while( N>nDash ){ - sqlite3_fputs(zDash, out); - N -= nDash; - } - sqlite3_fprintf(out, "%.*s", N, zDash); -} - -/* -** Print a markdown or table-style row separator using ascii-art -*/ -static void print_row_separator( - ShellState *p, - int nArg, - const char *zSep -){ - int i; - if( nArg>0 ){ - sqlite3_fputs(zSep, p->out); - print_dashes(p->out, p->actualWidth[0]+2); - for(i=1; iout); - print_dashes(p->out, p->actualWidth[i]+2); - } - sqlite3_fputs(zSep, p->out); - } - sqlite3_fputs("\n", p->out); -} - -/* -** This is the callback routine that the shell -** invokes for each row of a query result. -*/ -static int shell_callback( - void *pArg, - int nArg, /* Number of result columns */ - char **azArg, /* Text of each result column */ - char **azCol, /* Column names */ - int *aiType /* Column types. Might be NULL */ -){ - int i; - ShellState *p = (ShellState*)pArg; - - if( azArg==0 ) return 0; - switch( p->cMode ){ - case MODE_Count: - case MODE_Off: { - break; - } - case MODE_Line: { - int w = 5; - if( azArg==0 ) break; - for(i=0; iw ) w = len; - } - if( p->cnt++>0 ) sqlite3_fputs(p->rowSeparator, p->out); - for(i=0; iout, "%*s = %s%s", w, azCol[i], - azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); - } - break; - } - case MODE_ScanExp: - case MODE_Explain: { - static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13}; - static const int aExplainMap[] = {0, 1, 2, 3, 4, 5, 6, 7 }; - static const int aScanExpWidth[] = {4, 15, 6, 13, 4, 4, 4, 13, 2, 13}; - static const int aScanExpMap[] = {0, 9, 8, 1, 2, 3, 4, 5, 6, 7 }; - - const int *aWidth = aExplainWidth; - const int *aMap = aExplainMap; - int nWidth = ArraySize(aExplainWidth); - int iIndent = 1; - - if( p->cMode==MODE_ScanExp ){ - aWidth = aScanExpWidth; - aMap = aScanExpMap; - nWidth = ArraySize(aScanExpWidth); - iIndent = 3; - } - if( nArg>nWidth ) nArg = nWidth; - - /* If this is the first row seen, print out the headers */ - if( p->cnt++==0 ){ - for(i=0; iout, aWidth[i], azCol[ aMap[i] ]); - sqlite3_fputs(i==nArg-1 ? "\n" : " ", p->out); - } - for(i=0; iout, aWidth[i]); - sqlite3_fputs(i==nArg-1 ? "\n" : " ", p->out); - } - } - - /* If there is no data, exit early. */ - if( azArg==0 ) break; - - for(i=0; iw ){ - w = strlenChar(zVal); - zSep = " "; - } - if( i==iIndent && p->aiIndent && p->pStmt ){ - if( p->iIndentnIndent ){ - sqlite3_fprintf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); - } - p->iIndent++; - } - utf8_width_print(p->out, w, zVal ? zVal : p->nullValue); - sqlite3_fputs(i==nArg-1 ? "\n" : zSep, p->out); - } - break; - } - case MODE_Semi: { /* .schema and .fullschema output */ - printSchemaLine(p->out, azArg[0], ";\n"); - break; - } - case MODE_Pretty: { /* .schema and .fullschema with --indent */ - char *z; - int j; - int nParen = 0; - char cEnd = 0; - char c; - int nLine = 0; - assert( nArg==1 ); - if( azArg[0]==0 ) break; - if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0 - || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0 - ){ - sqlite3_fprintf(p->out, "%s;\n", azArg[0]); - break; - } - z = sqlite3_mprintf("%s", azArg[0]); - shell_check_oom(z); - j = 0; - for(i=0; IsSpace(z[i]); i++){} - for(; (c = z[i])!=0; i++){ - if( IsSpace(c) ){ - if( z[j-1]=='\r' ) z[j-1] = '\n'; - if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; - }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ - j--; - } - z[j++] = c; - } - while( j>0 && IsSpace(z[j-1]) ){ j--; } - z[j] = 0; - if( strlen30(z)>=79 ){ - for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */ - if( c==cEnd ){ - cEnd = 0; - }else if( c=='"' || c=='\'' || c=='`' ){ - cEnd = c; - }else if( c=='[' ){ - cEnd = ']'; - }else if( c=='-' && z[i+1]=='-' ){ - cEnd = '\n'; - }else if( c=='(' ){ - nParen++; - }else if( c==')' ){ - nParen--; - if( nLine>0 && nParen==0 && j>0 ){ - printSchemaLineN(p->out, z, j, "\n"); - j = 0; - } - } - z[j++] = c; - if( nParen==1 && cEnd==0 - && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1))) - ){ - if( c=='\n' ) j--; - printSchemaLineN(p->out, z, j, "\n "); - j = 0; - nLine++; - while( IsSpace(z[i+1]) ){ i++; } - } - } - z[j] = 0; - } - printSchemaLine(p->out, z, ";\n"); - sqlite3_free(z); - break; - } - case MODE_List: { - if( p->cnt++==0 && p->showHeader ){ - for(i=0; iout, "%s%s", azCol[i], - i==nArg-1 ? p->rowSeparator : p->colSeparator); - } - } - if( azArg==0 ) break; - for(i=0; inullValue; - sqlite3_fputs(z, p->out); - sqlite3_fputs((icolSeparator : p->rowSeparator, p->out); - } - break; - } - case MODE_Www: - case MODE_Html: { - if( p->cnt==0 && p->cMode==MODE_Www ){ - sqlite3_fputs( - "\n" - "\n" - ,p->out - ); - } - if( p->cnt==0 && (p->showHeader || p->cMode==MODE_Www) ){ - sqlite3_fputs("", p->out); - for(i=0; i", p->out); - output_html_string(p->out, azCol[i]); - sqlite3_fputs("\n", p->out); - } - sqlite3_fputs("\n", p->out); - } - p->cnt++; - if( azArg==0 ) break; - sqlite3_fputs("", p->out); - for(i=0; i", p->out); - output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); - sqlite3_fputs("\n", p->out); - } - sqlite3_fputs("\n", p->out); - break; - } - case MODE_Tcl: { - if( p->cnt++==0 && p->showHeader ){ - for(i=0; iout, azCol[i] ? azCol[i] : ""); - if(icolSeparator, p->out); - } - sqlite3_fputs(p->rowSeparator, p->out); - } - if( azArg==0 ) break; - for(i=0; iout, azArg[i] ? azArg[i] : p->nullValue); - if(icolSeparator, p->out); - } - sqlite3_fputs(p->rowSeparator, p->out); - break; - } - case MODE_Csv: { - sqlite3_fsetmode(p->out, _O_BINARY); - if( p->cnt++==0 && p->showHeader ){ - for(i=0; irowSeparator, p->out); - } - if( nArg>0 ){ - for(i=0; irowSeparator, p->out); - } - setCrlfMode(p); - break; - } - case MODE_Insert: { - if( azArg==0 ) break; - sqlite3_fprintf(p->out, "INSERT INTO %s",p->zDestTable); - if( p->showHeader ){ - sqlite3_fputs("(", p->out); - for(i=0; i0 ) sqlite3_fputs(",", p->out); - if( quoteChar(azCol[i]) ){ - char *z = sqlite3_mprintf("\"%w\"", azCol[i]); - shell_check_oom(z); - sqlite3_fputs(z, p->out); - sqlite3_free(z); - }else{ - sqlite3_fprintf(p->out, "%s", azCol[i]); - } - } - sqlite3_fputs(")", p->out); - } - p->cnt++; - for(i=0; i0 ? "," : " VALUES(", p->out); - if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ - sqlite3_fputs("NULL", p->out); - }else if( aiType && aiType[i]==SQLITE_TEXT ){ - if( ShellHasFlag(p, SHFLG_Newlines) ){ - output_quoted_string(p, azArg[i]); - }else{ - output_quoted_escaped_string(p, azArg[i]); - } - }else if( aiType && aiType[i]==SQLITE_INTEGER ){ - sqlite3_fputs(azArg[i], p->out); - }else if( aiType && aiType[i]==SQLITE_FLOAT ){ - char z[50]; - double r = sqlite3_column_double(p->pStmt, i); - sqlite3_uint64 ur; - memcpy(&ur,&r,sizeof(r)); - if( ur==0x7ff0000000000000LL ){ - sqlite3_fputs("9.0e+999", p->out); - }else if( ur==0xfff0000000000000LL ){ - sqlite3_fputs("-9.0e+999", p->out); - }else{ - sqlite3_int64 ir = (sqlite3_int64)r; - if( r==(double)ir ){ - sqlite3_snprintf(50,z,"%lld.0", ir); - }else{ - sqlite3_snprintf(50,z,"%!.20g", r); - } - sqlite3_fputs(z, p->out); - } - }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ - const void *pBlob = sqlite3_column_blob(p->pStmt, i); - int nBlob = sqlite3_column_bytes(p->pStmt, i); - output_hex_blob(p->out, pBlob, nBlob); - }else if( isNumber(azArg[i], 0) ){ - sqlite3_fputs(azArg[i], p->out); - }else if( ShellHasFlag(p, SHFLG_Newlines) ){ - output_quoted_string(p, azArg[i]); - }else{ - output_quoted_escaped_string(p, azArg[i]); - } - } - sqlite3_fputs(");\n", p->out); - break; - } - case MODE_Json: { - if( azArg==0 ) break; - if( p->cnt==0 ){ - sqlite3_fputs("[{", p->out); - }else{ - sqlite3_fputs(",\n{", p->out); - } - p->cnt++; - for(i=0; iout, azCol[i], -1); - sqlite3_fputs(":", p->out); - if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ - sqlite3_fputs("null", p->out); - }else if( aiType && aiType[i]==SQLITE_FLOAT ){ - char z[50]; - double r = sqlite3_column_double(p->pStmt, i); - sqlite3_uint64 ur; - memcpy(&ur,&r,sizeof(r)); - if( ur==0x7ff0000000000000LL ){ - sqlite3_fputs("9.0e+999", p->out); - }else if( ur==0xfff0000000000000LL ){ - sqlite3_fputs("-9.0e+999", p->out); - }else{ - sqlite3_snprintf(50,z,"%!.20g", r); - sqlite3_fputs(z, p->out); - } - }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ - const void *pBlob = sqlite3_column_blob(p->pStmt, i); - int nBlob = sqlite3_column_bytes(p->pStmt, i); - output_json_string(p->out, pBlob, nBlob); - }else if( aiType && aiType[i]==SQLITE_TEXT ){ - output_json_string(p->out, azArg[i], -1); - }else{ - sqlite3_fputs(azArg[i], p->out); - } - if( iout); - } - } - sqlite3_fputs("}", p->out); - break; - } - case MODE_Quote: { - if( azArg==0 ) break; - if( p->cnt==0 && p->showHeader ){ - for(i=0; i0 ) sqlite3_fputs(p->colSeparator, p->out); - output_quoted_string(p, azCol[i]); - } - sqlite3_fputs(p->rowSeparator, p->out); - } - p->cnt++; - for(i=0; i0 ) sqlite3_fputs(p->colSeparator, p->out); - if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ - sqlite3_fputs("NULL", p->out); - }else if( aiType && aiType[i]==SQLITE_TEXT ){ - output_quoted_string(p, azArg[i]); - }else if( aiType && aiType[i]==SQLITE_INTEGER ){ - sqlite3_fputs(azArg[i], p->out); - }else if( aiType && aiType[i]==SQLITE_FLOAT ){ - char z[50]; - double r = sqlite3_column_double(p->pStmt, i); - sqlite3_snprintf(50,z,"%!.20g", r); - sqlite3_fputs(z, p->out); - }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ - const void *pBlob = sqlite3_column_blob(p->pStmt, i); - int nBlob = sqlite3_column_bytes(p->pStmt, i); - output_hex_blob(p->out, pBlob, nBlob); - }else if( isNumber(azArg[i], 0) ){ - sqlite3_fputs(azArg[i], p->out); - }else{ - output_quoted_string(p, azArg[i]); - } - } - sqlite3_fputs(p->rowSeparator, p->out); - break; - } - case MODE_Ascii: { - if( p->cnt++==0 && p->showHeader ){ - for(i=0; i0 ) sqlite3_fputs(p->colSeparator, p->out); - sqlite3_fputs(azCol[i] ? azCol[i] : "", p->out); - } - sqlite3_fputs(p->rowSeparator, p->out); - } - if( azArg==0 ) break; - for(i=0; i0 ) sqlite3_fputs(p->colSeparator, p->out); - sqlite3_fputs(azArg[i] ? azArg[i] : p->nullValue, p->out); - } - sqlite3_fputs(p->rowSeparator, p->out); - break; - } - case MODE_EQP: { - eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]); - break; - } - } - return 0; -} - -/* -** This is the callback routine that the SQLite library -** invokes for each row of a query result. -*/ -static int callback(void *pArg, int nArg, char **azArg, char **azCol){ - /* since we don't have type info, call the shell_callback with a NULL value */ - return shell_callback(pArg, nArg, azArg, azCol, NULL); -} - -/* -** This is the callback routine from sqlite3_exec() that appends all -** output onto the end of a ShellText object. -*/ -static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){ - ShellText *p = (ShellText*)pArg; - int i; - UNUSED_PARAMETER(az); - if( azArg==0 ) return 0; - if( p->n ) appendText(p, "|", 0); - for(i=0; idb, - "SAVEPOINT selftest_init;\n" - "CREATE TABLE IF NOT EXISTS selftest(\n" - " tno INTEGER PRIMARY KEY,\n" /* Test number */ - " op TEXT,\n" /* Operator: memo run */ - " cmd TEXT,\n" /* Command text */ - " ans TEXT\n" /* Desired answer */ - ");" - "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n" - "INSERT INTO [_shell$self](rowid,op,cmd)\n" - " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n" - " 'memo','Tests generated by --init');\n" - "INSERT INTO [_shell$self]\n" - " SELECT 'run',\n" - " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql " - "FROM sqlite_schema ORDER BY 2'',224))',\n" - " hex(sha3_query('SELECT type,name,tbl_name,sql " - "FROM sqlite_schema ORDER BY 2',224));\n" - "INSERT INTO [_shell$self]\n" - " SELECT 'run'," - " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||" - " printf('%w',name) || '\" NOT INDEXED'',224))',\n" - " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n" - " FROM (\n" - " SELECT name FROM sqlite_schema\n" - " WHERE type='table'\n" - " AND name<>'selftest'\n" - " AND coalesce(rootpage,0)>0\n" - " )\n" - " ORDER BY name;\n" - "INSERT INTO [_shell$self]\n" - " VALUES('run','PRAGMA integrity_check','ok');\n" - "INSERT INTO selftest(tno,op,cmd,ans)" - " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n" - "DROP TABLE [_shell$self];" - ,0,0,&zErrMsg); - if( zErrMsg ){ - sqlite3_fprintf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg); - sqlite3_free(zErrMsg); - } - sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); -} - - -/* -** Set the destination table field of the ShellState structure to -** the name of the table given. Escape any quote characters in the -** table name. -*/ -static void set_table_name(ShellState *p, const char *zName){ - int i, n; - char cQuote; - char *z; - - if( p->zDestTable ){ - free(p->zDestTable); - p->zDestTable = 0; - } - if( zName==0 ) return; - cQuote = quoteChar(zName); - n = strlen30(zName); - if( cQuote ) n += n+2; - z = p->zDestTable = malloc( n+1 ); - shell_check_oom(z); - n = 0; - if( cQuote ) z[n++] = cQuote; - for(i=0; zName[i]; i++){ - z[n++] = zName[i]; - if( zName[i]==cQuote ) z[n++] = cQuote; - } - if( cQuote ) z[n++] = cQuote; - z[n] = 0; -} - -/* -** Maybe construct two lines of text that point out the position of a -** syntax error. Return a pointer to the text, in memory obtained from -** sqlite3_malloc(). Or, if the most recent error does not involve a -** specific token that we can point to, return an empty string. -** -** In all cases, the memory returned is obtained from sqlite3_malloc64() -** and should be released by the caller invoking sqlite3_free(). -*/ -static char *shell_error_context(const char *zSql, sqlite3 *db){ - int iOffset; - size_t len; - char *zCode; - char *zMsg; - int i; - if( db==0 - || zSql==0 - || (iOffset = sqlite3_error_offset(db))<0 - || iOffset>=(int)strlen(zSql) - ){ - return sqlite3_mprintf(""); - } - while( iOffset>50 ){ - iOffset--; - zSql++; - while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; } - } - len = strlen(zSql); - if( len>78 ){ - len = 78; - while( len>0 && (zSql[len]&0xc0)==0x80 ) len--; - } - zCode = sqlite3_mprintf("%.*s", len, zSql); - shell_check_oom(zCode); - for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; } - if( iOffset<25 ){ - zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode,iOffset,""); - }else{ - zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode,iOffset-14,""); - } - return zMsg; -} - - -/* -** Execute a query statement that will generate SQL output. Print -** the result columns, comma-separated, on a line and then add a -** semicolon terminator to the end of that line. -** -** If the number of columns is 1 and that column contains text "--" -** then write the semicolon on a separate line. That way, if a -** "--" comment occurs at the end of the statement, the comment -** won't consume the semicolon terminator. -*/ -static int run_table_dump_query( - ShellState *p, /* Query context */ - const char *zSelect /* SELECT statement to extract content */ -){ - sqlite3_stmt *pSelect; - int rc; - int nResult; - int i; - const char *z; - rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); - if( rc!=SQLITE_OK || !pSelect ){ - char *zContext = shell_error_context(zSelect, p->db); - sqlite3_fprintf(p->out, "/**** ERROR: (%d) %s *****/\n%s", - rc, sqlite3_errmsg(p->db), zContext); - sqlite3_free(zContext); - if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; - return rc; - } - rc = sqlite3_step(pSelect); - nResult = sqlite3_column_count(pSelect); - while( rc==SQLITE_ROW ){ - z = (const char*)sqlite3_column_text(pSelect, 0); - sqlite3_fprintf(p->out, "%s", z); - for(i=1; iout, ",%s", sqlite3_column_text(pSelect, i)); - } - if( z==0 ) z = ""; - while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; - if( z[0] ){ - sqlite3_fputs("\n;\n", p->out); - }else{ - sqlite3_fputs(";\n", p->out); - } - rc = sqlite3_step(pSelect); - } - rc = sqlite3_finalize(pSelect); - if( rc!=SQLITE_OK ){ - sqlite3_fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", - rc, sqlite3_errmsg(p->db)); - if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; - } - return rc; -} - -/* -** Allocate space and save off string indicating current error. -*/ -static char *save_err_msg( - sqlite3 *db, /* Database to query */ - const char *zPhase, /* When the error occurs */ - int rc, /* Error code returned from API */ - const char *zSql /* SQL string, or NULL */ -){ - char *zErr; - char *zContext; - sqlite3_str *pStr = sqlite3_str_new(0); - sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db)); - if( rc>1 ){ - sqlite3_str_appendf(pStr, " (%d)", rc); - } - zContext = shell_error_context(zSql, db); - if( zContext ){ - sqlite3_str_appendall(pStr, zContext); - sqlite3_free(zContext); - } - zErr = sqlite3_str_finish(pStr); - shell_check_oom(zErr); - return zErr; -} - -#ifdef __linux__ -/* -** Attempt to display I/O stats on Linux using /proc/PID/io -*/ -static void displayLinuxIoStats(FILE *out){ - FILE *in; - char z[200]; - sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); - in = sqlite3_fopen(z, "rb"); - if( in==0 ) return; - while( sqlite3_fgets(z, sizeof(z), in)!=0 ){ - static const struct { - const char *zPattern; - const char *zDesc; - } aTrans[] = { - { "rchar: ", "Bytes received by read():" }, - { "wchar: ", "Bytes sent to write():" }, - { "syscr: ", "Read() system calls:" }, - { "syscw: ", "Write() system calls:" }, - { "read_bytes: ", "Bytes read from storage:" }, - { "write_bytes: ", "Bytes written to storage:" }, - { "cancelled_write_bytes: ", "Cancelled write bytes:" }, - }; - int i; - for(i=0; i1 ){ - sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr); - }else{ - sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr); - } - sqlite3_fprintf(out, "%-36s %s\n", zLabel, zLine); -} - -/* -** Display memory stats. -*/ -static int display_stats( - sqlite3 *db, /* Database to query */ - ShellState *pArg, /* Pointer to ShellState */ - int bReset /* True to reset the stats */ -){ - int iCur; - int iHiwtr; - FILE *out; - if( pArg==0 || pArg->out==0 ) return 0; - out = pArg->out; - - if( pArg->pStmt && pArg->statsOn==2 ){ - int nCol, i, x; - sqlite3_stmt *pStmt = pArg->pStmt; - char z[100]; - nCol = sqlite3_column_count(pStmt); - sqlite3_fprintf(out, "%-36s %d\n", "Number of output columns:", nCol); - for(i=0; istatsOn==3 ){ - if( pArg->pStmt ){ - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP,bReset); - sqlite3_fprintf(out, "VM-steps: %d\n", iCur); - } - return 0; - } - - displayStatLine(out, "Memory Used:", - "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset); - displayStatLine(out, "Number of Outstanding Allocations:", - "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset); - if( pArg->shellFlgs & SHFLG_Pagecache ){ - displayStatLine(out, "Number of Pcache Pages Used:", - "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset); - } - displayStatLine(out, "Number of Pcache Overflow Bytes:", - "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset); - displayStatLine(out, "Largest Allocation:", - "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset); - displayStatLine(out, "Largest Pcache Allocation:", - "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset); -#ifdef YYTRACKMAXSTACKDEPTH - displayStatLine(out, "Deepest Parser Stack:", - "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset); -#endif - - if( db ){ - if( pArg->shellFlgs & SHFLG_Lookaside ){ - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, - &iCur, &iHiwtr, bReset); - sqlite3_fprintf(out, - "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr); - sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, - &iCur, &iHiwtr, bReset); - sqlite3_fprintf(out, - "Successful lookaside attempts: %d\n", iHiwtr); - sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, - &iCur, &iHiwtr, bReset); - sqlite3_fprintf(out, - "Lookaside failures due to size: %d\n", iHiwtr); - sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, - &iCur, &iHiwtr, bReset); - sqlite3_fprintf(out, - "Lookaside failures due to OOM: %d\n", iHiwtr); - } - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); - sqlite3_fprintf(out, - "Pager Heap Usage: %d bytes\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); - sqlite3_fprintf(out, - "Page cache hits: %d\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); - sqlite3_fprintf(out, - "Page cache misses: %d\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); - sqlite3_fprintf(out, - "Page cache writes: %d\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1); - sqlite3_fprintf(out, - "Page cache spills: %d\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); - sqlite3_fprintf(out, - "Schema Heap Usage: %d bytes\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); - sqlite3_fprintf(out, - "Statement Heap/Lookaside Usage: %d bytes\n", iCur); - } - - if( pArg->pStmt ){ - int iHit, iMiss; - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, - bReset); - sqlite3_fprintf(out, - "Fullscan Steps: %d\n", iCur); - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); - sqlite3_fprintf(out, - "Sort Operations: %d\n", iCur); - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); - sqlite3_fprintf(out, - "Autoindex Inserts: %d\n", iCur); - iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, - bReset); - iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, - bReset); - if( iHit || iMiss ){ - sqlite3_fprintf(out, - "Bloom filter bypass taken: %d/%d\n", iHit, iHit+iMiss); - } - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); - sqlite3_fprintf(out, - "Virtual Machine Steps: %d\n", iCur); - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset); - sqlite3_fprintf(out, - "Reprepare operations: %d\n", iCur); - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); - sqlite3_fprintf(out, - "Number of times run: %d\n", iCur); - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); - sqlite3_fprintf(out, - "Memory used by prepared stmt: %d\n", iCur); - } - -#ifdef __linux__ - displayLinuxIoStats(pArg->out); -#endif - - /* Do not remove this machine readable comment: extra-stats-output-here */ - - return 0; -} - - -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS -static int scanStatsHeight(sqlite3_stmt *p, int iEntry){ - int iPid = 0; - int ret = 1; - sqlite3_stmt_scanstatus_v2(p, iEntry, - SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid - ); - while( iPid!=0 ){ - int ii; - for(ii=0; 1; ii++){ - int iId; - int res; - res = sqlite3_stmt_scanstatus_v2(p, ii, - SQLITE_SCANSTAT_SELECTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iId - ); - if( res ) break; - if( iId==iPid ){ - sqlite3_stmt_scanstatus_v2(p, ii, - SQLITE_SCANSTAT_PARENTID, SQLITE_SCANSTAT_COMPLEX, (void*)&iPid - ); - } - } - ret++; - } - return ret; -} -#endif - -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS -static void display_explain_scanstats( - sqlite3 *db, /* Database to query */ - ShellState *pArg /* Pointer to ShellState */ -){ - static const int f = SQLITE_SCANSTAT_COMPLEX; - sqlite3_stmt *p = pArg->pStmt; - int ii = 0; - i64 nTotal = 0; - int nWidth = 0; - eqp_reset(pArg); - - for(ii=0; 1; ii++){ - const char *z = 0; - int n = 0; - if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&z) ){ - break; - } - n = (int)strlen(z) + scanStatsHeight(p, ii)*3; - if( n>nWidth ) nWidth = n; - } - nWidth += 4; - - sqlite3_stmt_scanstatus_v2(p, -1, SQLITE_SCANSTAT_NCYCLE, f, (void*)&nTotal); - for(ii=0; 1; ii++){ - i64 nLoop = 0; - i64 nRow = 0; - i64 nCycle = 0; - int iId = 0; - int iPid = 0; - const char *zo = 0; - const char *zName = 0; - char *zText = 0; - double rEst = 0.0; - - if( sqlite3_stmt_scanstatus_v2(p,ii,SQLITE_SCANSTAT_EXPLAIN,f,(void*)&zo) ){ - break; - } - sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_EST,f,(void*)&rEst); - sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NLOOP,f,(void*)&nLoop); - sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NVISIT,f,(void*)&nRow); - sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NCYCLE,f,(void*)&nCycle); - sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_SELECTID,f,(void*)&iId); - sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_PARENTID,f,(void*)&iPid); - sqlite3_stmt_scanstatus_v2(p, ii, SQLITE_SCANSTAT_NAME,f,(void*)&zName); - - zText = sqlite3_mprintf("%s", zo); - if( nCycle>=0 || nLoop>=0 || nRow>=0 ){ - char *z = 0; - if( nCycle>=0 && nTotal>0 ){ - z = sqlite3_mprintf("%zcycles=%lld [%d%%]", z, - nCycle, ((nCycle*100)+nTotal/2) / nTotal - ); - } - if( nLoop>=0 ){ - z = sqlite3_mprintf("%z%sloops=%lld", z, z ? " " : "", nLoop); - } - if( nRow>=0 ){ - z = sqlite3_mprintf("%z%srows=%lld", z, z ? " " : "", nRow); - } - - if( zName && pArg->scanstatsOn>1 ){ - double rpl = (double)nRow / (double)nLoop; - z = sqlite3_mprintf("%z rpl=%.1f est=%.1f", z, rpl, rEst); - } - - zText = sqlite3_mprintf( - "% *z (%z)", -1*(nWidth-scanStatsHeight(p, ii)*3), zText, z - ); - } - - eqp_append(pArg, iId, iPid, zText); - sqlite3_free(zText); - } - - eqp_render(pArg, nTotal); -} -#endif - - -/* -** Parameter azArray points to a zero-terminated array of strings. zStr -** points to a single nul-terminated string. Return non-zero if zStr -** is equal, according to strcmp(), to any of the strings in the array. -** Otherwise, return zero. -*/ -static int str_in_array(const char *zStr, const char **azArray){ - int i; - for(i=0; azArray[i]; i++){ - if( 0==cli_strcmp(zStr, azArray[i]) ) return 1; - } - return 0; -} - -/* -** If compiled statement pSql appears to be an EXPLAIN statement, allocate -** and populate the ShellState.aiIndent[] array with the number of -** spaces each opcode should be indented before it is output. -** -** The indenting rules are: -** -** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent -** all opcodes that occur between the p2 jump destination and the opcode -** itself by 2 spaces. -** -** * Do the previous for "Return" instructions for when P2 is positive. -** See tag-20220407a in wherecode.c and vdbe.c. -** -** * For each "Goto", if the jump destination is earlier in the program -** and ends on one of: -** Yield SeekGt SeekLt RowSetRead Rewind -** or if the P1 parameter is one instead of zero, -** then indent all opcodes between the earlier instruction -** and "Goto" by 2 spaces. -*/ -static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){ - int *abYield = 0; /* True if op is an OP_Yield */ - int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ - int iOp; /* Index of operation in p->aiIndent[] */ - - const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", - "Return", 0 }; - const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", - "Rewind", 0 }; - const char *azGoto[] = { "Goto", 0 }; - - /* The caller guarantees that the leftmost 4 columns of the statement - ** passed to this function are equivalent to the leftmost 4 columns - ** of EXPLAIN statement output. In practice the statement may be - ** an EXPLAIN, or it may be a query on the bytecode() virtual table. */ - assert( sqlite3_column_count(pSql)>=4 ); - assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 0), "addr" ) ); - assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 1), "opcode" ) ); - assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 2), "p1" ) ); - assert( 0==sqlite3_stricmp( sqlite3_column_name(pSql, 3), "p2" ) ); - - for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ - int i; - int iAddr = sqlite3_column_int(pSql, 0); - const char *zOp = (const char*)sqlite3_column_text(pSql, 1); - int p1 = sqlite3_column_int(pSql, 2); - int p2 = sqlite3_column_int(pSql, 3); - - /* Assuming that p2 is an instruction address, set variable p2op to the - ** index of that instruction in the aiIndent[] array. p2 and p2op may be - ** different if the current instruction is part of a sub-program generated - ** by an SQL trigger or foreign key. */ - int p2op = (p2 + (iOp-iAddr)); - - /* Grow the p->aiIndent array as required */ - if( iOp>=nAlloc ){ - nAlloc += 100; - p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); - shell_check_oom(p->aiIndent); - abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int)); - shell_check_oom(abYield); - } - - abYield[iOp] = str_in_array(zOp, azYield); - p->aiIndent[iOp] = 0; - p->nIndent = iOp+1; - if( str_in_array(zOp, azNext) && p2op>0 ){ - for(i=p2op; iaiIndent[i] += 2; - } - if( str_in_array(zOp, azGoto) && p2opaiIndent[i] += 2; - } - } - - p->iIndent = 0; - sqlite3_free(abYield); - sqlite3_reset(pSql); -} - -/* -** Free the array allocated by explain_data_prepare(). -*/ -static void explain_data_delete(ShellState *p){ - sqlite3_free(p->aiIndent); - p->aiIndent = 0; - p->nIndent = 0; - p->iIndent = 0; -} - -static void exec_prepared_stmt(ShellState*, sqlite3_stmt*); - -/* -** Display scan stats. -*/ -static void display_scanstats( - sqlite3 *db, /* Database to query */ - ShellState *pArg /* Pointer to ShellState */ -){ -#ifndef SQLITE_ENABLE_STMT_SCANSTATUS - UNUSED_PARAMETER(db); - UNUSED_PARAMETER(pArg); -#else - if( pArg->scanstatsOn==3 ){ - const char *zSql = - " SELECT addr, opcode, p1, p2, p3, p4, p5, comment, nexec," - " format('% 6s (%.2f%%)'," - " CASE WHEN ncycle<100_000 THEN ncycle || ' '" - " WHEN ncycle<100_000_000 THEN (ncycle/1_000) || 'K'" - " WHEN ncycle<100_000_000_000 THEN (ncycle/1_000_000) || 'M'" - " ELSE (ncycle/1000_000_000) || 'G' END," - " ncycle*100.0/(sum(ncycle) OVER ())" - " ) AS cycles" - " FROM bytecode(?)"; - - int rc = SQLITE_OK; - sqlite3_stmt *pStmt = 0; - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - if( rc==SQLITE_OK ){ - sqlite3_stmt *pSave = pArg->pStmt; - pArg->pStmt = pStmt; - sqlite3_bind_pointer(pStmt, 1, pSave, "stmt-pointer", 0); - - pArg->cnt = 0; - pArg->cMode = MODE_ScanExp; - explain_data_prepare(pArg, pStmt); - exec_prepared_stmt(pArg, pStmt); - explain_data_delete(pArg); - - sqlite3_finalize(pStmt); - pArg->pStmt = pSave; - } - }else{ - display_explain_scanstats(db, pArg); - } -#endif -} - -/* -** Disable and restore .wheretrace and .treetrace/.selecttrace settings. -*/ -static unsigned int savedSelectTrace; -static unsigned int savedWhereTrace; -static void disable_debug_trace_modes(void){ - unsigned int zero = 0; - sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace); - sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero); - sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace); - sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero); -} -static void restore_debug_trace_modes(void){ - sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace); - sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace); -} - -/* Create the TEMP table used to store parameter bindings */ -static void bind_table_init(ShellState *p){ - int wrSchema = 0; - int defensiveMode = 0; - sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode); - sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0); - sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); - sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); - sqlite3_exec(p->db, - "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n" - " key TEXT PRIMARY KEY,\n" - " value\n" - ") WITHOUT ROWID;", - 0, 0, 0); - sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); - sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0); -} - -/* -** Bind parameters on a prepared statement. -** -** Parameter bindings are taken from a TEMP table of the form: -** -** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value) -** WITHOUT ROWID; -** -** No bindings occur if this table does not exist. The name of the table -** begins with "sqlite_" so that it will not collide with ordinary application -** tables. The table must be in the TEMP schema. -*/ -static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){ - int nVar; - int i; - int rc; - sqlite3_stmt *pQ = 0; - - nVar = sqlite3_bind_parameter_count(pStmt); - if( nVar==0 ) return; /* Nothing to do */ - if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters", - "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){ - rc = SQLITE_NOTFOUND; - pQ = 0; - }else{ - rc = sqlite3_prepare_v2(pArg->db, - "SELECT value FROM temp.sqlite_parameters" - " WHERE key=?1", -1, &pQ, 0); - } - for(i=1; i<=nVar; i++){ - char zNum[30]; - const char *zVar = sqlite3_bind_parameter_name(pStmt, i); - if( zVar==0 ){ - sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i); - zVar = zNum; - } - sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); - if( rc==SQLITE_OK && pQ && sqlite3_step(pQ)==SQLITE_ROW ){ - sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0)); -#ifdef NAN - }else if( sqlite3_strlike("_NAN", zVar, 0)==0 ){ - sqlite3_bind_double(pStmt, i, NAN); -#endif -#ifdef INFINITY - }else if( sqlite3_strlike("_INF", zVar, 0)==0 ){ - sqlite3_bind_double(pStmt, i, INFINITY); -#endif - }else if( strncmp(zVar, "$int_", 5)==0 ){ - sqlite3_bind_int(pStmt, i, atoi(&zVar[5])); - }else if( strncmp(zVar, "$text_", 6)==0 ){ - size_t szVar = strlen(zVar); - char *zBuf = sqlite3_malloc64( szVar-5 ); - if( zBuf ){ - memcpy(zBuf, &zVar[6], szVar-5); - sqlite3_bind_text64(pStmt, i, zBuf, szVar-6, sqlite3_free, SQLITE_UTF8); - } - }else{ - sqlite3_bind_null(pStmt, i); - } - sqlite3_reset(pQ); - } - sqlite3_finalize(pQ); -} - -/* -** UTF8 box-drawing characters. Imagine box lines like this: -** -** 1 -** | -** 4 --+-- 2 -** | -** 3 -** -** Each box characters has between 2 and 4 of the lines leading from -** the center. The characters are here identified by the numbers of -** their corresponding lines. -*/ -#define BOX_24 "\342\224\200" /* U+2500 --- */ -#define BOX_13 "\342\224\202" /* U+2502 | */ -#define BOX_23 "\342\224\214" /* U+250c ,- */ -#define BOX_34 "\342\224\220" /* U+2510 -, */ -#define BOX_12 "\342\224\224" /* U+2514 '- */ -#define BOX_14 "\342\224\230" /* U+2518 -' */ -#define BOX_123 "\342\224\234" /* U+251c |- */ -#define BOX_134 "\342\224\244" /* U+2524 -| */ -#define BOX_234 "\342\224\254" /* U+252c -,- */ -#define BOX_124 "\342\224\264" /* U+2534 -'- */ -#define BOX_1234 "\342\224\274" /* U+253c -|- */ - -/* Draw horizontal line N characters long using unicode box -** characters -*/ -static void print_box_line(FILE *out, int N){ - const char zDash[] = - BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 - BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24; - const int nDash = sizeof(zDash) - 1; - N *= 3; - while( N>nDash ){ - sqlite3_fputs(zDash, out); - N -= nDash; - } - sqlite3_fprintf(out, "%.*s", N, zDash); -} - -/* -** Draw a horizontal separator for a MODE_Box table. -*/ -static void print_box_row_separator( - ShellState *p, - int nArg, - const char *zSep1, - const char *zSep2, - const char *zSep3 -){ - int i; - if( nArg>0 ){ - sqlite3_fputs(zSep1, p->out); - print_box_line(p->out, p->actualWidth[0]+2); - for(i=1; iout); - print_box_line(p->out, p->actualWidth[i]+2); - } - sqlite3_fputs(zSep3, p->out); - } - sqlite3_fputs("\n", p->out); -} - -/* -** z[] is a line of text that is to be displayed the .mode box or table or -** similar tabular formats. z[] might contain control characters such -** as \n, \t, \f, or \r. -** -** Compute characters to display on the first line of z[]. Stop at the -** first \r, \n, or \f. Expand \t into spaces. Return a copy (obtained -** from malloc()) of that first line, which caller should free sometime. -** Write anything to display on the next line into *pzTail. If this is -** the last line, write a NULL into *pzTail. (*pzTail is not allocated.) -*/ -static char *translateForDisplayAndDup( - const unsigned char *z, /* Input text to be transformed */ - const unsigned char **pzTail, /* OUT: Tail of the input for next line */ - int mxWidth, /* Max width. 0 means no limit */ - u8 bWordWrap /* If true, avoid breaking mid-word */ -){ - int i; /* Input bytes consumed */ - int j; /* Output bytes generated */ - int k; /* Input bytes to be displayed */ - int n; /* Output column number */ - unsigned char *zOut; /* Output text */ - - if( z==0 ){ - *pzTail = 0; - return 0; - } - if( mxWidth<0 ) mxWidth = -mxWidth; - if( mxWidth==0 ) mxWidth = 1000000; - i = j = n = 0; - while( n=0xc0 ){ - int u; - int len = decodeUtf8(&z[i], &u); - i += len; - j += len; - n += cli_wcwidth(u); - continue; - } - if( c>=' ' ){ - n++; - i++; - j++; - continue; - } - if( c=='\t' ){ - do{ - n++; - j++; - }while( (n&7)!=0 && n=mxWidth && bWordWrap ){ - /* Perhaps try to back up to a better place to break the line */ - for(k=i; k>i/2; k--){ - if( isspace(z[k-1]) ) break; - } - if( k<=i/2 ){ - for(k=i; k>i/2; k--){ - if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break; - } - } - if( k<=i/2 ){ - k = i; - }else{ - i = k; - while( z[i]==' ' ) i++; - } - }else{ - k = i; - } - if( n>=mxWidth && z[i]>=' ' ){ - *pzTail = &z[i]; - }else if( z[i]=='\r' && z[i+1]=='\n' ){ - *pzTail = z[i+2] ? &z[i+2] : 0; - }else if( z[i]==0 || z[i+1]==0 ){ - *pzTail = 0; - }else{ - *pzTail = &z[i+1]; - } - zOut = malloc( j+1 ); - shell_check_oom(zOut); - i = j = n = 0; - while( i=0xc0 ){ - int u; - int len = decodeUtf8(&z[i], &u); - do{ zOut[j++] = z[i++]; }while( (--len)>0 ); - n += cli_wcwidth(u); - continue; - } - if( c>=' ' ){ - n++; - zOut[j++] = z[i++]; - continue; - } - if( z[i]=='\t' ){ - do{ - n++; - zOut[j++] = ' '; - }while( (n&7)!=0 && ncmOpts.bWordWrap; - const char *zEmpty = ""; - const char *zShowNull = p->nullValue; - - rc = sqlite3_step(pStmt); - if( rc!=SQLITE_ROW ) return; - nColumn = sqlite3_column_count(pStmt); - if( nColumn==0 ) goto columnar_end; - nAlloc = nColumn*4; - if( nAlloc<=0 ) nAlloc = 1; - azData = sqlite3_malloc64( nAlloc*sizeof(char*) ); - shell_check_oom(azData); - azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) ); - shell_check_oom(azNextLine); - memset((void*)azNextLine, 0, nColumn*sizeof(char*) ); - if( p->cmOpts.bQuote ){ - azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) ); - shell_check_oom(azQuoted); - memset(azQuoted, 0, nColumn*sizeof(char*) ); - } - abRowDiv = sqlite3_malloc64( nAlloc/nColumn ); - shell_check_oom(abRowDiv); - if( nColumn>p->nWidth ){ - p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int)); - shell_check_oom(p->colWidth); - for(i=p->nWidth; icolWidth[i] = 0; - p->nWidth = nColumn; - p->actualWidth = &p->colWidth[nColumn]; - } - memset(p->actualWidth, 0, nColumn*sizeof(int)); - for(i=0; icolWidth[i]; - if( w<0 ) w = -w; - p->actualWidth[i] = w; - } - for(i=0; icolWidth[i]; - if( wx==0 ){ - wx = p->cmOpts.iWrap; - } - if( wx<0 ) wx = -wx; - uz = (const unsigned char*)sqlite3_column_name(pStmt,i); - if( uz==0 ) uz = (u8*)""; - azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw); - } - do{ - int useNextLine = bNextLine; - bNextLine = 0; - if( (nRow+2)*nColumn >= nAlloc ){ - nAlloc *= 2; - azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*)); - shell_check_oom(azData); - abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn); - shell_check_oom(abRowDiv); - } - abRowDiv[nRow] = 1; - nRow++; - for(i=0; icolWidth[i]; - if( wx==0 ){ - wx = p->cmOpts.iWrap; - } - if( wx<0 ) wx = -wx; - if( useNextLine ){ - uz = azNextLine[i]; - if( uz==0 ) uz = (u8*)zEmpty; - }else if( p->cmOpts.bQuote ){ - sqlite3_free(azQuoted[i]); - azQuoted[i] = quoted_column(pStmt,i); - uz = (const unsigned char*)azQuoted[i]; - }else{ - uz = (const unsigned char*)sqlite3_column_text(pStmt,i); - if( uz==0 ) uz = (u8*)zShowNull; - } - azData[nRow*nColumn + i] - = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw); - if( azNextLine[i] ){ - bNextLine = 1; - abRowDiv[nRow-1] = 0; - bMultiLineRowExists = 1; - } - } - }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW ); - nTotal = nColumn*(nRow+1); - for(i=0; ip->actualWidth[j] ) p->actualWidth[j] = n; - } - if( seenInterrupt ) goto columnar_end; - switch( p->cMode ){ - case MODE_Column: { - colSep = " "; - rowSep = "\n"; - if( p->showHeader ){ - for(i=0; iactualWidth[i]; - if( p->colWidth[i]<0 ) w = -w; - utf8_width_print(p->out, w, azData[i]); - sqlite3_fputs(i==nColumn-1?"\n":" ", p->out); - } - for(i=0; iout, p->actualWidth[i]); - sqlite3_fputs(i==nColumn-1?"\n":" ", p->out); - } - } - break; - } - case MODE_Table: { - colSep = " | "; - rowSep = " |\n"; - print_row_separator(p, nColumn, "+"); - sqlite3_fputs("| ", p->out); - for(i=0; iactualWidth[i]; - n = strlenChar(azData[i]); - sqlite3_fprintf(p->out, "%*s%s%*s", (w-n)/2, "", - azData[i], (w-n+1)/2, ""); - sqlite3_fputs(i==nColumn-1?" |\n":" | ", p->out); - } - print_row_separator(p, nColumn, "+"); - break; - } - case MODE_Markdown: { - colSep = " | "; - rowSep = " |\n"; - sqlite3_fputs("| ", p->out); - for(i=0; iactualWidth[i]; - n = strlenChar(azData[i]); - sqlite3_fprintf(p->out, "%*s%s%*s", (w-n)/2, "", - azData[i], (w-n+1)/2, ""); - sqlite3_fputs(i==nColumn-1?" |\n":" | ", p->out); - } - print_row_separator(p, nColumn, "|"); - break; - } - case MODE_Box: { - colSep = " " BOX_13 " "; - rowSep = " " BOX_13 "\n"; - print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34); - sqlite3_fputs(BOX_13 " ", p->out); - for(i=0; iactualWidth[i]; - n = strlenChar(azData[i]); - sqlite3_fprintf(p->out, "%*s%s%*s%s", - (w-n)/2, "", azData[i], (w-n+1)/2, "", - i==nColumn-1?" "BOX_13"\n":" "BOX_13" "); - } - print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134); - break; - } - } - for(i=nColumn, j=0; icMode!=MODE_Column ){ - sqlite3_fputs(p->cMode==MODE_Box?BOX_13" ":"| ", p->out); - } - z = azData[i]; - if( z==0 ) z = p->nullValue; - w = p->actualWidth[j]; - if( p->colWidth[j]<0 ) w = -w; - utf8_width_print(p->out, w, z); - if( j==nColumn-1 ){ - sqlite3_fputs(rowSep, p->out); - if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1cMode==MODE_Table ){ - print_row_separator(p, nColumn, "+"); - }else if( p->cMode==MODE_Box ){ - print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134); - }else if( p->cMode==MODE_Column ){ - sqlite3_fputs("\n", p->out); - } - } - j = -1; - if( seenInterrupt ) goto columnar_end; - }else{ - sqlite3_fputs(colSep, p->out); - } - } - if( p->cMode==MODE_Table ){ - print_row_separator(p, nColumn, "+"); - }else if( p->cMode==MODE_Box ){ - print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14); - } -columnar_end: - if( seenInterrupt ){ - sqlite3_fputs("Interrupt\n", p->out); - } - nData = (nRow+1)*nColumn; - for(i=0; icMode==MODE_Column - || pArg->cMode==MODE_Table - || pArg->cMode==MODE_Box - || pArg->cMode==MODE_Markdown - ){ - exec_prepared_stmt_columnar(pArg, pStmt); - return; - } - - /* perform the first step. this will tell us if we - ** have a result set or not and how wide it is. - */ - rc = sqlite3_step(pStmt); - /* if we have a result set... */ - if( SQLITE_ROW == rc ){ - /* allocate space for col name ptr, value ptr, and type */ - int nCol = sqlite3_column_count(pStmt); - void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1); - if( !pData ){ - shell_out_of_memory(); - }else{ - char **azCols = (char **)pData; /* Names of result columns */ - char **azVals = &azCols[nCol]; /* Results */ - int *aiTypes = (int *)&azVals[nCol]; /* Result types */ - int i, x; - assert(sizeof(int) <= sizeof(char *)); - /* save off ptrs to column names */ - for(i=0; icMode==MODE_Insert || pArg->cMode==MODE_Quote) - ){ - azVals[i] = ""; - }else{ - azVals[i] = (char*)sqlite3_column_text(pStmt, i); - } - if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ - rc = SQLITE_NOMEM; - break; /* from for */ - } - } /* end for */ - - /* if data and types extracted successfully... */ - if( SQLITE_ROW == rc ){ - /* call the supplied callback with the result row data */ - if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){ - rc = SQLITE_ABORT; - }else{ - rc = sqlite3_step(pStmt); - } - } - } while( SQLITE_ROW == rc ); - sqlite3_free(pData); - if( pArg->cMode==MODE_Json ){ - sqlite3_fputs("]\n", pArg->out); - }else if( pArg->cMode==MODE_Www ){ - sqlite3_fputs("
\n